View.java revision 08ca2e3a7593ced4967c56709a1fe675408d42dc
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.IntRange;
28import android.annotation.LayoutRes;
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.annotation.Size;
32import android.annotation.UiThread;
33import android.content.ClipData;
34import android.content.Context;
35import android.content.ContextWrapper;
36import android.content.Intent;
37import android.content.res.ColorStateList;
38import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Insets;
44import android.graphics.Interpolator;
45import android.graphics.LinearGradient;
46import android.graphics.Matrix;
47import android.graphics.Outline;
48import android.graphics.Paint;
49import android.graphics.PixelFormat;
50import android.graphics.Point;
51import android.graphics.PorterDuff;
52import android.graphics.PorterDuffXfermode;
53import android.graphics.Rect;
54import android.graphics.RectF;
55import android.graphics.Region;
56import android.graphics.Shader;
57import android.graphics.drawable.ColorDrawable;
58import android.graphics.drawable.Drawable;
59import android.hardware.display.DisplayManagerGlobal;
60import android.os.Build.VERSION_CODES;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Parcel;
65import android.os.Parcelable;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.SystemProperties;
69import android.os.Trace;
70import android.text.TextUtils;
71import android.util.AttributeSet;
72import android.util.FloatProperty;
73import android.util.LayoutDirection;
74import android.util.Log;
75import android.util.LongSparseLongArray;
76import android.util.Pools.SynchronizedPool;
77import android.util.Property;
78import android.util.SparseArray;
79import android.util.StateSet;
80import android.util.SuperNotCalledException;
81import android.util.TypedValue;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.AccessibilityIterators.TextSegmentIterator;
86import android.view.AccessibilityIterators.WordTextSegmentIterator;
87import android.view.accessibility.AccessibilityEvent;
88import android.view.accessibility.AccessibilityEventSource;
89import android.view.accessibility.AccessibilityManager;
90import android.view.accessibility.AccessibilityNodeInfo;
91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
92import android.view.accessibility.AccessibilityNodeProvider;
93import android.view.animation.Animation;
94import android.view.animation.AnimationUtils;
95import android.view.animation.Transformation;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputConnection;
98import android.view.inputmethod.InputMethodManager;
99import android.widget.Checkable;
100import android.widget.FrameLayout;
101import android.widget.ScrollBarDrawable;
102import static android.os.Build.VERSION_CODES.*;
103import static java.lang.Math.max;
104
105import com.android.internal.R;
106import com.android.internal.util.Predicate;
107import com.android.internal.view.menu.MenuBuilder;
108import com.android.internal.widget.ScrollBarUtils;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.NullPointerException;
113import java.lang.annotation.Retention;
114import java.lang.annotation.RetentionPolicy;
115import java.lang.ref.WeakReference;
116import java.lang.reflect.Field;
117import java.lang.reflect.InvocationTargetException;
118import java.lang.reflect.Method;
119import java.lang.reflect.Modifier;
120import java.util.ArrayList;
121import java.util.Arrays;
122import java.util.Collections;
123import java.util.HashMap;
124import java.util.List;
125import java.util.Locale;
126import java.util.Map;
127import java.util.concurrent.CopyOnWriteArrayList;
128import java.util.concurrent.atomic.AtomicInteger;
129
130/**
131 * <p>
132 * This class represents the basic building block for user interface components. A View
133 * occupies a rectangular area on the screen and is responsible for drawing and
134 * event handling. View is the base class for <em>widgets</em>, which are
135 * used to create interactive UI components (buttons, text fields, etc.). The
136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
137 * are invisible containers that hold other Views (or other ViewGroups) and define
138 * their layout properties.
139 * </p>
140 *
141 * <div class="special reference">
142 * <h3>Developer Guides</h3>
143 * <p>For information about using this class to develop your application's user interface,
144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
145 * </div>
146 *
147 * <a name="Using"></a>
148 * <h3>Using Views</h3>
149 * <p>
150 * All of the views in a window are arranged in a single tree. You can add views
151 * either from code or by specifying a tree of views in one or more XML layout
152 * files. There are many specialized subclasses of views that act as controls or
153 * are capable of displaying text, images, or other content.
154 * </p>
155 * <p>
156 * Once you have created a tree of views, there are typically a few types of
157 * common operations you may wish to perform:
158 * <ul>
159 * <li><strong>Set properties:</strong> for example setting the text of a
160 * {@link android.widget.TextView}. The available properties and the methods
161 * that set them will vary among the different subclasses of views. Note that
162 * properties that are known at build time can be set in the XML layout
163 * files.</li>
164 * <li><strong>Set focus:</strong> The framework will handle moving focus in
165 * response to user input. To force focus to a specific view, call
166 * {@link #requestFocus}.</li>
167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
168 * that will be notified when something interesting happens to the view. For
169 * example, all views will let you set a listener to be notified when the view
170 * gains or loses focus. You can register such a listener using
171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
172 * Other view subclasses offer more specialized listeners. For example, a Button
173 * exposes a listener to notify clients when the button is clicked.</li>
174 * <li><strong>Set visibility:</strong> You can hide or show views using
175 * {@link #setVisibility(int)}.</li>
176 * </ul>
177 * </p>
178 * <p><em>
179 * Note: The Android framework is responsible for measuring, laying out and
180 * drawing views. You should not call methods that perform these actions on
181 * views yourself unless you are actually implementing a
182 * {@link android.view.ViewGroup}.
183 * </em></p>
184 *
185 * <a name="Lifecycle"></a>
186 * <h3>Implementing a Custom View</h3>
187 *
188 * <p>
189 * To implement a custom view, you will usually begin by providing overrides for
190 * some of the standard methods that the framework calls on all views. You do
191 * not need to override all of these methods. In fact, you can start by just
192 * overriding {@link #onDraw(android.graphics.Canvas)}.
193 * <table border="2" width="85%" align="center" cellpadding="5">
194 *     <thead>
195 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
196 *     </thead>
197 *
198 *     <tbody>
199 *     <tr>
200 *         <td rowspan="2">Creation</td>
201 *         <td>Constructors</td>
202 *         <td>There is a form of the constructor that are called when the view
203 *         is created from code and a form that is called when the view is
204 *         inflated from a layout file. The second form should parse and apply
205 *         any attributes defined in the layout file.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onFinishInflate()}</code></td>
210 *         <td>Called after a view and all of its children has been inflated
211 *         from XML.</td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td rowspan="3">Layout</td>
216 *         <td><code>{@link #onMeasure(int, int)}</code></td>
217 *         <td>Called to determine the size requirements for this view and all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
223 *         <td>Called when this view should assign a size and position to all
224 *         of its children.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
229 *         <td>Called when the size of this view has changed.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td>Drawing</td>
235 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
236 *         <td>Called when the view should render its content.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="4">Event processing</td>
242 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
243 *         <td>Called when a new hardware key event occurs.
244 *         </td>
245 *     </tr>
246 *     <tr>
247 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
248 *         <td>Called when a hardware key up event occurs.
249 *         </td>
250 *     </tr>
251 *     <tr>
252 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
253 *         <td>Called when a trackball motion event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
258 *         <td>Called when a touch screen motion event occurs.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td rowspan="2">Focus</td>
264 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
265 *         <td>Called when the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
271 *         <td>Called when the window containing the view gains or loses focus.
272 *         </td>
273 *     </tr>
274 *
275 *     <tr>
276 *         <td rowspan="3">Attaching</td>
277 *         <td><code>{@link #onAttachedToWindow()}</code></td>
278 *         <td>Called when the view is attached to a window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onDetachedFromWindow}</code></td>
284 *         <td>Called when the view is detached from its window.
285 *         </td>
286 *     </tr>
287 *
288 *     <tr>
289 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
290 *         <td>Called when the visibility of the window containing the view
291 *         has changed.
292 *         </td>
293 *     </tr>
294 *     </tbody>
295 *
296 * </table>
297 * </p>
298 *
299 * <a name="IDs"></a>
300 * <h3>IDs</h3>
301 * Views may have an integer id associated with them. These ids are typically
302 * assigned in the layout XML files, and are used to find specific views within
303 * the view tree. A common pattern is to:
304 * <ul>
305 * <li>Define a Button in the layout file and assign it a unique ID.
306 * <pre>
307 * &lt;Button
308 *     android:id="@+id/my_button"
309 *     android:layout_width="wrap_content"
310 *     android:layout_height="wrap_content"
311 *     android:text="@string/my_button_text"/&gt;
312 * </pre></li>
313 * <li>From the onCreate method of an Activity, find the Button
314 * <pre class="prettyprint">
315 *      Button myButton = (Button) findViewById(R.id.my_button);
316 * </pre></li>
317 * </ul>
318 * <p>
319 * View IDs need not be unique throughout the tree, but it is good practice to
320 * ensure that they are at least unique within the part of the tree you are
321 * searching.
322 * </p>
323 *
324 * <a name="Position"></a>
325 * <h3>Position</h3>
326 * <p>
327 * The geometry of a view is that of a rectangle. A view has a location,
328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
329 * two dimensions, expressed as a width and a height. The unit for location
330 * and dimensions is the pixel.
331 * </p>
332 *
333 * <p>
334 * It is possible to retrieve the location of a view by invoking the methods
335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
336 * coordinate of the rectangle representing the view. The latter returns the
337 * top, or Y, coordinate of the rectangle representing the view. These methods
338 * both return the location of the view relative to its parent. For instance,
339 * when getLeft() returns 20, that means the view is located 20 pixels to the
340 * right of the left edge of its direct parent.
341 * </p>
342 *
343 * <p>
344 * In addition, several convenience methods are offered to avoid unnecessary
345 * computations, namely {@link #getRight()} and {@link #getBottom()}.
346 * These methods return the coordinates of the right and bottom edges of the
347 * rectangle representing the view. For instance, calling {@link #getRight()}
348 * is similar to the following computation: <code>getLeft() + getWidth()</code>
349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
350 * </p>
351 *
352 * <a name="SizePaddingMargins"></a>
353 * <h3>Size, padding and margins</h3>
354 * <p>
355 * The size of a view is expressed with a width and a height. A view actually
356 * possess two pairs of width and height values.
357 * </p>
358 *
359 * <p>
360 * The first pair is known as <em>measured width</em> and
361 * <em>measured height</em>. These dimensions define how big a view wants to be
362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
364 * and {@link #getMeasuredHeight()}.
365 * </p>
366 *
367 * <p>
368 * The second pair is simply known as <em>width</em> and <em>height</em>, or
369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
370 * dimensions define the actual size of the view on screen, at drawing time and
371 * after layout. These values may, but do not have to, be different from the
372 * measured width and height. The width and height can be obtained by calling
373 * {@link #getWidth()} and {@link #getHeight()}.
374 * </p>
375 *
376 * <p>
377 * To measure its dimensions, a view takes into account its padding. The padding
378 * is expressed in pixels for the left, top, right and bottom parts of the view.
379 * Padding can be used to offset the content of the view by a specific amount of
380 * pixels. For instance, a left padding of 2 will push the view's content by
381 * 2 pixels to the right of the left edge. Padding can be set using the
382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
385 * {@link #getPaddingEnd()}.
386 * </p>
387 *
388 * <p>
389 * Even though a view can define a padding, it does not provide any support for
390 * margins. However, view groups provide such a support. Refer to
391 * {@link android.view.ViewGroup} and
392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
393 * </p>
394 *
395 * <a name="Layout"></a>
396 * <h3>Layout</h3>
397 * <p>
398 * Layout is a two pass process: a measure pass and a layout pass. The measuring
399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
400 * of the view tree. Each view pushes dimension specifications down the tree
401 * during the recursion. At the end of the measure pass, every view has stored
402 * its measurements. The second pass happens in
403 * {@link #layout(int,int,int,int)} and is also top-down. During
404 * this pass each parent is responsible for positioning all of its children
405 * using the sizes computed in the measure pass.
406 * </p>
407 *
408 * <p>
409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
410 * {@link #getMeasuredHeight()} values must be set, along with those for all of
411 * that view's descendants. A view's measured width and measured height values
412 * must respect the constraints imposed by the view's parents. This guarantees
413 * that at the end of the measure pass, all parents accept all of their
414 * children's measurements. A parent view may call measure() more than once on
415 * its children. For example, the parent may measure each child once with
416 * unspecified dimensions to find out how big they want to be, then call
417 * measure() on them again with actual numbers if the sum of all the children's
418 * unconstrained sizes is too big or too small.
419 * </p>
420 *
421 * <p>
422 * The measure pass uses two classes to communicate dimensions. The
423 * {@link MeasureSpec} class is used by views to tell their parents how they
424 * want to be measured and positioned. The base LayoutParams class just
425 * describes how big the view wants to be for both width and height. For each
426 * dimension, it can specify one of:
427 * <ul>
428 * <li> an exact number
429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
430 * (minus padding)
431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
432 * enclose its content (plus padding).
433 * </ul>
434 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
436 * an X and Y value.
437 * </p>
438 *
439 * <p>
440 * MeasureSpecs are used to push requirements down the tree from parent to
441 * child. A MeasureSpec can be in one of three modes:
442 * <ul>
443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
444 * of a child view. For example, a LinearLayout may call measure() on its child
445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
446 * tall the child view wants to be given a width of 240 pixels.
447 * <li>EXACTLY: This is used by the parent to impose an exact size on the
448 * child. The child must use this size, and guarantee that all of its
449 * descendants will fit within this size.
450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
451 * child. The child must guarantee that it and all of its descendants will fit
452 * within this size.
453 * </ul>
454 * </p>
455 *
456 * <p>
457 * To initiate a layout, call {@link #requestLayout}. This method is typically
458 * called by a view on itself when it believes that is can no longer fit within
459 * its current bounds.
460 * </p>
461 *
462 * <a name="Drawing"></a>
463 * <h3>Drawing</h3>
464 * <p>
465 * Drawing is handled by walking the tree and recording the drawing commands of
466 * any View that needs to update. After this, the drawing commands of the
467 * entire tree are issued to screen, clipped to the newly damaged area.
468 * </p>
469 *
470 * <p>
471 * The tree is largely recorded and drawn in order, with parents drawn before
472 * (i.e., behind) their children, with siblings drawn in the order they appear
473 * in the tree. If you set a background drawable for a View, then the View will
474 * draw it before calling back to its <code>onDraw()</code> method. The child
475 * drawing order can be overridden with
476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
478 * </p>
479 *
480 * <p>
481 * To force a view to draw, call {@link #invalidate()}.
482 * </p>
483 *
484 * <a name="EventHandlingThreading"></a>
485 * <h3>Event Handling and Threading</h3>
486 * <p>
487 * The basic cycle of a view is as follows:
488 * <ol>
489 * <li>An event comes in and is dispatched to the appropriate view. The view
490 * handles the event and notifies any listeners.</li>
491 * <li>If in the course of processing the event, the view's bounds may need
492 * to be changed, the view will call {@link #requestLayout()}.</li>
493 * <li>Similarly, if in the course of processing the event the view's appearance
494 * may need to be changed, the view will call {@link #invalidate()}.</li>
495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
496 * the framework will take care of measuring, laying out, and drawing the tree
497 * as appropriate.</li>
498 * </ol>
499 * </p>
500 *
501 * <p><em>Note: The entire view tree is single threaded. You must always be on
502 * the UI thread when calling any method on any view.</em>
503 * If you are doing work on other threads and want to update the state of a view
504 * from that thread, you should use a {@link Handler}.
505 * </p>
506 *
507 * <a name="FocusHandling"></a>
508 * <h3>Focus Handling</h3>
509 * <p>
510 * The framework will handle routine focus movement in response to user input.
511 * This includes changing the focus as views are removed or hidden, or as new
512 * views become available. Views indicate their willingness to take focus
513 * through the {@link #isFocusable} method. To change whether a view can take
514 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
516 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
517 * </p>
518 * <p>
519 * Focus movement is based on an algorithm which finds the nearest neighbor in a
520 * given direction. In rare cases, the default algorithm may not match the
521 * intended behavior of the developer. In these situations, you can provide
522 * explicit overrides by using these XML attributes in the layout file:
523 * <pre>
524 * nextFocusDown
525 * nextFocusLeft
526 * nextFocusRight
527 * nextFocusUp
528 * </pre>
529 * </p>
530 *
531 *
532 * <p>
533 * To get a particular view to take focus, call {@link #requestFocus()}.
534 * </p>
535 *
536 * <a name="TouchMode"></a>
537 * <h3>Touch Mode</h3>
538 * <p>
539 * When a user is navigating a user interface via directional keys such as a D-pad, it is
540 * necessary to give focus to actionable items such as buttons so the user can see
541 * what will take input.  If the device has touch capabilities, however, and the user
542 * begins interacting with the interface by touching it, it is no longer necessary to
543 * always highlight, or give focus to, a particular view.  This motivates a mode
544 * for interaction named 'touch mode'.
545 * </p>
546 * <p>
547 * For a touch capable device, once the user touches the screen, the device
548 * will enter touch mode.  From this point onward, only views for which
549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
550 * Other views that are touchable, like buttons, will not take focus when touched; they will
551 * only fire the on click listeners.
552 * </p>
553 * <p>
554 * Any time a user hits a directional key, such as a D-pad direction, the view device will
555 * exit touch mode, and find a view to take focus, so that the user may resume interacting
556 * with the user interface without touching the screen again.
557 * </p>
558 * <p>
559 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
560 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
561 * </p>
562 *
563 * <a name="Scrolling"></a>
564 * <h3>Scrolling</h3>
565 * <p>
566 * The framework provides basic support for views that wish to internally
567 * scroll their content. This includes keeping track of the X and Y scroll
568 * offset as well as mechanisms for drawing scrollbars. See
569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
570 * {@link #awakenScrollBars()} for more details.
571 * </p>
572 *
573 * <a name="Tags"></a>
574 * <h3>Tags</h3>
575 * <p>
576 * Unlike IDs, tags are not used to identify views. Tags are essentially an
577 * extra piece of information that can be associated with a view. They are most
578 * often used as a convenience to store data related to views in the views
579 * themselves rather than by putting them in a separate structure.
580 * </p>
581 * <p>
582 * Tags may be specified with character sequence values in layout XML as either
583 * a single tag using the {@link android.R.styleable#View_tag android:tag}
584 * attribute or multiple tags using the {@code <tag>} child element:
585 * <pre>
586 *     &ltView ...
587 *           android:tag="@string/mytag_value" /&gt;
588 *     &ltView ...&gt;
589 *         &lttag android:id="@+id/mytag"
590 *              android:value="@string/mytag_value" /&gt;
591 *     &lt/View>
592 * </pre>
593 * </p>
594 * <p>
595 * Tags may also be specified with arbitrary objects from code using
596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
597 * </p>
598 *
599 * <a name="Themes"></a>
600 * <h3>Themes</h3>
601 * <p>
602 * By default, Views are created using the theme of the Context object supplied
603 * to their constructor; however, a different theme may be specified by using
604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
606 * code.
607 * </p>
608 * <p>
609 * When the {@link android.R.styleable#View_theme android:theme} attribute is
610 * used in XML, the specified theme is applied on top of the inflation
611 * context's theme (see {@link LayoutInflater}) and used for the view itself as
612 * well as any child elements.
613 * </p>
614 * <p>
615 * In the following example, both views will be created using the Material dark
616 * color scheme; however, because an overlay theme is used which only defines a
617 * subset of attributes, the value of
618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
619 * the inflation context's theme (e.g. the Activity theme) will be preserved.
620 * <pre>
621 *     &ltLinearLayout
622 *             ...
623 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
624 *         &ltView ...&gt;
625 *     &lt/LinearLayout&gt;
626 * </pre>
627 * </p>
628 *
629 * <a name="Properties"></a>
630 * <h3>Properties</h3>
631 * <p>
632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
634 * available both in the {@link Property} form as well as in similarly-named setter/getter
635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
636 * be used to set persistent state associated with these rendering-related properties on the view.
637 * The properties and methods can also be used in conjunction with
638 * {@link android.animation.Animator Animator}-based animations, described more in the
639 * <a href="#Animation">Animation</a> section.
640 * </p>
641 *
642 * <a name="Animation"></a>
643 * <h3>Animation</h3>
644 * <p>
645 * Starting with Android 3.0, the preferred way of animating views is to use the
646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
651 * makes animating these View properties particularly easy and efficient.
652 * </p>
653 * <p>
654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
655 * You can attach an {@link Animation} object to a view using
656 * {@link #setAnimation(Animation)} or
657 * {@link #startAnimation(Animation)}. The animation can alter the scale,
658 * rotation, translation and alpha of a view over time. If the animation is
659 * attached to a view that has children, the animation will affect the entire
660 * subtree rooted by that node. When an animation is started, the framework will
661 * take care of redrawing the appropriate views until the animation completes.
662 * </p>
663 *
664 * <a name="Security"></a>
665 * <h3>Security</h3>
666 * <p>
667 * Sometimes it is essential that an application be able to verify that an action
668 * is being performed with the full knowledge and consent of the user, such as
669 * granting a permission request, making a purchase or clicking on an advertisement.
670 * Unfortunately, a malicious application could try to spoof the user into
671 * performing these actions, unaware, by concealing the intended purpose of the view.
672 * As a remedy, the framework offers a touch filtering mechanism that can be used to
673 * improve the security of views that provide access to sensitive functionality.
674 * </p><p>
675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
676 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
677 * will discard touches that are received whenever the view's window is obscured by
678 * another visible window.  As a result, the view will not receive touches whenever a
679 * toast, dialog or other window appears above the view's window.
680 * </p><p>
681 * For more fine-grained control over security, consider overriding the
682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
684 * </p>
685 *
686 * @attr ref android.R.styleable#View_alpha
687 * @attr ref android.R.styleable#View_background
688 * @attr ref android.R.styleable#View_clickable
689 * @attr ref android.R.styleable#View_contentDescription
690 * @attr ref android.R.styleable#View_drawingCacheQuality
691 * @attr ref android.R.styleable#View_duplicateParentState
692 * @attr ref android.R.styleable#View_id
693 * @attr ref android.R.styleable#View_requiresFadingEdge
694 * @attr ref android.R.styleable#View_fadeScrollbars
695 * @attr ref android.R.styleable#View_fadingEdgeLength
696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
697 * @attr ref android.R.styleable#View_fitsSystemWindows
698 * @attr ref android.R.styleable#View_isScrollContainer
699 * @attr ref android.R.styleable#View_focusable
700 * @attr ref android.R.styleable#View_focusableInTouchMode
701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
702 * @attr ref android.R.styleable#View_keepScreenOn
703 * @attr ref android.R.styleable#View_layerType
704 * @attr ref android.R.styleable#View_layoutDirection
705 * @attr ref android.R.styleable#View_longClickable
706 * @attr ref android.R.styleable#View_minHeight
707 * @attr ref android.R.styleable#View_minWidth
708 * @attr ref android.R.styleable#View_nextFocusDown
709 * @attr ref android.R.styleable#View_nextFocusLeft
710 * @attr ref android.R.styleable#View_nextFocusRight
711 * @attr ref android.R.styleable#View_nextFocusUp
712 * @attr ref android.R.styleable#View_onClick
713 * @attr ref android.R.styleable#View_padding
714 * @attr ref android.R.styleable#View_paddingBottom
715 * @attr ref android.R.styleable#View_paddingLeft
716 * @attr ref android.R.styleable#View_paddingRight
717 * @attr ref android.R.styleable#View_paddingTop
718 * @attr ref android.R.styleable#View_paddingStart
719 * @attr ref android.R.styleable#View_paddingEnd
720 * @attr ref android.R.styleable#View_saveEnabled
721 * @attr ref android.R.styleable#View_rotation
722 * @attr ref android.R.styleable#View_rotationX
723 * @attr ref android.R.styleable#View_rotationY
724 * @attr ref android.R.styleable#View_scaleX
725 * @attr ref android.R.styleable#View_scaleY
726 * @attr ref android.R.styleable#View_scrollX
727 * @attr ref android.R.styleable#View_scrollY
728 * @attr ref android.R.styleable#View_scrollbarSize
729 * @attr ref android.R.styleable#View_scrollbarStyle
730 * @attr ref android.R.styleable#View_scrollbars
731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
732 * @attr ref android.R.styleable#View_scrollbarFadeDuration
733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbVertical
736 * @attr ref android.R.styleable#View_scrollbarTrackVertical
737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
739 * @attr ref android.R.styleable#View_stateListAnimator
740 * @attr ref android.R.styleable#View_transitionName
741 * @attr ref android.R.styleable#View_soundEffectsEnabled
742 * @attr ref android.R.styleable#View_tag
743 * @attr ref android.R.styleable#View_textAlignment
744 * @attr ref android.R.styleable#View_textDirection
745 * @attr ref android.R.styleable#View_transformPivotX
746 * @attr ref android.R.styleable#View_transformPivotY
747 * @attr ref android.R.styleable#View_translationX
748 * @attr ref android.R.styleable#View_translationY
749 * @attr ref android.R.styleable#View_translationZ
750 * @attr ref android.R.styleable#View_visibility
751 * @attr ref android.R.styleable#View_theme
752 *
753 * @see android.view.ViewGroup
754 */
755@UiThread
756public class View implements Drawable.Callback, KeyEvent.Callback,
757        AccessibilityEventSource {
758    private static final boolean DBG = false;
759
760    /**
761     * The logging tag used by this class with android.util.Log.
762     */
763    protected static final String VIEW_LOG_TAG = "View";
764
765    /**
766     * When set to true, apps will draw debugging information about their layouts.
767     *
768     * @hide
769     */
770    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
771
772    /**
773     * When set to true, this view will save its attribute data.
774     *
775     * @hide
776     */
777    public static boolean mDebugViewAttributes = false;
778
779    /**
780     * Used to mark a View that has no ID.
781     */
782    public static final int NO_ID = -1;
783
784    /**
785     * Signals that compatibility booleans have been initialized according to
786     * target SDK versions.
787     */
788    private static boolean sCompatibilityDone = false;
789
790    /**
791     * Use the old (broken) way of building MeasureSpecs.
792     */
793    private static boolean sUseBrokenMakeMeasureSpec = false;
794
795    /**
796     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
797     */
798    static boolean sUseZeroUnspecifiedMeasureSpec = false;
799
800    /**
801     * Ignore any optimizations using the measure cache.
802     */
803    private static boolean sIgnoreMeasureCache = false;
804
805    /**
806     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
807     */
808    private static boolean sAlwaysRemeasureExactly = false;
809
810    /**
811     * Relax constraints around whether setLayoutParams() must be called after
812     * modifying the layout params.
813     */
814    private static boolean sLayoutParamsAlwaysChanged = false;
815
816    /**
817     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
818     * without throwing
819     */
820    static boolean sTextureViewIgnoresDrawableSetters = false;
821
822    /**
823     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
824     * calling setFlags.
825     */
826    private static final int NOT_FOCUSABLE = 0x00000000;
827
828    /**
829     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
830     * setFlags.
831     */
832    private static final int FOCUSABLE = 0x00000001;
833
834    /**
835     * Mask for use with setFlags indicating bits used for focus.
836     */
837    private static final int FOCUSABLE_MASK = 0x00000001;
838
839    /**
840     * This view will adjust its padding to fit sytem windows (e.g. status bar)
841     */
842    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
843
844    /** @hide */
845    @IntDef({VISIBLE, INVISIBLE, GONE})
846    @Retention(RetentionPolicy.SOURCE)
847    public @interface Visibility {}
848
849    /**
850     * This view is visible.
851     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
852     * android:visibility}.
853     */
854    public static final int VISIBLE = 0x00000000;
855
856    /**
857     * This view is invisible, but it still takes up space for layout purposes.
858     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
859     * android:visibility}.
860     */
861    public static final int INVISIBLE = 0x00000004;
862
863    /**
864     * This view is invisible, and it doesn't take any space for layout
865     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
866     * android:visibility}.
867     */
868    public static final int GONE = 0x00000008;
869
870    /**
871     * Mask for use with setFlags indicating bits used for visibility.
872     * {@hide}
873     */
874    static final int VISIBILITY_MASK = 0x0000000C;
875
876    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
877
878    /**
879     * This view is enabled. Interpretation varies by subclass.
880     * Use with ENABLED_MASK when calling setFlags.
881     * {@hide}
882     */
883    static final int ENABLED = 0x00000000;
884
885    /**
886     * This view is disabled. Interpretation varies by subclass.
887     * Use with ENABLED_MASK when calling setFlags.
888     * {@hide}
889     */
890    static final int DISABLED = 0x00000020;
891
892   /**
893    * Mask for use with setFlags indicating bits used for indicating whether
894    * this view is enabled
895    * {@hide}
896    */
897    static final int ENABLED_MASK = 0x00000020;
898
899    /**
900     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
901     * called and further optimizations will be performed. It is okay to have
902     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
903     * {@hide}
904     */
905    static final int WILL_NOT_DRAW = 0x00000080;
906
907    /**
908     * Mask for use with setFlags indicating bits used for indicating whether
909     * this view is will draw
910     * {@hide}
911     */
912    static final int DRAW_MASK = 0x00000080;
913
914    /**
915     * <p>This view doesn't show scrollbars.</p>
916     * {@hide}
917     */
918    static final int SCROLLBARS_NONE = 0x00000000;
919
920    /**
921     * <p>This view shows horizontal scrollbars.</p>
922     * {@hide}
923     */
924    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
925
926    /**
927     * <p>This view shows vertical scrollbars.</p>
928     * {@hide}
929     */
930    static final int SCROLLBARS_VERTICAL = 0x00000200;
931
932    /**
933     * <p>Mask for use with setFlags indicating bits used for indicating which
934     * scrollbars are enabled.</p>
935     * {@hide}
936     */
937    static final int SCROLLBARS_MASK = 0x00000300;
938
939    /**
940     * Indicates that the view should filter touches when its window is obscured.
941     * Refer to the class comments for more information about this security feature.
942     * {@hide}
943     */
944    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
945
946    /**
947     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
948     * that they are optional and should be skipped if the window has
949     * requested system UI flags that ignore those insets for layout.
950     */
951    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
952
953    /**
954     * <p>This view doesn't show fading edges.</p>
955     * {@hide}
956     */
957    static final int FADING_EDGE_NONE = 0x00000000;
958
959    /**
960     * <p>This view shows horizontal fading edges.</p>
961     * {@hide}
962     */
963    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
964
965    /**
966     * <p>This view shows vertical fading edges.</p>
967     * {@hide}
968     */
969    static final int FADING_EDGE_VERTICAL = 0x00002000;
970
971    /**
972     * <p>Mask for use with setFlags indicating bits used for indicating which
973     * fading edges are enabled.</p>
974     * {@hide}
975     */
976    static final int FADING_EDGE_MASK = 0x00003000;
977
978    /**
979     * <p>Indicates this view can be clicked. When clickable, a View reacts
980     * to clicks by notifying the OnClickListener.<p>
981     * {@hide}
982     */
983    static final int CLICKABLE = 0x00004000;
984
985    /**
986     * <p>Indicates this view is caching its drawing into a bitmap.</p>
987     * {@hide}
988     */
989    static final int DRAWING_CACHE_ENABLED = 0x00008000;
990
991    /**
992     * <p>Indicates that no icicle should be saved for this view.<p>
993     * {@hide}
994     */
995    static final int SAVE_DISABLED = 0x000010000;
996
997    /**
998     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
999     * property.</p>
1000     * {@hide}
1001     */
1002    static final int SAVE_DISABLED_MASK = 0x000010000;
1003
1004    /**
1005     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1006     * {@hide}
1007     */
1008    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1009
1010    /**
1011     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1012     * {@hide}
1013     */
1014    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1015
1016    /** @hide */
1017    @Retention(RetentionPolicy.SOURCE)
1018    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1019    public @interface DrawingCacheQuality {}
1020
1021    /**
1022     * <p>Enables low quality mode for the drawing cache.</p>
1023     */
1024    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1025
1026    /**
1027     * <p>Enables high quality mode for the drawing cache.</p>
1028     */
1029    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1030
1031    /**
1032     * <p>Enables automatic quality mode for the drawing cache.</p>
1033     */
1034    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1035
1036    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1037            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1038    };
1039
1040    /**
1041     * <p>Mask for use with setFlags indicating bits used for the cache
1042     * quality property.</p>
1043     * {@hide}
1044     */
1045    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1046
1047    /**
1048     * <p>
1049     * Indicates this view can be long clicked. When long clickable, a View
1050     * reacts to long clicks by notifying the OnLongClickListener or showing a
1051     * context menu.
1052     * </p>
1053     * {@hide}
1054     */
1055    static final int LONG_CLICKABLE = 0x00200000;
1056
1057    /**
1058     * <p>Indicates that this view gets its drawable states from its direct parent
1059     * and ignores its original internal states.</p>
1060     *
1061     * @hide
1062     */
1063    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1064
1065    /**
1066     * <p>
1067     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1068     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1069     * OnContextClickListener.
1070     * </p>
1071     * {@hide}
1072     */
1073    static final int CONTEXT_CLICKABLE = 0x00800000;
1074
1075
1076    /** @hide */
1077    @IntDef({
1078        SCROLLBARS_INSIDE_OVERLAY,
1079        SCROLLBARS_INSIDE_INSET,
1080        SCROLLBARS_OUTSIDE_OVERLAY,
1081        SCROLLBARS_OUTSIDE_INSET
1082    })
1083    @Retention(RetentionPolicy.SOURCE)
1084    public @interface ScrollBarStyle {}
1085
1086    /**
1087     * The scrollbar style to display the scrollbars inside the content area,
1088     * without increasing the padding. The scrollbars will be overlaid with
1089     * translucency on the view's content.
1090     */
1091    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1092
1093    /**
1094     * The scrollbar style to display the scrollbars inside the padded area,
1095     * increasing the padding of the view. The scrollbars will not overlap the
1096     * content area of the view.
1097     */
1098    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1099
1100    /**
1101     * The scrollbar style to display the scrollbars at the edge of the view,
1102     * without increasing the padding. The scrollbars will be overlaid with
1103     * translucency.
1104     */
1105    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1106
1107    /**
1108     * The scrollbar style to display the scrollbars at the edge of the view,
1109     * increasing the padding of the view. The scrollbars will only overlap the
1110     * background, if any.
1111     */
1112    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1113
1114    /**
1115     * Mask to check if the scrollbar style is overlay or inset.
1116     * {@hide}
1117     */
1118    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1119
1120    /**
1121     * Mask to check if the scrollbar style is inside or outside.
1122     * {@hide}
1123     */
1124    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1125
1126    /**
1127     * Mask for scrollbar style.
1128     * {@hide}
1129     */
1130    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1131
1132    /**
1133     * View flag indicating that the screen should remain on while the
1134     * window containing this view is visible to the user.  This effectively
1135     * takes care of automatically setting the WindowManager's
1136     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1137     */
1138    public static final int KEEP_SCREEN_ON = 0x04000000;
1139
1140    /**
1141     * View flag indicating whether this view should have sound effects enabled
1142     * for events such as clicking and touching.
1143     */
1144    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1145
1146    /**
1147     * View flag indicating whether this view should have haptic feedback
1148     * enabled for events such as long presses.
1149     */
1150    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1151
1152    /**
1153     * <p>Indicates that the view hierarchy should stop saving state when
1154     * it reaches this view.  If state saving is initiated immediately at
1155     * the view, it will be allowed.
1156     * {@hide}
1157     */
1158    static final int PARENT_SAVE_DISABLED = 0x20000000;
1159
1160    /**
1161     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1162     * {@hide}
1163     */
1164    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1165
1166    /** @hide */
1167    @IntDef(flag = true,
1168            value = {
1169                FOCUSABLES_ALL,
1170                FOCUSABLES_TOUCH_MODE
1171            })
1172    @Retention(RetentionPolicy.SOURCE)
1173    public @interface FocusableMode {}
1174
1175    /**
1176     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1177     * should add all focusable Views regardless if they are focusable in touch mode.
1178     */
1179    public static final int FOCUSABLES_ALL = 0x00000000;
1180
1181    /**
1182     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1183     * should add only Views focusable in touch mode.
1184     */
1185    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1186
1187    /** @hide */
1188    @IntDef({
1189            FOCUS_BACKWARD,
1190            FOCUS_FORWARD,
1191            FOCUS_LEFT,
1192            FOCUS_UP,
1193            FOCUS_RIGHT,
1194            FOCUS_DOWN
1195    })
1196    @Retention(RetentionPolicy.SOURCE)
1197    public @interface FocusDirection {}
1198
1199    /** @hide */
1200    @IntDef({
1201            FOCUS_LEFT,
1202            FOCUS_UP,
1203            FOCUS_RIGHT,
1204            FOCUS_DOWN
1205    })
1206    @Retention(RetentionPolicy.SOURCE)
1207    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1208
1209    /**
1210     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1211     * item.
1212     */
1213    public static final int FOCUS_BACKWARD = 0x00000001;
1214
1215    /**
1216     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1217     * item.
1218     */
1219    public static final int FOCUS_FORWARD = 0x00000002;
1220
1221    /**
1222     * Use with {@link #focusSearch(int)}. Move focus to the left.
1223     */
1224    public static final int FOCUS_LEFT = 0x00000011;
1225
1226    /**
1227     * Use with {@link #focusSearch(int)}. Move focus up.
1228     */
1229    public static final int FOCUS_UP = 0x00000021;
1230
1231    /**
1232     * Use with {@link #focusSearch(int)}. Move focus to the right.
1233     */
1234    public static final int FOCUS_RIGHT = 0x00000042;
1235
1236    /**
1237     * Use with {@link #focusSearch(int)}. Move focus down.
1238     */
1239    public static final int FOCUS_DOWN = 0x00000082;
1240
1241    /**
1242     * Bits of {@link #getMeasuredWidthAndState()} and
1243     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1244     */
1245    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1246
1247    /**
1248     * Bits of {@link #getMeasuredWidthAndState()} and
1249     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1250     */
1251    public static final int MEASURED_STATE_MASK = 0xff000000;
1252
1253    /**
1254     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1255     * for functions that combine both width and height into a single int,
1256     * such as {@link #getMeasuredState()} and the childState argument of
1257     * {@link #resolveSizeAndState(int, int, int)}.
1258     */
1259    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1260
1261    /**
1262     * Bit of {@link #getMeasuredWidthAndState()} and
1263     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1264     * is smaller that the space the view would like to have.
1265     */
1266    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1267
1268    /**
1269     * Base View state sets
1270     */
1271    // Singles
1272    /**
1273     * Indicates the view has no states set. States are used with
1274     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1275     * view depending on its state.
1276     *
1277     * @see android.graphics.drawable.Drawable
1278     * @see #getDrawableState()
1279     */
1280    protected static final int[] EMPTY_STATE_SET;
1281    /**
1282     * Indicates the view is enabled. States are used with
1283     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1284     * view depending on its state.
1285     *
1286     * @see android.graphics.drawable.Drawable
1287     * @see #getDrawableState()
1288     */
1289    protected static final int[] ENABLED_STATE_SET;
1290    /**
1291     * Indicates the view is focused. States are used with
1292     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1293     * view depending on its state.
1294     *
1295     * @see android.graphics.drawable.Drawable
1296     * @see #getDrawableState()
1297     */
1298    protected static final int[] FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is selected. States are used with
1301     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1302     * view depending on its state.
1303     *
1304     * @see android.graphics.drawable.Drawable
1305     * @see #getDrawableState()
1306     */
1307    protected static final int[] SELECTED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed. States are used with
1310     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1311     * view depending on its state.
1312     *
1313     * @see android.graphics.drawable.Drawable
1314     * @see #getDrawableState()
1315     */
1316    protected static final int[] PRESSED_STATE_SET;
1317    /**
1318     * Indicates the view's window has focus. States are used with
1319     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1320     * view depending on its state.
1321     *
1322     * @see android.graphics.drawable.Drawable
1323     * @see #getDrawableState()
1324     */
1325    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1326    // Doubles
1327    /**
1328     * Indicates the view is enabled and has the focus.
1329     *
1330     * @see #ENABLED_STATE_SET
1331     * @see #FOCUSED_STATE_SET
1332     */
1333    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is enabled and selected.
1336     *
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     */
1340    protected static final int[] ENABLED_SELECTED_STATE_SET;
1341    /**
1342     * Indicates the view is enabled and that its window has focus.
1343     *
1344     * @see #ENABLED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1348    /**
1349     * Indicates the view is focused and selected.
1350     *
1351     * @see #FOCUSED_STATE_SET
1352     * @see #SELECTED_STATE_SET
1353     */
1354    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1355    /**
1356     * Indicates the view has the focus and that its window has the focus.
1357     *
1358     * @see #FOCUSED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is selected and that its window has the focus.
1364     *
1365     * @see #SELECTED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1369    // Triples
1370    /**
1371     * Indicates the view is enabled, focused and selected.
1372     *
1373     * @see #ENABLED_STATE_SET
1374     * @see #FOCUSED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     */
1377    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1378    /**
1379     * Indicates the view is enabled, focused and its window has the focus.
1380     *
1381     * @see #ENABLED_STATE_SET
1382     * @see #FOCUSED_STATE_SET
1383     * @see #WINDOW_FOCUSED_STATE_SET
1384     */
1385    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1386    /**
1387     * Indicates the view is enabled, selected and its window has the focus.
1388     *
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     * @see #WINDOW_FOCUSED_STATE_SET
1392     */
1393    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1394    /**
1395     * Indicates the view is focused, selected and its window has the focus.
1396     *
1397     * @see #FOCUSED_STATE_SET
1398     * @see #SELECTED_STATE_SET
1399     * @see #WINDOW_FOCUSED_STATE_SET
1400     */
1401    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1402    /**
1403     * Indicates the view is enabled, focused, selected and its window
1404     * has the focus.
1405     *
1406     * @see #ENABLED_STATE_SET
1407     * @see #FOCUSED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is pressed and its window has the focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed and selected.
1421     *
1422     * @see #PRESSED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     */
1425    protected static final int[] PRESSED_SELECTED_STATE_SET;
1426    /**
1427     * Indicates the view is pressed, selected and its window has the focus.
1428     *
1429     * @see #PRESSED_STATE_SET
1430     * @see #SELECTED_STATE_SET
1431     * @see #WINDOW_FOCUSED_STATE_SET
1432     */
1433    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1434    /**
1435     * Indicates the view is pressed and focused.
1436     *
1437     * @see #PRESSED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1441    /**
1442     * Indicates the view is pressed, focused and its window has the focus.
1443     *
1444     * @see #PRESSED_STATE_SET
1445     * @see #FOCUSED_STATE_SET
1446     * @see #WINDOW_FOCUSED_STATE_SET
1447     */
1448    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1449    /**
1450     * Indicates the view is pressed, focused and selected.
1451     *
1452     * @see #PRESSED_STATE_SET
1453     * @see #SELECTED_STATE_SET
1454     * @see #FOCUSED_STATE_SET
1455     */
1456    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1457    /**
1458     * Indicates the view is pressed, focused, selected and its window has the focus.
1459     *
1460     * @see #PRESSED_STATE_SET
1461     * @see #FOCUSED_STATE_SET
1462     * @see #SELECTED_STATE_SET
1463     * @see #WINDOW_FOCUSED_STATE_SET
1464     */
1465    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1466    /**
1467     * Indicates the view is pressed and enabled.
1468     *
1469     * @see #PRESSED_STATE_SET
1470     * @see #ENABLED_STATE_SET
1471     */
1472    protected static final int[] PRESSED_ENABLED_STATE_SET;
1473    /**
1474     * Indicates the view is pressed, enabled and its window has the focus.
1475     *
1476     * @see #PRESSED_STATE_SET
1477     * @see #ENABLED_STATE_SET
1478     * @see #WINDOW_FOCUSED_STATE_SET
1479     */
1480    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1481    /**
1482     * Indicates the view is pressed, enabled and selected.
1483     *
1484     * @see #PRESSED_STATE_SET
1485     * @see #ENABLED_STATE_SET
1486     * @see #SELECTED_STATE_SET
1487     */
1488    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1489    /**
1490     * Indicates the view is pressed, enabled, selected and its window has the
1491     * focus.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #ENABLED_STATE_SET
1495     * @see #SELECTED_STATE_SET
1496     * @see #WINDOW_FOCUSED_STATE_SET
1497     */
1498    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1499    /**
1500     * Indicates the view is pressed, enabled and focused.
1501     *
1502     * @see #PRESSED_STATE_SET
1503     * @see #ENABLED_STATE_SET
1504     * @see #FOCUSED_STATE_SET
1505     */
1506    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1507    /**
1508     * Indicates the view is pressed, enabled, focused and its window has the
1509     * focus.
1510     *
1511     * @see #PRESSED_STATE_SET
1512     * @see #ENABLED_STATE_SET
1513     * @see #FOCUSED_STATE_SET
1514     * @see #WINDOW_FOCUSED_STATE_SET
1515     */
1516    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1517    /**
1518     * Indicates the view is pressed, enabled, focused and selected.
1519     *
1520     * @see #PRESSED_STATE_SET
1521     * @see #ENABLED_STATE_SET
1522     * @see #SELECTED_STATE_SET
1523     * @see #FOCUSED_STATE_SET
1524     */
1525    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1526    /**
1527     * Indicates the view is pressed, enabled, focused, selected and its window
1528     * has the focus.
1529     *
1530     * @see #PRESSED_STATE_SET
1531     * @see #ENABLED_STATE_SET
1532     * @see #SELECTED_STATE_SET
1533     * @see #FOCUSED_STATE_SET
1534     * @see #WINDOW_FOCUSED_STATE_SET
1535     */
1536    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1537
1538    static {
1539        EMPTY_STATE_SET = StateSet.get(0);
1540
1541        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1542
1543        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1544        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1545                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1546
1547        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1548        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1549                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1550        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1551                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1552        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1553                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1554                        | StateSet.VIEW_STATE_FOCUSED);
1555
1556        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1557        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1558                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1559        ENABLED_SELECTED_STATE_SET = StateSet.get(
1560                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1561        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1562                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1563                        | StateSet.VIEW_STATE_ENABLED);
1564        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1565                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1566        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1567                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1568                        | StateSet.VIEW_STATE_ENABLED);
1569        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1571                        | StateSet.VIEW_STATE_ENABLED);
1572        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1573                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1574                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1575
1576        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1577        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1578                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1579        PRESSED_SELECTED_STATE_SET = StateSet.get(
1580                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1581        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1582                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1583                        | StateSet.VIEW_STATE_PRESSED);
1584        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1585                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1586        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1587                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1588                        | StateSet.VIEW_STATE_PRESSED);
1589        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1591                        | StateSet.VIEW_STATE_PRESSED);
1592        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1593                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1594                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1595        PRESSED_ENABLED_STATE_SET = StateSet.get(
1596                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1597        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1598                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1599                        | StateSet.VIEW_STATE_PRESSED);
1600        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1601                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1602                        | StateSet.VIEW_STATE_PRESSED);
1603        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1604                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1605                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1606        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1607                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1608                        | StateSet.VIEW_STATE_PRESSED);
1609        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1610                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1611                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1612        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1614                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1615        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1616                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1617                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1618                        | StateSet.VIEW_STATE_PRESSED);
1619    }
1620
1621    /**
1622     * Accessibility event types that are dispatched for text population.
1623     */
1624    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1625            AccessibilityEvent.TYPE_VIEW_CLICKED
1626            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1627            | AccessibilityEvent.TYPE_VIEW_SELECTED
1628            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1629            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1630            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1631            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1632            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1633            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1634            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1635            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1636
1637    /**
1638     * Temporary Rect currently for use in setBackground().  This will probably
1639     * be extended in the future to hold our own class with more than just
1640     * a Rect. :)
1641     */
1642    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1643
1644    /**
1645     * Map used to store views' tags.
1646     */
1647    private SparseArray<Object> mKeyedTags;
1648
1649    /**
1650     * The next available accessibility id.
1651     */
1652    private static int sNextAccessibilityViewId;
1653
1654    /**
1655     * The animation currently associated with this view.
1656     * @hide
1657     */
1658    protected Animation mCurrentAnimation = null;
1659
1660    /**
1661     * Width as measured during measure pass.
1662     * {@hide}
1663     */
1664    @ViewDebug.ExportedProperty(category = "measurement")
1665    int mMeasuredWidth;
1666
1667    /**
1668     * Height as measured during measure pass.
1669     * {@hide}
1670     */
1671    @ViewDebug.ExportedProperty(category = "measurement")
1672    int mMeasuredHeight;
1673
1674    /**
1675     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1676     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1677     * its display list. This flag, used only when hw accelerated, allows us to clear the
1678     * flag while retaining this information until it's needed (at getDisplayList() time and
1679     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1680     *
1681     * {@hide}
1682     */
1683    boolean mRecreateDisplayList = false;
1684
1685    /**
1686     * The view's identifier.
1687     * {@hide}
1688     *
1689     * @see #setId(int)
1690     * @see #getId()
1691     */
1692    @IdRes
1693    @ViewDebug.ExportedProperty(resolveId = true)
1694    int mID = NO_ID;
1695
1696    /**
1697     * The stable ID of this view for accessibility purposes.
1698     */
1699    int mAccessibilityViewId = NO_ID;
1700
1701    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1702
1703    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1704
1705    /**
1706     * The view's tag.
1707     * {@hide}
1708     *
1709     * @see #setTag(Object)
1710     * @see #getTag()
1711     */
1712    protected Object mTag = null;
1713
1714    // for mPrivateFlags:
1715    /** {@hide} */
1716    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1717    /** {@hide} */
1718    static final int PFLAG_FOCUSED                     = 0x00000002;
1719    /** {@hide} */
1720    static final int PFLAG_SELECTED                    = 0x00000004;
1721    /** {@hide} */
1722    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1723    /** {@hide} */
1724    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1725    /** {@hide} */
1726    static final int PFLAG_DRAWN                       = 0x00000020;
1727    /**
1728     * When this flag is set, this view is running an animation on behalf of its
1729     * children and should therefore not cancel invalidate requests, even if they
1730     * lie outside of this view's bounds.
1731     *
1732     * {@hide}
1733     */
1734    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1735    /** {@hide} */
1736    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1737    /** {@hide} */
1738    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1739    /** {@hide} */
1740    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1741    /** {@hide} */
1742    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1743    /** {@hide} */
1744    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1745    /** {@hide} */
1746    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1747
1748    private static final int PFLAG_PRESSED             = 0x00004000;
1749
1750    /** {@hide} */
1751    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1752    /**
1753     * Flag used to indicate that this view should be drawn once more (and only once
1754     * more) after its animation has completed.
1755     * {@hide}
1756     */
1757    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1758
1759    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1760
1761    /**
1762     * Indicates that the View returned true when onSetAlpha() was called and that
1763     * the alpha must be restored.
1764     * {@hide}
1765     */
1766    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1767
1768    /**
1769     * Set by {@link #setScrollContainer(boolean)}.
1770     */
1771    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1772
1773    /**
1774     * Set by {@link #setScrollContainer(boolean)}.
1775     */
1776    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1777
1778    /**
1779     * View flag indicating whether this view was invalidated (fully or partially.)
1780     *
1781     * @hide
1782     */
1783    static final int PFLAG_DIRTY                       = 0x00200000;
1784
1785    /**
1786     * View flag indicating whether this view was invalidated by an opaque
1787     * invalidate request.
1788     *
1789     * @hide
1790     */
1791    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1792
1793    /**
1794     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1795     *
1796     * @hide
1797     */
1798    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1799
1800    /**
1801     * Indicates whether the background is opaque.
1802     *
1803     * @hide
1804     */
1805    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1806
1807    /**
1808     * Indicates whether the scrollbars are opaque.
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1813
1814    /**
1815     * Indicates whether the view is opaque.
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1820
1821    /**
1822     * Indicates a prepressed state;
1823     * the short time between ACTION_DOWN and recognizing
1824     * a 'real' press. Prepressed is used to recognize quick taps
1825     * even when they are shorter than ViewConfiguration.getTapTimeout().
1826     *
1827     * @hide
1828     */
1829    private static final int PFLAG_PREPRESSED          = 0x02000000;
1830
1831    /**
1832     * Indicates whether the view is temporarily detached.
1833     *
1834     * @hide
1835     */
1836    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1837
1838    /**
1839     * Indicates that we should awaken scroll bars once attached
1840     *
1841     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1842     * during window attachment and it is no longer needed. Feel free to repurpose it.
1843     *
1844     * @hide
1845     */
1846    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1847
1848    /**
1849     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1850     * @hide
1851     */
1852    private static final int PFLAG_HOVERED             = 0x10000000;
1853
1854    /**
1855     * no longer needed, should be reused
1856     */
1857    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1858
1859    /** {@hide} */
1860    static final int PFLAG_ACTIVATED                   = 0x40000000;
1861
1862    /**
1863     * Indicates that this view was specifically invalidated, not just dirtied because some
1864     * child view was invalidated. The flag is used to determine when we need to recreate
1865     * a view's display list (as opposed to just returning a reference to its existing
1866     * display list).
1867     *
1868     * @hide
1869     */
1870    static final int PFLAG_INVALIDATED                 = 0x80000000;
1871
1872    /**
1873     * Masks for mPrivateFlags2, as generated by dumpFlags():
1874     *
1875     * |-------|-------|-------|-------|
1876     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1877     *                                1  PFLAG2_DRAG_HOVERED
1878     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1879     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1880     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1881     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1882     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1883     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1884     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1885     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1886     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1887     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1888     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1889     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1890     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1891     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1892     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1893     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1894     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1895     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1896     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1897     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1898     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1899     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1900     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1901     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1902     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1903     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1904     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1905     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1906     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1907     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1908     *    1                              PFLAG2_PADDING_RESOLVED
1909     *   1                               PFLAG2_DRAWABLE_RESOLVED
1910     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1911     * |-------|-------|-------|-------|
1912     */
1913
1914    /**
1915     * Indicates that this view has reported that it can accept the current drag's content.
1916     * Cleared when the drag operation concludes.
1917     * @hide
1918     */
1919    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1920
1921    /**
1922     * Indicates that this view is currently directly under the drag location in a
1923     * drag-and-drop operation involving content that it can accept.  Cleared when
1924     * the drag exits the view, or when the drag operation concludes.
1925     * @hide
1926     */
1927    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1928
1929    /** @hide */
1930    @IntDef({
1931        LAYOUT_DIRECTION_LTR,
1932        LAYOUT_DIRECTION_RTL,
1933        LAYOUT_DIRECTION_INHERIT,
1934        LAYOUT_DIRECTION_LOCALE
1935    })
1936    @Retention(RetentionPolicy.SOURCE)
1937    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1938    public @interface LayoutDir {}
1939
1940    /** @hide */
1941    @IntDef({
1942        LAYOUT_DIRECTION_LTR,
1943        LAYOUT_DIRECTION_RTL
1944    })
1945    @Retention(RetentionPolicy.SOURCE)
1946    public @interface ResolvedLayoutDir {}
1947
1948    /**
1949     * A flag to indicate that the layout direction of this view has not been defined yet.
1950     * @hide
1951     */
1952    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1953
1954    /**
1955     * Horizontal layout direction of this view is from Left to Right.
1956     * Use with {@link #setLayoutDirection}.
1957     */
1958    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1959
1960    /**
1961     * Horizontal layout direction of this view is from Right to Left.
1962     * Use with {@link #setLayoutDirection}.
1963     */
1964    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1965
1966    /**
1967     * Horizontal layout direction of this view is inherited from its parent.
1968     * Use with {@link #setLayoutDirection}.
1969     */
1970    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1971
1972    /**
1973     * Horizontal layout direction of this view is from deduced from the default language
1974     * script for the locale. Use with {@link #setLayoutDirection}.
1975     */
1976    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1977
1978    /**
1979     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1980     * @hide
1981     */
1982    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1983
1984    /**
1985     * Mask for use with private flags indicating bits used for horizontal layout direction.
1986     * @hide
1987     */
1988    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1989
1990    /**
1991     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1992     * right-to-left direction.
1993     * @hide
1994     */
1995    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1996
1997    /**
1998     * Indicates whether the view horizontal layout direction has been resolved.
1999     * @hide
2000     */
2001    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2002
2003    /**
2004     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2005     * @hide
2006     */
2007    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2008            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2009
2010    /*
2011     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2012     * flag value.
2013     * @hide
2014     */
2015    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2016            LAYOUT_DIRECTION_LTR,
2017            LAYOUT_DIRECTION_RTL,
2018            LAYOUT_DIRECTION_INHERIT,
2019            LAYOUT_DIRECTION_LOCALE
2020    };
2021
2022    /**
2023     * Default horizontal layout direction.
2024     */
2025    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2026
2027    /**
2028     * Default horizontal layout direction.
2029     * @hide
2030     */
2031    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2032
2033    /**
2034     * Text direction is inherited through {@link ViewGroup}
2035     */
2036    public static final int TEXT_DIRECTION_INHERIT = 0;
2037
2038    /**
2039     * Text direction is using "first strong algorithm". The first strong directional character
2040     * determines the paragraph direction. If there is no strong directional character, the
2041     * paragraph direction is the view's resolved layout direction.
2042     */
2043    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2044
2045    /**
2046     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2047     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2048     * If there are neither, the paragraph direction is the view's resolved layout direction.
2049     */
2050    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2051
2052    /**
2053     * Text direction is forced to LTR.
2054     */
2055    public static final int TEXT_DIRECTION_LTR = 3;
2056
2057    /**
2058     * Text direction is forced to RTL.
2059     */
2060    public static final int TEXT_DIRECTION_RTL = 4;
2061
2062    /**
2063     * Text direction is coming from the system Locale.
2064     */
2065    public static final int TEXT_DIRECTION_LOCALE = 5;
2066
2067    /**
2068     * Text direction is using "first strong algorithm". The first strong directional character
2069     * determines the paragraph direction. If there is no strong directional character, the
2070     * paragraph direction is LTR.
2071     */
2072    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2073
2074    /**
2075     * Text direction is using "first strong algorithm". The first strong directional character
2076     * determines the paragraph direction. If there is no strong directional character, the
2077     * paragraph direction is RTL.
2078     */
2079    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2080
2081    /**
2082     * Default text direction is inherited
2083     */
2084    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2085
2086    /**
2087     * Default resolved text direction
2088     * @hide
2089     */
2090    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2091
2092    /**
2093     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2094     * @hide
2095     */
2096    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2097
2098    /**
2099     * Mask for use with private flags indicating bits used for text direction.
2100     * @hide
2101     */
2102    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2103            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2104
2105    /**
2106     * Array of text direction flags for mapping attribute "textDirection" to correct
2107     * flag value.
2108     * @hide
2109     */
2110    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2111            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2112            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2113            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2114            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2115            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2116            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2117            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2118            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2119    };
2120
2121    /**
2122     * Indicates whether the view text direction has been resolved.
2123     * @hide
2124     */
2125    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2126            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2127
2128    /**
2129     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2130     * @hide
2131     */
2132    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2133
2134    /**
2135     * Mask for use with private flags indicating bits used for resolved text direction.
2136     * @hide
2137     */
2138    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2139            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2140
2141    /**
2142     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2143     * @hide
2144     */
2145    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2146            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2147
2148    /** @hide */
2149    @IntDef({
2150        TEXT_ALIGNMENT_INHERIT,
2151        TEXT_ALIGNMENT_GRAVITY,
2152        TEXT_ALIGNMENT_CENTER,
2153        TEXT_ALIGNMENT_TEXT_START,
2154        TEXT_ALIGNMENT_TEXT_END,
2155        TEXT_ALIGNMENT_VIEW_START,
2156        TEXT_ALIGNMENT_VIEW_END
2157    })
2158    @Retention(RetentionPolicy.SOURCE)
2159    public @interface TextAlignment {}
2160
2161    /**
2162     * Default text alignment. The text alignment of this View is inherited from its parent.
2163     * Use with {@link #setTextAlignment(int)}
2164     */
2165    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2166
2167    /**
2168     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2169     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2170     *
2171     * Use with {@link #setTextAlignment(int)}
2172     */
2173    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2174
2175    /**
2176     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2177     *
2178     * Use with {@link #setTextAlignment(int)}
2179     */
2180    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2181
2182    /**
2183     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2184     *
2185     * Use with {@link #setTextAlignment(int)}
2186     */
2187    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2188
2189    /**
2190     * Center the paragraph, e.g. ALIGN_CENTER.
2191     *
2192     * Use with {@link #setTextAlignment(int)}
2193     */
2194    public static final int TEXT_ALIGNMENT_CENTER = 4;
2195
2196    /**
2197     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2198     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2199     *
2200     * Use with {@link #setTextAlignment(int)}
2201     */
2202    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2203
2204    /**
2205     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2206     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2207     *
2208     * Use with {@link #setTextAlignment(int)}
2209     */
2210    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2211
2212    /**
2213     * Default text alignment is inherited
2214     */
2215    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2216
2217    /**
2218     * Default resolved text alignment
2219     * @hide
2220     */
2221    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2222
2223    /**
2224      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2225      * @hide
2226      */
2227    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2228
2229    /**
2230      * Mask for use with private flags indicating bits used for text alignment.
2231      * @hide
2232      */
2233    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2234
2235    /**
2236     * Array of text direction flags for mapping attribute "textAlignment" to correct
2237     * flag value.
2238     * @hide
2239     */
2240    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2241            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2242            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2243            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2244            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2245            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2246            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2247            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2248    };
2249
2250    /**
2251     * Indicates whether the view text alignment has been resolved.
2252     * @hide
2253     */
2254    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2255
2256    /**
2257     * Bit shift to get the resolved text alignment.
2258     * @hide
2259     */
2260    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2261
2262    /**
2263     * Mask for use with private flags indicating bits used for text alignment.
2264     * @hide
2265     */
2266    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2267            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2268
2269    /**
2270     * Indicates whether if the view text alignment has been resolved to gravity
2271     */
2272    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2273            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2274
2275    // Accessiblity constants for mPrivateFlags2
2276
2277    /**
2278     * Shift for the bits in {@link #mPrivateFlags2} related to the
2279     * "importantForAccessibility" attribute.
2280     */
2281    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2282
2283    /**
2284     * Automatically determine whether a view is important for accessibility.
2285     */
2286    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2287
2288    /**
2289     * The view is important for accessibility.
2290     */
2291    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2292
2293    /**
2294     * The view is not important for accessibility.
2295     */
2296    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2297
2298    /**
2299     * The view is not important for accessibility, nor are any of its
2300     * descendant views.
2301     */
2302    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2303
2304    /**
2305     * The default whether the view is important for accessibility.
2306     */
2307    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2308
2309    /**
2310     * Mask for obtainig the bits which specify how to determine
2311     * whether a view is important for accessibility.
2312     */
2313    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2314        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2315        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2316        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2317
2318    /**
2319     * Shift for the bits in {@link #mPrivateFlags2} related to the
2320     * "accessibilityLiveRegion" attribute.
2321     */
2322    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2323
2324    /**
2325     * Live region mode specifying that accessibility services should not
2326     * automatically announce changes to this view. This is the default live
2327     * region mode for most views.
2328     * <p>
2329     * Use with {@link #setAccessibilityLiveRegion(int)}.
2330     */
2331    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2332
2333    /**
2334     * Live region mode specifying that accessibility services should announce
2335     * changes to this view.
2336     * <p>
2337     * Use with {@link #setAccessibilityLiveRegion(int)}.
2338     */
2339    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2340
2341    /**
2342     * Live region mode specifying that accessibility services should interrupt
2343     * ongoing speech to immediately announce changes to this view.
2344     * <p>
2345     * Use with {@link #setAccessibilityLiveRegion(int)}.
2346     */
2347    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2348
2349    /**
2350     * The default whether the view is important for accessibility.
2351     */
2352    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2353
2354    /**
2355     * Mask for obtaining the bits which specify a view's accessibility live
2356     * region mode.
2357     */
2358    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2359            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2360            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2361
2362    /**
2363     * Flag indicating whether a view has accessibility focus.
2364     */
2365    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2366
2367    /**
2368     * Flag whether the accessibility state of the subtree rooted at this view changed.
2369     */
2370    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2371
2372    /**
2373     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2374     * is used to check whether later changes to the view's transform should invalidate the
2375     * view to force the quickReject test to run again.
2376     */
2377    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2378
2379    /**
2380     * Flag indicating that start/end padding has been resolved into left/right padding
2381     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2382     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2383     * during measurement. In some special cases this is required such as when an adapter-based
2384     * view measures prospective children without attaching them to a window.
2385     */
2386    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2387
2388    /**
2389     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2390     */
2391    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2392
2393    /**
2394     * Indicates that the view is tracking some sort of transient state
2395     * that the app should not need to be aware of, but that the framework
2396     * should take special care to preserve.
2397     */
2398    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2399
2400    /**
2401     * Group of bits indicating that RTL properties resolution is done.
2402     */
2403    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2404            PFLAG2_TEXT_DIRECTION_RESOLVED |
2405            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2406            PFLAG2_PADDING_RESOLVED |
2407            PFLAG2_DRAWABLE_RESOLVED;
2408
2409    // There are a couple of flags left in mPrivateFlags2
2410
2411    /* End of masks for mPrivateFlags2 */
2412
2413    /**
2414     * Masks for mPrivateFlags3, as generated by dumpFlags():
2415     *
2416     * |-------|-------|-------|-------|
2417     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2418     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2419     *                               1   PFLAG3_IS_LAID_OUT
2420     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2421     *                             1     PFLAG3_CALLED_SUPER
2422     *                            1      PFLAG3_APPLYING_INSETS
2423     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2424     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2425     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2426     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2427     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2428     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2429     *                     1             PFLAG3_SCROLL_INDICATOR_START
2430     *                    1              PFLAG3_SCROLL_INDICATOR_END
2431     *                   1               PFLAG3_ASSIST_BLOCKED
2432     *                  1                PFLAG3_POINTER_ICON_NULL
2433     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2434     *           11111111                PFLAG3_POINTER_ICON_MASK
2435     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2436     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2437     *        1                          PFLAG3_TEMPORARY_DETACH
2438     * |-------|-------|-------|-------|
2439     */
2440
2441    /**
2442     * Flag indicating that view has a transform animation set on it. This is used to track whether
2443     * an animation is cleared between successive frames, in order to tell the associated
2444     * DisplayList to clear its animation matrix.
2445     */
2446    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2447
2448    /**
2449     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2450     * animation is cleared between successive frames, in order to tell the associated
2451     * DisplayList to restore its alpha value.
2452     */
2453    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2454
2455    /**
2456     * Flag indicating that the view has been through at least one layout since it
2457     * was last attached to a window.
2458     */
2459    static final int PFLAG3_IS_LAID_OUT = 0x4;
2460
2461    /**
2462     * Flag indicating that a call to measure() was skipped and should be done
2463     * instead when layout() is invoked.
2464     */
2465    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2466
2467    /**
2468     * Flag indicating that an overridden method correctly called down to
2469     * the superclass implementation as required by the API spec.
2470     */
2471    static final int PFLAG3_CALLED_SUPER = 0x10;
2472
2473    /**
2474     * Flag indicating that we're in the process of applying window insets.
2475     */
2476    static final int PFLAG3_APPLYING_INSETS = 0x20;
2477
2478    /**
2479     * Flag indicating that we're in the process of fitting system windows using the old method.
2480     */
2481    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2482
2483    /**
2484     * Flag indicating that nested scrolling is enabled for this view.
2485     * The view will optionally cooperate with views up its parent chain to allow for
2486     * integrated nested scrolling along the same axis.
2487     */
2488    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2489
2490    /**
2491     * Flag indicating that the bottom scroll indicator should be displayed
2492     * when this view can scroll up.
2493     */
2494    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2495
2496    /**
2497     * Flag indicating that the bottom scroll indicator should be displayed
2498     * when this view can scroll down.
2499     */
2500    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2501
2502    /**
2503     * Flag indicating that the left scroll indicator should be displayed
2504     * when this view can scroll left.
2505     */
2506    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2507
2508    /**
2509     * Flag indicating that the right scroll indicator should be displayed
2510     * when this view can scroll right.
2511     */
2512    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2513
2514    /**
2515     * Flag indicating that the start scroll indicator should be displayed
2516     * when this view can scroll in the start direction.
2517     */
2518    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2519
2520    /**
2521     * Flag indicating that the end scroll indicator should be displayed
2522     * when this view can scroll in the end direction.
2523     */
2524    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2525
2526    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2527
2528    static final int SCROLL_INDICATORS_NONE = 0x0000;
2529
2530    /**
2531     * Mask for use with setFlags indicating bits used for indicating which
2532     * scroll indicators are enabled.
2533     */
2534    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2535            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2536            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2537            | PFLAG3_SCROLL_INDICATOR_END;
2538
2539    /**
2540     * Left-shift required to translate between public scroll indicator flags
2541     * and internal PFLAGS3 flags. When used as a right-shift, translates
2542     * PFLAGS3 flags to public flags.
2543     */
2544    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2545
2546    /** @hide */
2547    @Retention(RetentionPolicy.SOURCE)
2548    @IntDef(flag = true,
2549            value = {
2550                    SCROLL_INDICATOR_TOP,
2551                    SCROLL_INDICATOR_BOTTOM,
2552                    SCROLL_INDICATOR_LEFT,
2553                    SCROLL_INDICATOR_RIGHT,
2554                    SCROLL_INDICATOR_START,
2555                    SCROLL_INDICATOR_END,
2556            })
2557    public @interface ScrollIndicators {}
2558
2559    /**
2560     * Scroll indicator direction for the top edge of the view.
2561     *
2562     * @see #setScrollIndicators(int)
2563     * @see #setScrollIndicators(int, int)
2564     * @see #getScrollIndicators()
2565     */
2566    public static final int SCROLL_INDICATOR_TOP =
2567            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2568
2569    /**
2570     * Scroll indicator direction for the bottom edge of the view.
2571     *
2572     * @see #setScrollIndicators(int)
2573     * @see #setScrollIndicators(int, int)
2574     * @see #getScrollIndicators()
2575     */
2576    public static final int SCROLL_INDICATOR_BOTTOM =
2577            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2578
2579    /**
2580     * Scroll indicator direction for the left edge of the view.
2581     *
2582     * @see #setScrollIndicators(int)
2583     * @see #setScrollIndicators(int, int)
2584     * @see #getScrollIndicators()
2585     */
2586    public static final int SCROLL_INDICATOR_LEFT =
2587            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2588
2589    /**
2590     * Scroll indicator direction for the right edge of the view.
2591     *
2592     * @see #setScrollIndicators(int)
2593     * @see #setScrollIndicators(int, int)
2594     * @see #getScrollIndicators()
2595     */
2596    public static final int SCROLL_INDICATOR_RIGHT =
2597            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2598
2599    /**
2600     * Scroll indicator direction for the starting edge of the view.
2601     * <p>
2602     * Resolved according to the view's layout direction, see
2603     * {@link #getLayoutDirection()} for more information.
2604     *
2605     * @see #setScrollIndicators(int)
2606     * @see #setScrollIndicators(int, int)
2607     * @see #getScrollIndicators()
2608     */
2609    public static final int SCROLL_INDICATOR_START =
2610            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2611
2612    /**
2613     * Scroll indicator direction for the ending edge of the view.
2614     * <p>
2615     * Resolved according to the view's layout direction, see
2616     * {@link #getLayoutDirection()} for more information.
2617     *
2618     * @see #setScrollIndicators(int)
2619     * @see #setScrollIndicators(int, int)
2620     * @see #getScrollIndicators()
2621     */
2622    public static final int SCROLL_INDICATOR_END =
2623            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2624
2625    /**
2626     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2627     * into this view.<p>
2628     */
2629    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2630
2631    /**
2632     * The mask for use with private flags indicating bits used for pointer icon shapes.
2633     */
2634    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2635
2636    /**
2637     * Left-shift used for pointer icon shape values in private flags.
2638     */
2639    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2640
2641    /**
2642     * Value indicating no specific pointer icons.
2643     */
2644    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2645
2646    /**
2647     * Value indicating {@link PointerIcon.STYLE_NULL}.
2648     */
2649    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2650
2651    /**
2652     * The base value for other pointer icon shapes.
2653     */
2654    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2655
2656    /**
2657     * Whether this view has rendered elements that overlap (see {@link
2658     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2659     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2660     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2661     * determined by whatever {@link #hasOverlappingRendering()} returns.
2662     */
2663    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2664
2665    /**
2666     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2667     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2668     */
2669    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2670
2671    /**
2672     * Flag indicating that the view is temporarily detached from the parent view.
2673     *
2674     * @see #onStartTemporaryDetach()
2675     * @see #onFinishTemporaryDetach()
2676     */
2677    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2678
2679    /* End of masks for mPrivateFlags3 */
2680
2681    /**
2682     * Always allow a user to over-scroll this view, provided it is a
2683     * view that can scroll.
2684     *
2685     * @see #getOverScrollMode()
2686     * @see #setOverScrollMode(int)
2687     */
2688    public static final int OVER_SCROLL_ALWAYS = 0;
2689
2690    /**
2691     * Allow a user to over-scroll this view only if the content is large
2692     * enough to meaningfully scroll, provided it is a view that can scroll.
2693     *
2694     * @see #getOverScrollMode()
2695     * @see #setOverScrollMode(int)
2696     */
2697    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2698
2699    /**
2700     * Never allow a user to over-scroll this view.
2701     *
2702     * @see #getOverScrollMode()
2703     * @see #setOverScrollMode(int)
2704     */
2705    public static final int OVER_SCROLL_NEVER = 2;
2706
2707    /**
2708     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2709     * requested the system UI (status bar) to be visible (the default).
2710     *
2711     * @see #setSystemUiVisibility(int)
2712     */
2713    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2714
2715    /**
2716     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2717     * system UI to enter an unobtrusive "low profile" mode.
2718     *
2719     * <p>This is for use in games, book readers, video players, or any other
2720     * "immersive" application where the usual system chrome is deemed too distracting.
2721     *
2722     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2723     *
2724     * @see #setSystemUiVisibility(int)
2725     */
2726    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2727
2728    /**
2729     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2730     * system navigation be temporarily hidden.
2731     *
2732     * <p>This is an even less obtrusive state than that called for by
2733     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2734     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2735     * those to disappear. This is useful (in conjunction with the
2736     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2737     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2738     * window flags) for displaying content using every last pixel on the display.
2739     *
2740     * <p>There is a limitation: because navigation controls are so important, the least user
2741     * interaction will cause them to reappear immediately.  When this happens, both
2742     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2743     * so that both elements reappear at the same time.
2744     *
2745     * @see #setSystemUiVisibility(int)
2746     */
2747    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2748
2749    /**
2750     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2751     * into the normal fullscreen mode so that its content can take over the screen
2752     * while still allowing the user to interact with the application.
2753     *
2754     * <p>This has the same visual effect as
2755     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2756     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2757     * meaning that non-critical screen decorations (such as the status bar) will be
2758     * hidden while the user is in the View's window, focusing the experience on
2759     * that content.  Unlike the window flag, if you are using ActionBar in
2760     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2761     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2762     * hide the action bar.
2763     *
2764     * <p>This approach to going fullscreen is best used over the window flag when
2765     * it is a transient state -- that is, the application does this at certain
2766     * points in its user interaction where it wants to allow the user to focus
2767     * on content, but not as a continuous state.  For situations where the application
2768     * would like to simply stay full screen the entire time (such as a game that
2769     * wants to take over the screen), the
2770     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2771     * is usually a better approach.  The state set here will be removed by the system
2772     * in various situations (such as the user moving to another application) like
2773     * the other system UI states.
2774     *
2775     * <p>When using this flag, the application should provide some easy facility
2776     * for the user to go out of it.  A common example would be in an e-book
2777     * reader, where tapping on the screen brings back whatever screen and UI
2778     * decorations that had been hidden while the user was immersed in reading
2779     * the book.
2780     *
2781     * @see #setSystemUiVisibility(int)
2782     */
2783    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2784
2785    /**
2786     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2787     * flags, we would like a stable view of the content insets given to
2788     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2789     * will always represent the worst case that the application can expect
2790     * as a continuous state.  In the stock Android UI this is the space for
2791     * the system bar, nav bar, and status bar, but not more transient elements
2792     * such as an input method.
2793     *
2794     * The stable layout your UI sees is based on the system UI modes you can
2795     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2796     * then you will get a stable layout for changes of the
2797     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2798     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2799     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2800     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2801     * with a stable layout.  (Note that you should avoid using
2802     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2803     *
2804     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2805     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2806     * then a hidden status bar will be considered a "stable" state for purposes
2807     * here.  This allows your UI to continually hide the status bar, while still
2808     * using the system UI flags to hide the action bar while still retaining
2809     * a stable layout.  Note that changing the window fullscreen flag will never
2810     * provide a stable layout for a clean transition.
2811     *
2812     * <p>If you are using ActionBar in
2813     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2814     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2815     * insets it adds to those given to the application.
2816     */
2817    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2818
2819    /**
2820     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2821     * to be laid out as if it has requested
2822     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2823     * allows it to avoid artifacts when switching in and out of that mode, at
2824     * the expense that some of its user interface may be covered by screen
2825     * decorations when they are shown.  You can perform layout of your inner
2826     * UI elements to account for the navigation system UI through the
2827     * {@link #fitSystemWindows(Rect)} method.
2828     */
2829    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2830
2831    /**
2832     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2833     * to be laid out as if it has requested
2834     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2835     * allows it to avoid artifacts when switching in and out of that mode, at
2836     * the expense that some of its user interface may be covered by screen
2837     * decorations when they are shown.  You can perform layout of your inner
2838     * UI elements to account for non-fullscreen system UI through the
2839     * {@link #fitSystemWindows(Rect)} method.
2840     */
2841    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2842
2843    /**
2844     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2845     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2846     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2847     * user interaction.
2848     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2849     * has an effect when used in combination with that flag.</p>
2850     */
2851    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2852
2853    /**
2854     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2855     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2856     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2857     * experience while also hiding the system bars.  If this flag is not set,
2858     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2859     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2860     * if the user swipes from the top of the screen.
2861     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2862     * system gestures, such as swiping from the top of the screen.  These transient system bars
2863     * will overlay app’s content, may have some degree of transparency, and will automatically
2864     * hide after a short timeout.
2865     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2866     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2867     * with one or both of those flags.</p>
2868     */
2869    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2870
2871    /**
2872     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2873     * is compatible with light status bar backgrounds.
2874     *
2875     * <p>For this to take effect, the window must request
2876     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2877     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2878     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2879     *         FLAG_TRANSLUCENT_STATUS}.
2880     *
2881     * @see android.R.attr#windowLightStatusBar
2882     */
2883    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2884
2885    /**
2886     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2887     */
2888    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2889
2890    /**
2891     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2892     */
2893    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2894
2895    /**
2896     * @hide
2897     *
2898     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2899     * out of the public fields to keep the undefined bits out of the developer's way.
2900     *
2901     * Flag to make the status bar not expandable.  Unless you also
2902     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2903     */
2904    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2905
2906    /**
2907     * @hide
2908     *
2909     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2910     * out of the public fields to keep the undefined bits out of the developer's way.
2911     *
2912     * Flag to hide notification icons and scrolling ticker text.
2913     */
2914    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2915
2916    /**
2917     * @hide
2918     *
2919     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2920     * out of the public fields to keep the undefined bits out of the developer's way.
2921     *
2922     * Flag to disable incoming notification alerts.  This will not block
2923     * icons, but it will block sound, vibrating and other visual or aural notifications.
2924     */
2925    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2926
2927    /**
2928     * @hide
2929     *
2930     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2931     * out of the public fields to keep the undefined bits out of the developer's way.
2932     *
2933     * Flag to hide only the scrolling ticker.  Note that
2934     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2935     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2936     */
2937    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2938
2939    /**
2940     * @hide
2941     *
2942     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2943     * out of the public fields to keep the undefined bits out of the developer's way.
2944     *
2945     * Flag to hide the center system info area.
2946     */
2947    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2948
2949    /**
2950     * @hide
2951     *
2952     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2953     * out of the public fields to keep the undefined bits out of the developer's way.
2954     *
2955     * Flag to hide only the home button.  Don't use this
2956     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2957     */
2958    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2959
2960    /**
2961     * @hide
2962     *
2963     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2964     * out of the public fields to keep the undefined bits out of the developer's way.
2965     *
2966     * Flag to hide only the back button. Don't use this
2967     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2968     */
2969    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2970
2971    /**
2972     * @hide
2973     *
2974     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2975     * out of the public fields to keep the undefined bits out of the developer's way.
2976     *
2977     * Flag to hide only the clock.  You might use this if your activity has
2978     * its own clock making the status bar's clock redundant.
2979     */
2980    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2981
2982    /**
2983     * @hide
2984     *
2985     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2986     * out of the public fields to keep the undefined bits out of the developer's way.
2987     *
2988     * Flag to hide only the recent apps button. Don't use this
2989     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2990     */
2991    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2992
2993    /**
2994     * @hide
2995     *
2996     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2997     * out of the public fields to keep the undefined bits out of the developer's way.
2998     *
2999     * Flag to disable the global search gesture. Don't use this
3000     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3001     */
3002    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3003
3004    /**
3005     * @hide
3006     *
3007     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3008     * out of the public fields to keep the undefined bits out of the developer's way.
3009     *
3010     * Flag to specify that the status bar is displayed in transient mode.
3011     */
3012    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3013
3014    /**
3015     * @hide
3016     *
3017     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3018     * out of the public fields to keep the undefined bits out of the developer's way.
3019     *
3020     * Flag to specify that the navigation bar is displayed in transient mode.
3021     */
3022    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3023
3024    /**
3025     * @hide
3026     *
3027     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3028     * out of the public fields to keep the undefined bits out of the developer's way.
3029     *
3030     * Flag to specify that the hidden status bar would like to be shown.
3031     */
3032    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3033
3034    /**
3035     * @hide
3036     *
3037     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3038     * out of the public fields to keep the undefined bits out of the developer's way.
3039     *
3040     * Flag to specify that the hidden navigation bar would like to be shown.
3041     */
3042    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3043
3044    /**
3045     * @hide
3046     *
3047     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3048     * out of the public fields to keep the undefined bits out of the developer's way.
3049     *
3050     * Flag to specify that the status bar is displayed in translucent mode.
3051     */
3052    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3053
3054    /**
3055     * @hide
3056     *
3057     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3058     * out of the public fields to keep the undefined bits out of the developer's way.
3059     *
3060     * Flag to specify that the navigation bar is displayed in translucent mode.
3061     */
3062    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3063
3064    /**
3065     * @hide
3066     *
3067     * Whether Recents is visible or not.
3068     */
3069    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3070
3071    /**
3072     * @hide
3073     *
3074     * Whether the TV's picture-in-picture is visible or not.
3075     */
3076    public static final int TV_PICTURE_IN_PICTURE_VISIBLE = 0x00010000;
3077
3078    /**
3079     * @hide
3080     *
3081     * Makes navigation bar transparent (but not the status bar).
3082     */
3083    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3084
3085    /**
3086     * @hide
3087     *
3088     * Makes status bar transparent (but not the navigation bar).
3089     */
3090    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3091
3092    /**
3093     * @hide
3094     *
3095     * Makes both status bar and navigation bar transparent.
3096     */
3097    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3098            | STATUS_BAR_TRANSPARENT;
3099
3100    /**
3101     * @hide
3102     */
3103    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3104
3105    /**
3106     * These are the system UI flags that can be cleared by events outside
3107     * of an application.  Currently this is just the ability to tap on the
3108     * screen while hiding the navigation bar to have it return.
3109     * @hide
3110     */
3111    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3112            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3113            | SYSTEM_UI_FLAG_FULLSCREEN;
3114
3115    /**
3116     * Flags that can impact the layout in relation to system UI.
3117     */
3118    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3119            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3120            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3121
3122    /** @hide */
3123    @IntDef(flag = true,
3124            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3125    @Retention(RetentionPolicy.SOURCE)
3126    public @interface FindViewFlags {}
3127
3128    /**
3129     * Find views that render the specified text.
3130     *
3131     * @see #findViewsWithText(ArrayList, CharSequence, int)
3132     */
3133    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3134
3135    /**
3136     * Find find views that contain the specified content description.
3137     *
3138     * @see #findViewsWithText(ArrayList, CharSequence, int)
3139     */
3140    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3141
3142    /**
3143     * Find views that contain {@link AccessibilityNodeProvider}. Such
3144     * a View is a root of virtual view hierarchy and may contain the searched
3145     * text. If this flag is set Views with providers are automatically
3146     * added and it is a responsibility of the client to call the APIs of
3147     * the provider to determine whether the virtual tree rooted at this View
3148     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3149     * representing the virtual views with this text.
3150     *
3151     * @see #findViewsWithText(ArrayList, CharSequence, int)
3152     *
3153     * @hide
3154     */
3155    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3156
3157    /**
3158     * The undefined cursor position.
3159     *
3160     * @hide
3161     */
3162    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3163
3164    /**
3165     * Indicates that the screen has changed state and is now off.
3166     *
3167     * @see #onScreenStateChanged(int)
3168     */
3169    public static final int SCREEN_STATE_OFF = 0x0;
3170
3171    /**
3172     * Indicates that the screen has changed state and is now on.
3173     *
3174     * @see #onScreenStateChanged(int)
3175     */
3176    public static final int SCREEN_STATE_ON = 0x1;
3177
3178    /**
3179     * Indicates no axis of view scrolling.
3180     */
3181    public static final int SCROLL_AXIS_NONE = 0;
3182
3183    /**
3184     * Indicates scrolling along the horizontal axis.
3185     */
3186    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3187
3188    /**
3189     * Indicates scrolling along the vertical axis.
3190     */
3191    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3192
3193    /**
3194     * Controls the over-scroll mode for this view.
3195     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3196     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3197     * and {@link #OVER_SCROLL_NEVER}.
3198     */
3199    private int mOverScrollMode;
3200
3201    /**
3202     * The parent this view is attached to.
3203     * {@hide}
3204     *
3205     * @see #getParent()
3206     */
3207    protected ViewParent mParent;
3208
3209    /**
3210     * {@hide}
3211     */
3212    AttachInfo mAttachInfo;
3213
3214    /**
3215     * {@hide}
3216     */
3217    @ViewDebug.ExportedProperty(flagMapping = {
3218        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3219                name = "FORCE_LAYOUT"),
3220        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3221                name = "LAYOUT_REQUIRED"),
3222        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3223            name = "DRAWING_CACHE_INVALID", outputIf = false),
3224        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3225        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3226        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3227        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3228    }, formatToHexString = true)
3229    int mPrivateFlags;
3230    int mPrivateFlags2;
3231    int mPrivateFlags3;
3232
3233    /**
3234     * This view's request for the visibility of the status bar.
3235     * @hide
3236     */
3237    @ViewDebug.ExportedProperty(flagMapping = {
3238        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3239                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3240                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3241        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3242                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3243                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3244        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3245                                equals = SYSTEM_UI_FLAG_VISIBLE,
3246                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3247    }, formatToHexString = true)
3248    int mSystemUiVisibility;
3249
3250    /**
3251     * Reference count for transient state.
3252     * @see #setHasTransientState(boolean)
3253     */
3254    int mTransientStateCount = 0;
3255
3256    /**
3257     * Count of how many windows this view has been attached to.
3258     */
3259    int mWindowAttachCount;
3260
3261    /**
3262     * The layout parameters associated with this view and used by the parent
3263     * {@link android.view.ViewGroup} to determine how this view should be
3264     * laid out.
3265     * {@hide}
3266     */
3267    protected ViewGroup.LayoutParams mLayoutParams;
3268
3269    /**
3270     * The view flags hold various views states.
3271     * {@hide}
3272     */
3273    @ViewDebug.ExportedProperty(formatToHexString = true)
3274    int mViewFlags;
3275
3276    static class TransformationInfo {
3277        /**
3278         * The transform matrix for the View. This transform is calculated internally
3279         * based on the translation, rotation, and scale properties.
3280         *
3281         * Do *not* use this variable directly; instead call getMatrix(), which will
3282         * load the value from the View's RenderNode.
3283         */
3284        private final Matrix mMatrix = new Matrix();
3285
3286        /**
3287         * The inverse transform matrix for the View. This transform is calculated
3288         * internally based on the translation, rotation, and scale properties.
3289         *
3290         * Do *not* use this variable directly; instead call getInverseMatrix(),
3291         * which will load the value from the View's RenderNode.
3292         */
3293        private Matrix mInverseMatrix;
3294
3295        /**
3296         * The opacity of the View. This is a value from 0 to 1, where 0 means
3297         * completely transparent and 1 means completely opaque.
3298         */
3299        @ViewDebug.ExportedProperty
3300        float mAlpha = 1f;
3301
3302        /**
3303         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3304         * property only used by transitions, which is composited with the other alpha
3305         * values to calculate the final visual alpha value.
3306         */
3307        float mTransitionAlpha = 1f;
3308    }
3309
3310    TransformationInfo mTransformationInfo;
3311
3312    /**
3313     * Current clip bounds. to which all drawing of this view are constrained.
3314     */
3315    Rect mClipBounds = null;
3316
3317    private boolean mLastIsOpaque;
3318
3319    /**
3320     * The distance in pixels from the left edge of this view's parent
3321     * to the left edge of this view.
3322     * {@hide}
3323     */
3324    @ViewDebug.ExportedProperty(category = "layout")
3325    protected int mLeft;
3326    /**
3327     * The distance in pixels from the left edge of this view's parent
3328     * to the right edge of this view.
3329     * {@hide}
3330     */
3331    @ViewDebug.ExportedProperty(category = "layout")
3332    protected int mRight;
3333    /**
3334     * The distance in pixels from the top edge of this view's parent
3335     * to the top edge of this view.
3336     * {@hide}
3337     */
3338    @ViewDebug.ExportedProperty(category = "layout")
3339    protected int mTop;
3340    /**
3341     * The distance in pixels from the top edge of this view's parent
3342     * to the bottom edge of this view.
3343     * {@hide}
3344     */
3345    @ViewDebug.ExportedProperty(category = "layout")
3346    protected int mBottom;
3347
3348    /**
3349     * The offset, in pixels, by which the content of this view is scrolled
3350     * horizontally.
3351     * {@hide}
3352     */
3353    @ViewDebug.ExportedProperty(category = "scrolling")
3354    protected int mScrollX;
3355    /**
3356     * The offset, in pixels, by which the content of this view is scrolled
3357     * vertically.
3358     * {@hide}
3359     */
3360    @ViewDebug.ExportedProperty(category = "scrolling")
3361    protected int mScrollY;
3362
3363    /**
3364     * The left padding in pixels, that is the distance in pixels between the
3365     * left edge of this view and the left edge of its content.
3366     * {@hide}
3367     */
3368    @ViewDebug.ExportedProperty(category = "padding")
3369    protected int mPaddingLeft = 0;
3370    /**
3371     * The right padding in pixels, that is the distance in pixels between the
3372     * right edge of this view and the right edge of its content.
3373     * {@hide}
3374     */
3375    @ViewDebug.ExportedProperty(category = "padding")
3376    protected int mPaddingRight = 0;
3377    /**
3378     * The top padding in pixels, that is the distance in pixels between the
3379     * top edge of this view and the top edge of its content.
3380     * {@hide}
3381     */
3382    @ViewDebug.ExportedProperty(category = "padding")
3383    protected int mPaddingTop;
3384    /**
3385     * The bottom padding in pixels, that is the distance in pixels between the
3386     * bottom edge of this view and the bottom edge of its content.
3387     * {@hide}
3388     */
3389    @ViewDebug.ExportedProperty(category = "padding")
3390    protected int mPaddingBottom;
3391
3392    /**
3393     * The layout insets in pixels, that is the distance in pixels between the
3394     * visible edges of this view its bounds.
3395     */
3396    private Insets mLayoutInsets;
3397
3398    /**
3399     * Briefly describes the view and is primarily used for accessibility support.
3400     */
3401    private CharSequence mContentDescription;
3402
3403    /**
3404     * Specifies the id of a view for which this view serves as a label for
3405     * accessibility purposes.
3406     */
3407    private int mLabelForId = View.NO_ID;
3408
3409    /**
3410     * Predicate for matching labeled view id with its label for
3411     * accessibility purposes.
3412     */
3413    private MatchLabelForPredicate mMatchLabelForPredicate;
3414
3415    /**
3416     * Specifies a view before which this one is visited in accessibility traversal.
3417     */
3418    private int mAccessibilityTraversalBeforeId = NO_ID;
3419
3420    /**
3421     * Specifies a view after which this one is visited in accessibility traversal.
3422     */
3423    private int mAccessibilityTraversalAfterId = NO_ID;
3424
3425    /**
3426     * Predicate for matching a view by its id.
3427     */
3428    private MatchIdPredicate mMatchIdPredicate;
3429
3430    /**
3431     * Cache the paddingRight set by the user to append to the scrollbar's size.
3432     *
3433     * @hide
3434     */
3435    @ViewDebug.ExportedProperty(category = "padding")
3436    protected int mUserPaddingRight;
3437
3438    /**
3439     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3440     *
3441     * @hide
3442     */
3443    @ViewDebug.ExportedProperty(category = "padding")
3444    protected int mUserPaddingBottom;
3445
3446    /**
3447     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3448     *
3449     * @hide
3450     */
3451    @ViewDebug.ExportedProperty(category = "padding")
3452    protected int mUserPaddingLeft;
3453
3454    /**
3455     * Cache the paddingStart set by the user to append to the scrollbar's size.
3456     *
3457     */
3458    @ViewDebug.ExportedProperty(category = "padding")
3459    int mUserPaddingStart;
3460
3461    /**
3462     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3463     *
3464     */
3465    @ViewDebug.ExportedProperty(category = "padding")
3466    int mUserPaddingEnd;
3467
3468    /**
3469     * Cache initial left padding.
3470     *
3471     * @hide
3472     */
3473    int mUserPaddingLeftInitial;
3474
3475    /**
3476     * Cache initial right padding.
3477     *
3478     * @hide
3479     */
3480    int mUserPaddingRightInitial;
3481
3482    /**
3483     * Default undefined padding
3484     */
3485    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3486
3487    /**
3488     * Cache if a left padding has been defined
3489     */
3490    private boolean mLeftPaddingDefined = false;
3491
3492    /**
3493     * Cache if a right padding has been defined
3494     */
3495    private boolean mRightPaddingDefined = false;
3496
3497    /**
3498     * @hide
3499     */
3500    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3501    /**
3502     * @hide
3503     */
3504    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3505
3506    private LongSparseLongArray mMeasureCache;
3507
3508    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3509    private Drawable mBackground;
3510    private TintInfo mBackgroundTint;
3511
3512    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3513    private ForegroundInfo mForegroundInfo;
3514
3515    private Drawable mScrollIndicatorDrawable;
3516
3517    /**
3518     * RenderNode used for backgrounds.
3519     * <p>
3520     * When non-null and valid, this is expected to contain an up-to-date copy
3521     * of the background drawable. It is cleared on temporary detach, and reset
3522     * on cleanup.
3523     */
3524    private RenderNode mBackgroundRenderNode;
3525
3526    private int mBackgroundResource;
3527    private boolean mBackgroundSizeChanged;
3528
3529    private String mTransitionName;
3530
3531    static class TintInfo {
3532        ColorStateList mTintList;
3533        PorterDuff.Mode mTintMode;
3534        boolean mHasTintMode;
3535        boolean mHasTintList;
3536    }
3537
3538    private static class ForegroundInfo {
3539        private Drawable mDrawable;
3540        private TintInfo mTintInfo;
3541        private int mGravity = Gravity.FILL;
3542        private boolean mInsidePadding = true;
3543        private boolean mBoundsChanged = true;
3544        private final Rect mSelfBounds = new Rect();
3545        private final Rect mOverlayBounds = new Rect();
3546    }
3547
3548    static class ListenerInfo {
3549        /**
3550         * Listener used to dispatch focus change events.
3551         * This field should be made private, so it is hidden from the SDK.
3552         * {@hide}
3553         */
3554        protected OnFocusChangeListener mOnFocusChangeListener;
3555
3556        /**
3557         * Listeners for layout change events.
3558         */
3559        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3560
3561        protected OnScrollChangeListener mOnScrollChangeListener;
3562
3563        /**
3564         * Listeners for attach events.
3565         */
3566        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3567
3568        /**
3569         * Listener used to dispatch click events.
3570         * This field should be made private, so it is hidden from the SDK.
3571         * {@hide}
3572         */
3573        public OnClickListener mOnClickListener;
3574
3575        /**
3576         * Listener used to dispatch long click events.
3577         * This field should be made private, so it is hidden from the SDK.
3578         * {@hide}
3579         */
3580        protected OnLongClickListener mOnLongClickListener;
3581
3582        /**
3583         * Listener used to dispatch context click events. This field should be made private, so it
3584         * is hidden from the SDK.
3585         * {@hide}
3586         */
3587        protected OnContextClickListener mOnContextClickListener;
3588
3589        /**
3590         * Listener used to build the context menu.
3591         * This field should be made private, so it is hidden from the SDK.
3592         * {@hide}
3593         */
3594        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3595
3596        private OnKeyListener mOnKeyListener;
3597
3598        private OnTouchListener mOnTouchListener;
3599
3600        private OnHoverListener mOnHoverListener;
3601
3602        private OnGenericMotionListener mOnGenericMotionListener;
3603
3604        private OnDragListener mOnDragListener;
3605
3606        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3607
3608        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3609    }
3610
3611    ListenerInfo mListenerInfo;
3612
3613    // Temporary values used to hold (x,y) coordinates when delegating from the
3614    // two-arg performLongClick() method to the legacy no-arg version.
3615    private float mLongClickX = Float.NaN;
3616    private float mLongClickY = Float.NaN;
3617
3618    /**
3619     * The application environment this view lives in.
3620     * This field should be made private, so it is hidden from the SDK.
3621     * {@hide}
3622     */
3623    @ViewDebug.ExportedProperty(deepExport = true)
3624    protected Context mContext;
3625
3626    private final Resources mResources;
3627
3628    private ScrollabilityCache mScrollCache;
3629
3630    private int[] mDrawableState = null;
3631
3632    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3633
3634    /**
3635     * Animator that automatically runs based on state changes.
3636     */
3637    private StateListAnimator mStateListAnimator;
3638
3639    /**
3640     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3641     * the user may specify which view to go to next.
3642     */
3643    private int mNextFocusLeftId = View.NO_ID;
3644
3645    /**
3646     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3647     * the user may specify which view to go to next.
3648     */
3649    private int mNextFocusRightId = View.NO_ID;
3650
3651    /**
3652     * When this view has focus and the next focus is {@link #FOCUS_UP},
3653     * the user may specify which view to go to next.
3654     */
3655    private int mNextFocusUpId = View.NO_ID;
3656
3657    /**
3658     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3659     * the user may specify which view to go to next.
3660     */
3661    private int mNextFocusDownId = View.NO_ID;
3662
3663    /**
3664     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3665     * the user may specify which view to go to next.
3666     */
3667    int mNextFocusForwardId = View.NO_ID;
3668
3669    private CheckForLongPress mPendingCheckForLongPress;
3670    private CheckForTap mPendingCheckForTap = null;
3671    private PerformClick mPerformClick;
3672    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3673
3674    private UnsetPressedState mUnsetPressedState;
3675
3676    /**
3677     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3678     * up event while a long press is invoked as soon as the long press duration is reached, so
3679     * a long press could be performed before the tap is checked, in which case the tap's action
3680     * should not be invoked.
3681     */
3682    private boolean mHasPerformedLongPress;
3683
3684    /**
3685     * Whether a context click button is currently pressed down. This is true when the stylus is
3686     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3687     * pressed. This is false once the button is released or if the stylus has been lifted.
3688     */
3689    private boolean mInContextButtonPress;
3690
3691    /**
3692     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3693     * true after a stylus button press has occured, when the next up event should not be recognized
3694     * as a tap.
3695     */
3696    private boolean mIgnoreNextUpEvent;
3697
3698    /**
3699     * The minimum height of the view. We'll try our best to have the height
3700     * of this view to at least this amount.
3701     */
3702    @ViewDebug.ExportedProperty(category = "measurement")
3703    private int mMinHeight;
3704
3705    /**
3706     * The minimum width of the view. We'll try our best to have the width
3707     * of this view to at least this amount.
3708     */
3709    @ViewDebug.ExportedProperty(category = "measurement")
3710    private int mMinWidth;
3711
3712    /**
3713     * The delegate to handle touch events that are physically in this view
3714     * but should be handled by another view.
3715     */
3716    private TouchDelegate mTouchDelegate = null;
3717
3718    /**
3719     * Solid color to use as a background when creating the drawing cache. Enables
3720     * the cache to use 16 bit bitmaps instead of 32 bit.
3721     */
3722    private int mDrawingCacheBackgroundColor = 0;
3723
3724    /**
3725     * Special tree observer used when mAttachInfo is null.
3726     */
3727    private ViewTreeObserver mFloatingTreeObserver;
3728
3729    /**
3730     * Cache the touch slop from the context that created the view.
3731     */
3732    private int mTouchSlop;
3733
3734    /**
3735     * Object that handles automatic animation of view properties.
3736     */
3737    private ViewPropertyAnimator mAnimator = null;
3738
3739    /**
3740     * List of registered FrameMetricsObservers.
3741     */
3742    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3743
3744    /**
3745     * Flag indicating that a drag can cross window boundaries.  When
3746     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3747     * with this flag set, all visible applications will be able to participate
3748     * in the drag operation and receive the dragged content.
3749     *
3750     * If this is the only flag set, then the drag recipient will only have access to text data
3751     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3752     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags.
3753     */
3754    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3755
3756    /**
3757     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3758     * request read access to the content URI(s) contained in the {@link ClipData} object.
3759     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3760     */
3761    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3762
3763    /**
3764     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3765     * request write access to the content URI(s) contained in the {@link ClipData} object.
3766     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3767     */
3768    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3769
3770    /**
3771     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3772     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3773     * reboots until explicitly revoked with
3774     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3775     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3776     */
3777    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3778            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3779
3780    /**
3781     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3782     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3783     * match against the original granted URI.
3784     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3785     */
3786    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3787            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3788
3789    /**
3790     * Flag indicating that the drag shadow will be opaque.  When
3791     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3792     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3793     */
3794    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3795
3796    /**
3797     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3798     */
3799    private float mVerticalScrollFactor;
3800
3801    /**
3802     * Position of the vertical scroll bar.
3803     */
3804    private int mVerticalScrollbarPosition;
3805
3806    /**
3807     * Position the scroll bar at the default position as determined by the system.
3808     */
3809    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3810
3811    /**
3812     * Position the scroll bar along the left edge.
3813     */
3814    public static final int SCROLLBAR_POSITION_LEFT = 1;
3815
3816    /**
3817     * Position the scroll bar along the right edge.
3818     */
3819    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3820
3821    /**
3822     * Indicates that the view does not have a layer.
3823     *
3824     * @see #getLayerType()
3825     * @see #setLayerType(int, android.graphics.Paint)
3826     * @see #LAYER_TYPE_SOFTWARE
3827     * @see #LAYER_TYPE_HARDWARE
3828     */
3829    public static final int LAYER_TYPE_NONE = 0;
3830
3831    /**
3832     * <p>Indicates that the view has a software layer. A software layer is backed
3833     * by a bitmap and causes the view to be rendered using Android's software
3834     * rendering pipeline, even if hardware acceleration is enabled.</p>
3835     *
3836     * <p>Software layers have various usages:</p>
3837     * <p>When the application is not using hardware acceleration, a software layer
3838     * is useful to apply a specific color filter and/or blending mode and/or
3839     * translucency to a view and all its children.</p>
3840     * <p>When the application is using hardware acceleration, a software layer
3841     * is useful to render drawing primitives not supported by the hardware
3842     * accelerated pipeline. It can also be used to cache a complex view tree
3843     * into a texture and reduce the complexity of drawing operations. For instance,
3844     * when animating a complex view tree with a translation, a software layer can
3845     * be used to render the view tree only once.</p>
3846     * <p>Software layers should be avoided when the affected view tree updates
3847     * often. Every update will require to re-render the software layer, which can
3848     * potentially be slow (particularly when hardware acceleration is turned on
3849     * since the layer will have to be uploaded into a hardware texture after every
3850     * update.)</p>
3851     *
3852     * @see #getLayerType()
3853     * @see #setLayerType(int, android.graphics.Paint)
3854     * @see #LAYER_TYPE_NONE
3855     * @see #LAYER_TYPE_HARDWARE
3856     */
3857    public static final int LAYER_TYPE_SOFTWARE = 1;
3858
3859    /**
3860     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3861     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3862     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3863     * rendering pipeline, but only if hardware acceleration is turned on for the
3864     * view hierarchy. When hardware acceleration is turned off, hardware layers
3865     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3866     *
3867     * <p>A hardware layer is useful to apply a specific color filter and/or
3868     * blending mode and/or translucency to a view and all its children.</p>
3869     * <p>A hardware layer can be used to cache a complex view tree into a
3870     * texture and reduce the complexity of drawing operations. For instance,
3871     * when animating a complex view tree with a translation, a hardware layer can
3872     * be used to render the view tree only once.</p>
3873     * <p>A hardware layer can also be used to increase the rendering quality when
3874     * rotation transformations are applied on a view. It can also be used to
3875     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3876     *
3877     * @see #getLayerType()
3878     * @see #setLayerType(int, android.graphics.Paint)
3879     * @see #LAYER_TYPE_NONE
3880     * @see #LAYER_TYPE_SOFTWARE
3881     */
3882    public static final int LAYER_TYPE_HARDWARE = 2;
3883
3884    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3885            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3886            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3887            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3888    })
3889    int mLayerType = LAYER_TYPE_NONE;
3890    Paint mLayerPaint;
3891
3892    /**
3893     * Set to true when drawing cache is enabled and cannot be created.
3894     *
3895     * @hide
3896     */
3897    public boolean mCachingFailed;
3898    private Bitmap mDrawingCache;
3899    private Bitmap mUnscaledDrawingCache;
3900
3901    /**
3902     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3903     * <p>
3904     * When non-null and valid, this is expected to contain an up-to-date copy
3905     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3906     * cleanup.
3907     */
3908    final RenderNode mRenderNode;
3909
3910    /**
3911     * Set to true when the view is sending hover accessibility events because it
3912     * is the innermost hovered view.
3913     */
3914    private boolean mSendingHoverAccessibilityEvents;
3915
3916    /**
3917     * Delegate for injecting accessibility functionality.
3918     */
3919    AccessibilityDelegate mAccessibilityDelegate;
3920
3921    /**
3922     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3923     * and add/remove objects to/from the overlay directly through the Overlay methods.
3924     */
3925    ViewOverlay mOverlay;
3926
3927    /**
3928     * The currently active parent view for receiving delegated nested scrolling events.
3929     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3930     * by {@link #stopNestedScroll()} at the same point where we clear
3931     * requestDisallowInterceptTouchEvent.
3932     */
3933    private ViewParent mNestedScrollingParent;
3934
3935    /**
3936     * Consistency verifier for debugging purposes.
3937     * @hide
3938     */
3939    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3940            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3941                    new InputEventConsistencyVerifier(this, 0) : null;
3942
3943    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3944
3945    private int[] mTempNestedScrollConsumed;
3946
3947    /**
3948     * An overlay is going to draw this View instead of being drawn as part of this
3949     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3950     * when this view is invalidated.
3951     */
3952    GhostView mGhostView;
3953
3954    /**
3955     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3956     * @hide
3957     */
3958    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3959    public String[] mAttributes;
3960
3961    /**
3962     * Maps a Resource id to its name.
3963     */
3964    private static SparseArray<String> mAttributeMap;
3965
3966    /**
3967     * Queue of pending runnables. Used to postpone calls to post() until this
3968     * view is attached and has a handler.
3969     */
3970    private HandlerActionQueue mRunQueue;
3971
3972    /**
3973     * The pointer icon when the mouse hovers on this view. The default is null.
3974     */
3975    private PointerIcon mPointerIcon;
3976
3977    /**
3978     * @hide
3979     */
3980    String mStartActivityRequestWho;
3981
3982    /**
3983     * Simple constructor to use when creating a view from code.
3984     *
3985     * @param context The Context the view is running in, through which it can
3986     *        access the current theme, resources, etc.
3987     */
3988    public View(Context context) {
3989        mContext = context;
3990        mResources = context != null ? context.getResources() : null;
3991        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3992        // Set some flags defaults
3993        mPrivateFlags2 =
3994                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3995                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3996                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3997                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3998                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3999                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4000        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4001        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4002        mUserPaddingStart = UNDEFINED_PADDING;
4003        mUserPaddingEnd = UNDEFINED_PADDING;
4004        mRenderNode = RenderNode.create(getClass().getName(), this);
4005
4006        if (!sCompatibilityDone && context != null) {
4007            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4008
4009            // Older apps may need this compatibility hack for measurement.
4010            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4011
4012            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4013            // of whether a layout was requested on that View.
4014            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4015
4016            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4017
4018            // In M and newer, our widgets can pass a "hint" value in the size
4019            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4020            // know what the expected parent size is going to be, so e.g. list items can size
4021            // themselves at 1/3 the size of their container. It breaks older apps though,
4022            // specifically apps that use some popular open source libraries.
4023            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4024
4025            // Old versions of the platform would give different results from
4026            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4027            // modes, so we always need to run an additional EXACTLY pass.
4028            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4029
4030            // Prior to N, layout params could change without requiring a
4031            // subsequent call to setLayoutParams() and they would usually
4032            // work. Partial layout breaks this assumption.
4033            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4034
4035            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4036            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4037            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4038
4039            sCompatibilityDone = true;
4040        }
4041    }
4042
4043    /**
4044     * Constructor that is called when inflating a view from XML. This is called
4045     * when a view is being constructed from an XML file, supplying attributes
4046     * that were specified in the XML file. This version uses a default style of
4047     * 0, so the only attribute values applied are those in the Context's Theme
4048     * and the given AttributeSet.
4049     *
4050     * <p>
4051     * The method onFinishInflate() will be called after all children have been
4052     * added.
4053     *
4054     * @param context The Context the view is running in, through which it can
4055     *        access the current theme, resources, etc.
4056     * @param attrs The attributes of the XML tag that is inflating the view.
4057     * @see #View(Context, AttributeSet, int)
4058     */
4059    public View(Context context, @Nullable AttributeSet attrs) {
4060        this(context, attrs, 0);
4061    }
4062
4063    /**
4064     * Perform inflation from XML and apply a class-specific base style from a
4065     * theme attribute. This constructor of View allows subclasses to use their
4066     * own base style when they are inflating. For example, a Button class's
4067     * constructor would call this version of the super class constructor and
4068     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4069     * allows the theme's button style to modify all of the base view attributes
4070     * (in particular its background) as well as the Button class's attributes.
4071     *
4072     * @param context The Context the view is running in, through which it can
4073     *        access the current theme, resources, etc.
4074     * @param attrs The attributes of the XML tag that is inflating the view.
4075     * @param defStyleAttr An attribute in the current theme that contains a
4076     *        reference to a style resource that supplies default values for
4077     *        the view. Can be 0 to not look for defaults.
4078     * @see #View(Context, AttributeSet)
4079     */
4080    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4081        this(context, attrs, defStyleAttr, 0);
4082    }
4083
4084    /**
4085     * Perform inflation from XML and apply a class-specific base style from a
4086     * theme attribute or style resource. This constructor of View allows
4087     * subclasses to use their own base style when they are inflating.
4088     * <p>
4089     * When determining the final value of a particular attribute, there are
4090     * four inputs that come into play:
4091     * <ol>
4092     * <li>Any attribute values in the given AttributeSet.
4093     * <li>The style resource specified in the AttributeSet (named "style").
4094     * <li>The default style specified by <var>defStyleAttr</var>.
4095     * <li>The default style specified by <var>defStyleRes</var>.
4096     * <li>The base values in this theme.
4097     * </ol>
4098     * <p>
4099     * Each of these inputs is considered in-order, with the first listed taking
4100     * precedence over the following ones. In other words, if in the
4101     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4102     * , then the button's text will <em>always</em> be black, regardless of
4103     * what is specified in any of the styles.
4104     *
4105     * @param context The Context the view is running in, through which it can
4106     *        access the current theme, resources, etc.
4107     * @param attrs The attributes of the XML tag that is inflating the view.
4108     * @param defStyleAttr An attribute in the current theme that contains a
4109     *        reference to a style resource that supplies default values for
4110     *        the view. Can be 0 to not look for defaults.
4111     * @param defStyleRes A resource identifier of a style resource that
4112     *        supplies default values for the view, used only if
4113     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4114     *        to not look for defaults.
4115     * @see #View(Context, AttributeSet, int)
4116     */
4117    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4118        this(context);
4119
4120        final TypedArray a = context.obtainStyledAttributes(
4121                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4122
4123        if (mDebugViewAttributes) {
4124            saveAttributeData(attrs, a);
4125        }
4126
4127        Drawable background = null;
4128
4129        int leftPadding = -1;
4130        int topPadding = -1;
4131        int rightPadding = -1;
4132        int bottomPadding = -1;
4133        int startPadding = UNDEFINED_PADDING;
4134        int endPadding = UNDEFINED_PADDING;
4135
4136        int padding = -1;
4137
4138        int viewFlagValues = 0;
4139        int viewFlagMasks = 0;
4140
4141        boolean setScrollContainer = false;
4142
4143        int x = 0;
4144        int y = 0;
4145
4146        float tx = 0;
4147        float ty = 0;
4148        float tz = 0;
4149        float elevation = 0;
4150        float rotation = 0;
4151        float rotationX = 0;
4152        float rotationY = 0;
4153        float sx = 1f;
4154        float sy = 1f;
4155        boolean transformSet = false;
4156
4157        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4158        int overScrollMode = mOverScrollMode;
4159        boolean initializeScrollbars = false;
4160        boolean initializeScrollIndicators = false;
4161
4162        boolean startPaddingDefined = false;
4163        boolean endPaddingDefined = false;
4164        boolean leftPaddingDefined = false;
4165        boolean rightPaddingDefined = false;
4166
4167        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4168
4169        final int N = a.getIndexCount();
4170        for (int i = 0; i < N; i++) {
4171            int attr = a.getIndex(i);
4172            switch (attr) {
4173                case com.android.internal.R.styleable.View_background:
4174                    background = a.getDrawable(attr);
4175                    break;
4176                case com.android.internal.R.styleable.View_padding:
4177                    padding = a.getDimensionPixelSize(attr, -1);
4178                    mUserPaddingLeftInitial = padding;
4179                    mUserPaddingRightInitial = padding;
4180                    leftPaddingDefined = true;
4181                    rightPaddingDefined = true;
4182                    break;
4183                 case com.android.internal.R.styleable.View_paddingLeft:
4184                    leftPadding = a.getDimensionPixelSize(attr, -1);
4185                    mUserPaddingLeftInitial = leftPadding;
4186                    leftPaddingDefined = true;
4187                    break;
4188                case com.android.internal.R.styleable.View_paddingTop:
4189                    topPadding = a.getDimensionPixelSize(attr, -1);
4190                    break;
4191                case com.android.internal.R.styleable.View_paddingRight:
4192                    rightPadding = a.getDimensionPixelSize(attr, -1);
4193                    mUserPaddingRightInitial = rightPadding;
4194                    rightPaddingDefined = true;
4195                    break;
4196                case com.android.internal.R.styleable.View_paddingBottom:
4197                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4198                    break;
4199                case com.android.internal.R.styleable.View_paddingStart:
4200                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4201                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4202                    break;
4203                case com.android.internal.R.styleable.View_paddingEnd:
4204                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4205                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4206                    break;
4207                case com.android.internal.R.styleable.View_scrollX:
4208                    x = a.getDimensionPixelOffset(attr, 0);
4209                    break;
4210                case com.android.internal.R.styleable.View_scrollY:
4211                    y = a.getDimensionPixelOffset(attr, 0);
4212                    break;
4213                case com.android.internal.R.styleable.View_alpha:
4214                    setAlpha(a.getFloat(attr, 1f));
4215                    break;
4216                case com.android.internal.R.styleable.View_transformPivotX:
4217                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4218                    break;
4219                case com.android.internal.R.styleable.View_transformPivotY:
4220                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4221                    break;
4222                case com.android.internal.R.styleable.View_translationX:
4223                    tx = a.getDimensionPixelOffset(attr, 0);
4224                    transformSet = true;
4225                    break;
4226                case com.android.internal.R.styleable.View_translationY:
4227                    ty = a.getDimensionPixelOffset(attr, 0);
4228                    transformSet = true;
4229                    break;
4230                case com.android.internal.R.styleable.View_translationZ:
4231                    tz = a.getDimensionPixelOffset(attr, 0);
4232                    transformSet = true;
4233                    break;
4234                case com.android.internal.R.styleable.View_elevation:
4235                    elevation = a.getDimensionPixelOffset(attr, 0);
4236                    transformSet = true;
4237                    break;
4238                case com.android.internal.R.styleable.View_rotation:
4239                    rotation = a.getFloat(attr, 0);
4240                    transformSet = true;
4241                    break;
4242                case com.android.internal.R.styleable.View_rotationX:
4243                    rotationX = a.getFloat(attr, 0);
4244                    transformSet = true;
4245                    break;
4246                case com.android.internal.R.styleable.View_rotationY:
4247                    rotationY = a.getFloat(attr, 0);
4248                    transformSet = true;
4249                    break;
4250                case com.android.internal.R.styleable.View_scaleX:
4251                    sx = a.getFloat(attr, 1f);
4252                    transformSet = true;
4253                    break;
4254                case com.android.internal.R.styleable.View_scaleY:
4255                    sy = a.getFloat(attr, 1f);
4256                    transformSet = true;
4257                    break;
4258                case com.android.internal.R.styleable.View_id:
4259                    mID = a.getResourceId(attr, NO_ID);
4260                    break;
4261                case com.android.internal.R.styleable.View_tag:
4262                    mTag = a.getText(attr);
4263                    break;
4264                case com.android.internal.R.styleable.View_fitsSystemWindows:
4265                    if (a.getBoolean(attr, false)) {
4266                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4267                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4268                    }
4269                    break;
4270                case com.android.internal.R.styleable.View_focusable:
4271                    if (a.getBoolean(attr, false)) {
4272                        viewFlagValues |= FOCUSABLE;
4273                        viewFlagMasks |= FOCUSABLE_MASK;
4274                    }
4275                    break;
4276                case com.android.internal.R.styleable.View_focusableInTouchMode:
4277                    if (a.getBoolean(attr, false)) {
4278                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4279                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4280                    }
4281                    break;
4282                case com.android.internal.R.styleable.View_clickable:
4283                    if (a.getBoolean(attr, false)) {
4284                        viewFlagValues |= CLICKABLE;
4285                        viewFlagMasks |= CLICKABLE;
4286                    }
4287                    break;
4288                case com.android.internal.R.styleable.View_longClickable:
4289                    if (a.getBoolean(attr, false)) {
4290                        viewFlagValues |= LONG_CLICKABLE;
4291                        viewFlagMasks |= LONG_CLICKABLE;
4292                    }
4293                    break;
4294                case com.android.internal.R.styleable.View_contextClickable:
4295                    if (a.getBoolean(attr, false)) {
4296                        viewFlagValues |= CONTEXT_CLICKABLE;
4297                        viewFlagMasks |= CONTEXT_CLICKABLE;
4298                    }
4299                    break;
4300                case com.android.internal.R.styleable.View_saveEnabled:
4301                    if (!a.getBoolean(attr, true)) {
4302                        viewFlagValues |= SAVE_DISABLED;
4303                        viewFlagMasks |= SAVE_DISABLED_MASK;
4304                    }
4305                    break;
4306                case com.android.internal.R.styleable.View_duplicateParentState:
4307                    if (a.getBoolean(attr, false)) {
4308                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4309                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4310                    }
4311                    break;
4312                case com.android.internal.R.styleable.View_visibility:
4313                    final int visibility = a.getInt(attr, 0);
4314                    if (visibility != 0) {
4315                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4316                        viewFlagMasks |= VISIBILITY_MASK;
4317                    }
4318                    break;
4319                case com.android.internal.R.styleable.View_layoutDirection:
4320                    // Clear any layout direction flags (included resolved bits) already set
4321                    mPrivateFlags2 &=
4322                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4323                    // Set the layout direction flags depending on the value of the attribute
4324                    final int layoutDirection = a.getInt(attr, -1);
4325                    final int value = (layoutDirection != -1) ?
4326                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4327                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4328                    break;
4329                case com.android.internal.R.styleable.View_drawingCacheQuality:
4330                    final int cacheQuality = a.getInt(attr, 0);
4331                    if (cacheQuality != 0) {
4332                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4333                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4334                    }
4335                    break;
4336                case com.android.internal.R.styleable.View_contentDescription:
4337                    setContentDescription(a.getString(attr));
4338                    break;
4339                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4340                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4341                    break;
4342                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4343                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4344                    break;
4345                case com.android.internal.R.styleable.View_labelFor:
4346                    setLabelFor(a.getResourceId(attr, NO_ID));
4347                    break;
4348                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4349                    if (!a.getBoolean(attr, true)) {
4350                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4351                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4352                    }
4353                    break;
4354                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4355                    if (!a.getBoolean(attr, true)) {
4356                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4357                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4358                    }
4359                    break;
4360                case R.styleable.View_scrollbars:
4361                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4362                    if (scrollbars != SCROLLBARS_NONE) {
4363                        viewFlagValues |= scrollbars;
4364                        viewFlagMasks |= SCROLLBARS_MASK;
4365                        initializeScrollbars = true;
4366                    }
4367                    break;
4368                //noinspection deprecation
4369                case R.styleable.View_fadingEdge:
4370                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4371                        // Ignore the attribute starting with ICS
4372                        break;
4373                    }
4374                    // With builds < ICS, fall through and apply fading edges
4375                case R.styleable.View_requiresFadingEdge:
4376                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4377                    if (fadingEdge != FADING_EDGE_NONE) {
4378                        viewFlagValues |= fadingEdge;
4379                        viewFlagMasks |= FADING_EDGE_MASK;
4380                        initializeFadingEdgeInternal(a);
4381                    }
4382                    break;
4383                case R.styleable.View_scrollbarStyle:
4384                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4385                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4386                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4387                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4388                    }
4389                    break;
4390                case R.styleable.View_isScrollContainer:
4391                    setScrollContainer = true;
4392                    if (a.getBoolean(attr, false)) {
4393                        setScrollContainer(true);
4394                    }
4395                    break;
4396                case com.android.internal.R.styleable.View_keepScreenOn:
4397                    if (a.getBoolean(attr, false)) {
4398                        viewFlagValues |= KEEP_SCREEN_ON;
4399                        viewFlagMasks |= KEEP_SCREEN_ON;
4400                    }
4401                    break;
4402                case R.styleable.View_filterTouchesWhenObscured:
4403                    if (a.getBoolean(attr, false)) {
4404                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4405                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4406                    }
4407                    break;
4408                case R.styleable.View_nextFocusLeft:
4409                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4410                    break;
4411                case R.styleable.View_nextFocusRight:
4412                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4413                    break;
4414                case R.styleable.View_nextFocusUp:
4415                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4416                    break;
4417                case R.styleable.View_nextFocusDown:
4418                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4419                    break;
4420                case R.styleable.View_nextFocusForward:
4421                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4422                    break;
4423                case R.styleable.View_minWidth:
4424                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4425                    break;
4426                case R.styleable.View_minHeight:
4427                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4428                    break;
4429                case R.styleable.View_onClick:
4430                    if (context.isRestricted()) {
4431                        throw new IllegalStateException("The android:onClick attribute cannot "
4432                                + "be used within a restricted context");
4433                    }
4434
4435                    final String handlerName = a.getString(attr);
4436                    if (handlerName != null) {
4437                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4438                    }
4439                    break;
4440                case R.styleable.View_overScrollMode:
4441                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4442                    break;
4443                case R.styleable.View_verticalScrollbarPosition:
4444                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4445                    break;
4446                case R.styleable.View_layerType:
4447                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4448                    break;
4449                case R.styleable.View_textDirection:
4450                    // Clear any text direction flag already set
4451                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4452                    // Set the text direction flags depending on the value of the attribute
4453                    final int textDirection = a.getInt(attr, -1);
4454                    if (textDirection != -1) {
4455                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4456                    }
4457                    break;
4458                case R.styleable.View_textAlignment:
4459                    // Clear any text alignment flag already set
4460                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4461                    // Set the text alignment flag depending on the value of the attribute
4462                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4463                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4464                    break;
4465                case R.styleable.View_importantForAccessibility:
4466                    setImportantForAccessibility(a.getInt(attr,
4467                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4468                    break;
4469                case R.styleable.View_accessibilityLiveRegion:
4470                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4471                    break;
4472                case R.styleable.View_transitionName:
4473                    setTransitionName(a.getString(attr));
4474                    break;
4475                case R.styleable.View_nestedScrollingEnabled:
4476                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4477                    break;
4478                case R.styleable.View_stateListAnimator:
4479                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4480                            a.getResourceId(attr, 0)));
4481                    break;
4482                case R.styleable.View_backgroundTint:
4483                    // This will get applied later during setBackground().
4484                    if (mBackgroundTint == null) {
4485                        mBackgroundTint = new TintInfo();
4486                    }
4487                    mBackgroundTint.mTintList = a.getColorStateList(
4488                            R.styleable.View_backgroundTint);
4489                    mBackgroundTint.mHasTintList = true;
4490                    break;
4491                case R.styleable.View_backgroundTintMode:
4492                    // This will get applied later during setBackground().
4493                    if (mBackgroundTint == null) {
4494                        mBackgroundTint = new TintInfo();
4495                    }
4496                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4497                            R.styleable.View_backgroundTintMode, -1), null);
4498                    mBackgroundTint.mHasTintMode = true;
4499                    break;
4500                case R.styleable.View_outlineProvider:
4501                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4502                            PROVIDER_BACKGROUND));
4503                    break;
4504                case R.styleable.View_foreground:
4505                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4506                        setForeground(a.getDrawable(attr));
4507                    }
4508                    break;
4509                case R.styleable.View_foregroundGravity:
4510                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4511                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4512                    }
4513                    break;
4514                case R.styleable.View_foregroundTintMode:
4515                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4516                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4517                    }
4518                    break;
4519                case R.styleable.View_foregroundTint:
4520                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4521                        setForegroundTintList(a.getColorStateList(attr));
4522                    }
4523                    break;
4524                case R.styleable.View_foregroundInsidePadding:
4525                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4526                        if (mForegroundInfo == null) {
4527                            mForegroundInfo = new ForegroundInfo();
4528                        }
4529                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4530                                mForegroundInfo.mInsidePadding);
4531                    }
4532                    break;
4533                case R.styleable.View_scrollIndicators:
4534                    final int scrollIndicators =
4535                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4536                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4537                    if (scrollIndicators != 0) {
4538                        mPrivateFlags3 |= scrollIndicators;
4539                        initializeScrollIndicators = true;
4540                    }
4541                    break;
4542                case R.styleable.View_pointerShape:
4543                    final int resourceId = a.getResourceId(attr, 0);
4544                    if (resourceId != 0) {
4545                        setPointerIcon(PointerIcon.loadCustomIcon(
4546                                context.getResources(), resourceId));
4547                    } else {
4548                        final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED);
4549                        if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) {
4550                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape));
4551                        }
4552                    }
4553                    break;
4554                case R.styleable.View_forceHasOverlappingRendering:
4555                    if (a.peekValue(attr) != null) {
4556                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4557                    }
4558                    break;
4559
4560            }
4561        }
4562
4563        setOverScrollMode(overScrollMode);
4564
4565        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4566        // the resolved layout direction). Those cached values will be used later during padding
4567        // resolution.
4568        mUserPaddingStart = startPadding;
4569        mUserPaddingEnd = endPadding;
4570
4571        if (background != null) {
4572            setBackground(background);
4573        }
4574
4575        // setBackground above will record that padding is currently provided by the background.
4576        // If we have padding specified via xml, record that here instead and use it.
4577        mLeftPaddingDefined = leftPaddingDefined;
4578        mRightPaddingDefined = rightPaddingDefined;
4579
4580        if (padding >= 0) {
4581            leftPadding = padding;
4582            topPadding = padding;
4583            rightPadding = padding;
4584            bottomPadding = padding;
4585            mUserPaddingLeftInitial = padding;
4586            mUserPaddingRightInitial = padding;
4587        }
4588
4589        if (isRtlCompatibilityMode()) {
4590            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4591            // left / right padding are used if defined (meaning here nothing to do). If they are not
4592            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4593            // start / end and resolve them as left / right (layout direction is not taken into account).
4594            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4595            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4596            // defined.
4597            if (!mLeftPaddingDefined && startPaddingDefined) {
4598                leftPadding = startPadding;
4599            }
4600            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4601            if (!mRightPaddingDefined && endPaddingDefined) {
4602                rightPadding = endPadding;
4603            }
4604            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4605        } else {
4606            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4607            // values defined. Otherwise, left /right values are used.
4608            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4609            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4610            // defined.
4611            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4612
4613            if (mLeftPaddingDefined && !hasRelativePadding) {
4614                mUserPaddingLeftInitial = leftPadding;
4615            }
4616            if (mRightPaddingDefined && !hasRelativePadding) {
4617                mUserPaddingRightInitial = rightPadding;
4618            }
4619        }
4620
4621        internalSetPadding(
4622                mUserPaddingLeftInitial,
4623                topPadding >= 0 ? topPadding : mPaddingTop,
4624                mUserPaddingRightInitial,
4625                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4626
4627        if (viewFlagMasks != 0) {
4628            setFlags(viewFlagValues, viewFlagMasks);
4629        }
4630
4631        if (initializeScrollbars) {
4632            initializeScrollbarsInternal(a);
4633        }
4634
4635        if (initializeScrollIndicators) {
4636            initializeScrollIndicatorsInternal();
4637        }
4638
4639        a.recycle();
4640
4641        // Needs to be called after mViewFlags is set
4642        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4643            recomputePadding();
4644        }
4645
4646        if (x != 0 || y != 0) {
4647            scrollTo(x, y);
4648        }
4649
4650        if (transformSet) {
4651            setTranslationX(tx);
4652            setTranslationY(ty);
4653            setTranslationZ(tz);
4654            setElevation(elevation);
4655            setRotation(rotation);
4656            setRotationX(rotationX);
4657            setRotationY(rotationY);
4658            setScaleX(sx);
4659            setScaleY(sy);
4660        }
4661
4662        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4663            setScrollContainer(true);
4664        }
4665
4666        computeOpaqueFlags();
4667    }
4668
4669    /**
4670     * An implementation of OnClickListener that attempts to lazily load a
4671     * named click handling method from a parent or ancestor context.
4672     */
4673    private static class DeclaredOnClickListener implements OnClickListener {
4674        private final View mHostView;
4675        private final String mMethodName;
4676
4677        private Method mResolvedMethod;
4678        private Context mResolvedContext;
4679
4680        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4681            mHostView = hostView;
4682            mMethodName = methodName;
4683        }
4684
4685        @Override
4686        public void onClick(@NonNull View v) {
4687            if (mResolvedMethod == null) {
4688                resolveMethod(mHostView.getContext(), mMethodName);
4689            }
4690
4691            try {
4692                mResolvedMethod.invoke(mResolvedContext, v);
4693            } catch (IllegalAccessException e) {
4694                throw new IllegalStateException(
4695                        "Could not execute non-public method for android:onClick", e);
4696            } catch (InvocationTargetException e) {
4697                throw new IllegalStateException(
4698                        "Could not execute method for android:onClick", e);
4699            }
4700        }
4701
4702        @NonNull
4703        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4704            while (context != null) {
4705                try {
4706                    if (!context.isRestricted()) {
4707                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4708                        if (method != null) {
4709                            mResolvedMethod = method;
4710                            mResolvedContext = context;
4711                            return;
4712                        }
4713                    }
4714                } catch (NoSuchMethodException e) {
4715                    // Failed to find method, keep searching up the hierarchy.
4716                }
4717
4718                if (context instanceof ContextWrapper) {
4719                    context = ((ContextWrapper) context).getBaseContext();
4720                } else {
4721                    // Can't search up the hierarchy, null out and fail.
4722                    context = null;
4723                }
4724            }
4725
4726            final int id = mHostView.getId();
4727            final String idText = id == NO_ID ? "" : " with id '"
4728                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4729            throw new IllegalStateException("Could not find method " + mMethodName
4730                    + "(View) in a parent or ancestor Context for android:onClick "
4731                    + "attribute defined on view " + mHostView.getClass() + idText);
4732        }
4733    }
4734
4735    /**
4736     * Non-public constructor for use in testing
4737     */
4738    View() {
4739        mResources = null;
4740        mRenderNode = RenderNode.create(getClass().getName(), this);
4741    }
4742
4743    private static SparseArray<String> getAttributeMap() {
4744        if (mAttributeMap == null) {
4745            mAttributeMap = new SparseArray<>();
4746        }
4747        return mAttributeMap;
4748    }
4749
4750    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4751        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4752        final int indexCount = t.getIndexCount();
4753        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4754
4755        int i = 0;
4756
4757        // Store raw XML attributes.
4758        for (int j = 0; j < attrsCount; ++j) {
4759            attributes[i] = attrs.getAttributeName(j);
4760            attributes[i + 1] = attrs.getAttributeValue(j);
4761            i += 2;
4762        }
4763
4764        // Store resolved styleable attributes.
4765        final Resources res = t.getResources();
4766        final SparseArray<String> attributeMap = getAttributeMap();
4767        for (int j = 0; j < indexCount; ++j) {
4768            final int index = t.getIndex(j);
4769            if (!t.hasValueOrEmpty(index)) {
4770                // Value is undefined. Skip it.
4771                continue;
4772            }
4773
4774            final int resourceId = t.getResourceId(index, 0);
4775            if (resourceId == 0) {
4776                // Value is not a reference. Skip it.
4777                continue;
4778            }
4779
4780            String resourceName = attributeMap.get(resourceId);
4781            if (resourceName == null) {
4782                try {
4783                    resourceName = res.getResourceName(resourceId);
4784                } catch (Resources.NotFoundException e) {
4785                    resourceName = "0x" + Integer.toHexString(resourceId);
4786                }
4787                attributeMap.put(resourceId, resourceName);
4788            }
4789
4790            attributes[i] = resourceName;
4791            attributes[i + 1] = t.getString(index);
4792            i += 2;
4793        }
4794
4795        // Trim to fit contents.
4796        final String[] trimmed = new String[i];
4797        System.arraycopy(attributes, 0, trimmed, 0, i);
4798        mAttributes = trimmed;
4799    }
4800
4801    public String toString() {
4802        StringBuilder out = new StringBuilder(128);
4803        out.append(getClass().getName());
4804        out.append('{');
4805        out.append(Integer.toHexString(System.identityHashCode(this)));
4806        out.append(' ');
4807        switch (mViewFlags&VISIBILITY_MASK) {
4808            case VISIBLE: out.append('V'); break;
4809            case INVISIBLE: out.append('I'); break;
4810            case GONE: out.append('G'); break;
4811            default: out.append('.'); break;
4812        }
4813        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4814        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4815        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4816        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4817        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4818        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4819        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4820        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4821        out.append(' ');
4822        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4823        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4824        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4825        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4826            out.append('p');
4827        } else {
4828            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4829        }
4830        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4831        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4832        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4833        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4834        out.append(' ');
4835        out.append(mLeft);
4836        out.append(',');
4837        out.append(mTop);
4838        out.append('-');
4839        out.append(mRight);
4840        out.append(',');
4841        out.append(mBottom);
4842        final int id = getId();
4843        if (id != NO_ID) {
4844            out.append(" #");
4845            out.append(Integer.toHexString(id));
4846            final Resources r = mResources;
4847            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4848                try {
4849                    String pkgname;
4850                    switch (id&0xff000000) {
4851                        case 0x7f000000:
4852                            pkgname="app";
4853                            break;
4854                        case 0x01000000:
4855                            pkgname="android";
4856                            break;
4857                        default:
4858                            pkgname = r.getResourcePackageName(id);
4859                            break;
4860                    }
4861                    String typename = r.getResourceTypeName(id);
4862                    String entryname = r.getResourceEntryName(id);
4863                    out.append(" ");
4864                    out.append(pkgname);
4865                    out.append(":");
4866                    out.append(typename);
4867                    out.append("/");
4868                    out.append(entryname);
4869                } catch (Resources.NotFoundException e) {
4870                }
4871            }
4872        }
4873        out.append("}");
4874        return out.toString();
4875    }
4876
4877    /**
4878     * <p>
4879     * Initializes the fading edges from a given set of styled attributes. This
4880     * method should be called by subclasses that need fading edges and when an
4881     * instance of these subclasses is created programmatically rather than
4882     * being inflated from XML. This method is automatically called when the XML
4883     * is inflated.
4884     * </p>
4885     *
4886     * @param a the styled attributes set to initialize the fading edges from
4887     *
4888     * @removed
4889     */
4890    protected void initializeFadingEdge(TypedArray a) {
4891        // This method probably shouldn't have been included in the SDK to begin with.
4892        // It relies on 'a' having been initialized using an attribute filter array that is
4893        // not publicly available to the SDK. The old method has been renamed
4894        // to initializeFadingEdgeInternal and hidden for framework use only;
4895        // this one initializes using defaults to make it safe to call for apps.
4896
4897        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4898
4899        initializeFadingEdgeInternal(arr);
4900
4901        arr.recycle();
4902    }
4903
4904    /**
4905     * <p>
4906     * Initializes the fading edges from a given set of styled attributes. This
4907     * method should be called by subclasses that need fading edges and when an
4908     * instance of these subclasses is created programmatically rather than
4909     * being inflated from XML. This method is automatically called when the XML
4910     * is inflated.
4911     * </p>
4912     *
4913     * @param a the styled attributes set to initialize the fading edges from
4914     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4915     */
4916    protected void initializeFadingEdgeInternal(TypedArray a) {
4917        initScrollCache();
4918
4919        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4920                R.styleable.View_fadingEdgeLength,
4921                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4922    }
4923
4924    /**
4925     * Returns the size of the vertical faded edges used to indicate that more
4926     * content in this view is visible.
4927     *
4928     * @return The size in pixels of the vertical faded edge or 0 if vertical
4929     *         faded edges are not enabled for this view.
4930     * @attr ref android.R.styleable#View_fadingEdgeLength
4931     */
4932    public int getVerticalFadingEdgeLength() {
4933        if (isVerticalFadingEdgeEnabled()) {
4934            ScrollabilityCache cache = mScrollCache;
4935            if (cache != null) {
4936                return cache.fadingEdgeLength;
4937            }
4938        }
4939        return 0;
4940    }
4941
4942    /**
4943     * Set the size of the faded edge used to indicate that more content in this
4944     * view is available.  Will not change whether the fading edge is enabled; use
4945     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4946     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4947     * for the vertical or horizontal fading edges.
4948     *
4949     * @param length The size in pixels of the faded edge used to indicate that more
4950     *        content in this view is visible.
4951     */
4952    public void setFadingEdgeLength(int length) {
4953        initScrollCache();
4954        mScrollCache.fadingEdgeLength = length;
4955    }
4956
4957    /**
4958     * Returns the size of the horizontal faded edges used to indicate that more
4959     * content in this view is visible.
4960     *
4961     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4962     *         faded edges are not enabled for this view.
4963     * @attr ref android.R.styleable#View_fadingEdgeLength
4964     */
4965    public int getHorizontalFadingEdgeLength() {
4966        if (isHorizontalFadingEdgeEnabled()) {
4967            ScrollabilityCache cache = mScrollCache;
4968            if (cache != null) {
4969                return cache.fadingEdgeLength;
4970            }
4971        }
4972        return 0;
4973    }
4974
4975    /**
4976     * Returns the width of the vertical scrollbar.
4977     *
4978     * @return The width in pixels of the vertical scrollbar or 0 if there
4979     *         is no vertical scrollbar.
4980     */
4981    public int getVerticalScrollbarWidth() {
4982        ScrollabilityCache cache = mScrollCache;
4983        if (cache != null) {
4984            ScrollBarDrawable scrollBar = cache.scrollBar;
4985            if (scrollBar != null) {
4986                int size = scrollBar.getSize(true);
4987                if (size <= 0) {
4988                    size = cache.scrollBarSize;
4989                }
4990                return size;
4991            }
4992            return 0;
4993        }
4994        return 0;
4995    }
4996
4997    /**
4998     * Returns the height of the horizontal scrollbar.
4999     *
5000     * @return The height in pixels of the horizontal scrollbar or 0 if
5001     *         there is no horizontal scrollbar.
5002     */
5003    protected int getHorizontalScrollbarHeight() {
5004        ScrollabilityCache cache = mScrollCache;
5005        if (cache != null) {
5006            ScrollBarDrawable scrollBar = cache.scrollBar;
5007            if (scrollBar != null) {
5008                int size = scrollBar.getSize(false);
5009                if (size <= 0) {
5010                    size = cache.scrollBarSize;
5011                }
5012                return size;
5013            }
5014            return 0;
5015        }
5016        return 0;
5017    }
5018
5019    /**
5020     * <p>
5021     * Initializes the scrollbars from a given set of styled attributes. This
5022     * method should be called by subclasses that need scrollbars and when an
5023     * instance of these subclasses is created programmatically rather than
5024     * being inflated from XML. This method is automatically called when the XML
5025     * is inflated.
5026     * </p>
5027     *
5028     * @param a the styled attributes set to initialize the scrollbars from
5029     *
5030     * @removed
5031     */
5032    protected void initializeScrollbars(TypedArray a) {
5033        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5034        // using the View filter array which is not available to the SDK. As such, internal
5035        // framework usage now uses initializeScrollbarsInternal and we grab a default
5036        // TypedArray with the right filter instead here.
5037        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5038
5039        initializeScrollbarsInternal(arr);
5040
5041        // We ignored the method parameter. Recycle the one we actually did use.
5042        arr.recycle();
5043    }
5044
5045    /**
5046     * <p>
5047     * Initializes the scrollbars from a given set of styled attributes. This
5048     * method should be called by subclasses that need scrollbars and when an
5049     * instance of these subclasses is created programmatically rather than
5050     * being inflated from XML. This method is automatically called when the XML
5051     * is inflated.
5052     * </p>
5053     *
5054     * @param a the styled attributes set to initialize the scrollbars from
5055     * @hide
5056     */
5057    protected void initializeScrollbarsInternal(TypedArray a) {
5058        initScrollCache();
5059
5060        final ScrollabilityCache scrollabilityCache = mScrollCache;
5061
5062        if (scrollabilityCache.scrollBar == null) {
5063            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5064            scrollabilityCache.scrollBar.setState(getDrawableState());
5065            scrollabilityCache.scrollBar.setCallback(this);
5066        }
5067
5068        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5069
5070        if (!fadeScrollbars) {
5071            scrollabilityCache.state = ScrollabilityCache.ON;
5072        }
5073        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5074
5075
5076        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5077                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5078                        .getScrollBarFadeDuration());
5079        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5080                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5081                ViewConfiguration.getScrollDefaultDelay());
5082
5083
5084        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5085                com.android.internal.R.styleable.View_scrollbarSize,
5086                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5087
5088        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5089        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5090
5091        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5092        if (thumb != null) {
5093            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5094        }
5095
5096        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5097                false);
5098        if (alwaysDraw) {
5099            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5100        }
5101
5102        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5103        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5104
5105        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5106        if (thumb != null) {
5107            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5108        }
5109
5110        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5111                false);
5112        if (alwaysDraw) {
5113            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5114        }
5115
5116        // Apply layout direction to the new Drawables if needed
5117        final int layoutDirection = getLayoutDirection();
5118        if (track != null) {
5119            track.setLayoutDirection(layoutDirection);
5120        }
5121        if (thumb != null) {
5122            thumb.setLayoutDirection(layoutDirection);
5123        }
5124
5125        // Re-apply user/background padding so that scrollbar(s) get added
5126        resolvePadding();
5127    }
5128
5129    private void initializeScrollIndicatorsInternal() {
5130        // Some day maybe we'll break this into top/left/start/etc. and let the
5131        // client control it. Until then, you can have any scroll indicator you
5132        // want as long as it's a 1dp foreground-colored rectangle.
5133        if (mScrollIndicatorDrawable == null) {
5134            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5135        }
5136    }
5137
5138    /**
5139     * <p>
5140     * Initalizes the scrollability cache if necessary.
5141     * </p>
5142     */
5143    private void initScrollCache() {
5144        if (mScrollCache == null) {
5145            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5146        }
5147    }
5148
5149    private ScrollabilityCache getScrollCache() {
5150        initScrollCache();
5151        return mScrollCache;
5152    }
5153
5154    /**
5155     * Set the position of the vertical scroll bar. Should be one of
5156     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5157     * {@link #SCROLLBAR_POSITION_RIGHT}.
5158     *
5159     * @param position Where the vertical scroll bar should be positioned.
5160     */
5161    public void setVerticalScrollbarPosition(int position) {
5162        if (mVerticalScrollbarPosition != position) {
5163            mVerticalScrollbarPosition = position;
5164            computeOpaqueFlags();
5165            resolvePadding();
5166        }
5167    }
5168
5169    /**
5170     * @return The position where the vertical scroll bar will show, if applicable.
5171     * @see #setVerticalScrollbarPosition(int)
5172     */
5173    public int getVerticalScrollbarPosition() {
5174        return mVerticalScrollbarPosition;
5175    }
5176
5177    boolean isOnScrollbar(float x, float y) {
5178        if (mScrollCache == null) {
5179            return false;
5180        }
5181        x += getScrollX();
5182        y += getScrollY();
5183        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5184            final Rect bounds = mScrollCache.mScrollBarBounds;
5185            getVerticalScrollBarBounds(bounds);
5186            if (bounds.contains((int)x, (int)y)) {
5187                return true;
5188            }
5189        }
5190        if (isHorizontalScrollBarEnabled()) {
5191            final Rect bounds = mScrollCache.mScrollBarBounds;
5192            getHorizontalScrollBarBounds(bounds);
5193            if (bounds.contains((int)x, (int)y)) {
5194                return true;
5195            }
5196        }
5197        return false;
5198    }
5199
5200    boolean isOnScrollbarThumb(float x, float y) {
5201        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5202    }
5203
5204    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5205        if (mScrollCache == null) {
5206            return false;
5207        }
5208        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5209            x += getScrollX();
5210            y += getScrollY();
5211            final Rect bounds = mScrollCache.mScrollBarBounds;
5212            getVerticalScrollBarBounds(bounds);
5213            final int range = computeVerticalScrollRange();
5214            final int offset = computeVerticalScrollOffset();
5215            final int extent = computeVerticalScrollExtent();
5216            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5217                    extent, range);
5218            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5219                    extent, range, offset);
5220            final int thumbTop = bounds.top + thumbOffset;
5221            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5222                    && y <= thumbTop + thumbLength) {
5223                return true;
5224            }
5225        }
5226        return false;
5227    }
5228
5229    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5230        if (mScrollCache == null) {
5231            return false;
5232        }
5233        if (isHorizontalScrollBarEnabled()) {
5234            x += getScrollX();
5235            y += getScrollY();
5236            final Rect bounds = mScrollCache.mScrollBarBounds;
5237            getHorizontalScrollBarBounds(bounds);
5238            final int range = computeHorizontalScrollRange();
5239            final int offset = computeHorizontalScrollOffset();
5240            final int extent = computeHorizontalScrollExtent();
5241            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5242                    extent, range);
5243            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5244                    extent, range, offset);
5245            final int thumbLeft = bounds.left + thumbOffset;
5246            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5247                    && y <= bounds.bottom) {
5248                return true;
5249            }
5250        }
5251        return false;
5252    }
5253
5254    boolean isDraggingScrollBar() {
5255        return mScrollCache != null
5256                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5257    }
5258
5259    /**
5260     * Sets the state of all scroll indicators.
5261     * <p>
5262     * See {@link #setScrollIndicators(int, int)} for usage information.
5263     *
5264     * @param indicators a bitmask of indicators that should be enabled, or
5265     *                   {@code 0} to disable all indicators
5266     * @see #setScrollIndicators(int, int)
5267     * @see #getScrollIndicators()
5268     * @attr ref android.R.styleable#View_scrollIndicators
5269     */
5270    public void setScrollIndicators(@ScrollIndicators int indicators) {
5271        setScrollIndicators(indicators,
5272                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5273    }
5274
5275    /**
5276     * Sets the state of the scroll indicators specified by the mask. To change
5277     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5278     * <p>
5279     * When a scroll indicator is enabled, it will be displayed if the view
5280     * can scroll in the direction of the indicator.
5281     * <p>
5282     * Multiple indicator types may be enabled or disabled by passing the
5283     * logical OR of the desired types. If multiple types are specified, they
5284     * will all be set to the same enabled state.
5285     * <p>
5286     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5287     *
5288     * @param indicators the indicator direction, or the logical OR of multiple
5289     *             indicator directions. One or more of:
5290     *             <ul>
5291     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5292     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5293     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5294     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5295     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5296     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5297     *             </ul>
5298     * @see #setScrollIndicators(int)
5299     * @see #getScrollIndicators()
5300     * @attr ref android.R.styleable#View_scrollIndicators
5301     */
5302    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5303        // Shift and sanitize mask.
5304        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5305        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5306
5307        // Shift and mask indicators.
5308        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5309        indicators &= mask;
5310
5311        // Merge with non-masked flags.
5312        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5313
5314        if (mPrivateFlags3 != updatedFlags) {
5315            mPrivateFlags3 = updatedFlags;
5316
5317            if (indicators != 0) {
5318                initializeScrollIndicatorsInternal();
5319            }
5320            invalidate();
5321        }
5322    }
5323
5324    /**
5325     * Returns a bitmask representing the enabled scroll indicators.
5326     * <p>
5327     * For example, if the top and left scroll indicators are enabled and all
5328     * other indicators are disabled, the return value will be
5329     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5330     * <p>
5331     * To check whether the bottom scroll indicator is enabled, use the value
5332     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5333     *
5334     * @return a bitmask representing the enabled scroll indicators
5335     */
5336    @ScrollIndicators
5337    public int getScrollIndicators() {
5338        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5339                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5340    }
5341
5342    ListenerInfo getListenerInfo() {
5343        if (mListenerInfo != null) {
5344            return mListenerInfo;
5345        }
5346        mListenerInfo = new ListenerInfo();
5347        return mListenerInfo;
5348    }
5349
5350    /**
5351     * Register a callback to be invoked when the scroll X or Y positions of
5352     * this view change.
5353     * <p>
5354     * <b>Note:</b> Some views handle scrolling independently from View and may
5355     * have their own separate listeners for scroll-type events. For example,
5356     * {@link android.widget.ListView ListView} allows clients to register an
5357     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5358     * to listen for changes in list scroll position.
5359     *
5360     * @param l The listener to notify when the scroll X or Y position changes.
5361     * @see android.view.View#getScrollX()
5362     * @see android.view.View#getScrollY()
5363     */
5364    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5365        getListenerInfo().mOnScrollChangeListener = l;
5366    }
5367
5368    /**
5369     * Register a callback to be invoked when focus of this view changed.
5370     *
5371     * @param l The callback that will run.
5372     */
5373    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5374        getListenerInfo().mOnFocusChangeListener = l;
5375    }
5376
5377    /**
5378     * Add a listener that will be called when the bounds of the view change due to
5379     * layout processing.
5380     *
5381     * @param listener The listener that will be called when layout bounds change.
5382     */
5383    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5384        ListenerInfo li = getListenerInfo();
5385        if (li.mOnLayoutChangeListeners == null) {
5386            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5387        }
5388        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5389            li.mOnLayoutChangeListeners.add(listener);
5390        }
5391    }
5392
5393    /**
5394     * Remove a listener for layout changes.
5395     *
5396     * @param listener The listener for layout bounds change.
5397     */
5398    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5399        ListenerInfo li = mListenerInfo;
5400        if (li == null || li.mOnLayoutChangeListeners == null) {
5401            return;
5402        }
5403        li.mOnLayoutChangeListeners.remove(listener);
5404    }
5405
5406    /**
5407     * Add a listener for attach state changes.
5408     *
5409     * This listener will be called whenever this view is attached or detached
5410     * from a window. Remove the listener using
5411     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5412     *
5413     * @param listener Listener to attach
5414     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5415     */
5416    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5417        ListenerInfo li = getListenerInfo();
5418        if (li.mOnAttachStateChangeListeners == null) {
5419            li.mOnAttachStateChangeListeners
5420                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5421        }
5422        li.mOnAttachStateChangeListeners.add(listener);
5423    }
5424
5425    /**
5426     * Remove a listener for attach state changes. The listener will receive no further
5427     * notification of window attach/detach events.
5428     *
5429     * @param listener Listener to remove
5430     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5431     */
5432    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5433        ListenerInfo li = mListenerInfo;
5434        if (li == null || li.mOnAttachStateChangeListeners == null) {
5435            return;
5436        }
5437        li.mOnAttachStateChangeListeners.remove(listener);
5438    }
5439
5440    /**
5441     * Returns the focus-change callback registered for this view.
5442     *
5443     * @return The callback, or null if one is not registered.
5444     */
5445    public OnFocusChangeListener getOnFocusChangeListener() {
5446        ListenerInfo li = mListenerInfo;
5447        return li != null ? li.mOnFocusChangeListener : null;
5448    }
5449
5450    /**
5451     * Register a callback to be invoked when this view is clicked. If this view is not
5452     * clickable, it becomes clickable.
5453     *
5454     * @param l The callback that will run
5455     *
5456     * @see #setClickable(boolean)
5457     */
5458    public void setOnClickListener(@Nullable OnClickListener l) {
5459        if (!isClickable()) {
5460            setClickable(true);
5461        }
5462        getListenerInfo().mOnClickListener = l;
5463    }
5464
5465    /**
5466     * Return whether this view has an attached OnClickListener.  Returns
5467     * true if there is a listener, false if there is none.
5468     */
5469    public boolean hasOnClickListeners() {
5470        ListenerInfo li = mListenerInfo;
5471        return (li != null && li.mOnClickListener != null);
5472    }
5473
5474    /**
5475     * Register a callback to be invoked when this view is clicked and held. If this view is not
5476     * long clickable, it becomes long clickable.
5477     *
5478     * @param l The callback that will run
5479     *
5480     * @see #setLongClickable(boolean)
5481     */
5482    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5483        if (!isLongClickable()) {
5484            setLongClickable(true);
5485        }
5486        getListenerInfo().mOnLongClickListener = l;
5487    }
5488
5489    /**
5490     * Register a callback to be invoked when this view is context clicked. If the view is not
5491     * context clickable, it becomes context clickable.
5492     *
5493     * @param l The callback that will run
5494     * @see #setContextClickable(boolean)
5495     */
5496    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5497        if (!isContextClickable()) {
5498            setContextClickable(true);
5499        }
5500        getListenerInfo().mOnContextClickListener = l;
5501    }
5502
5503    /**
5504     * Register a callback to be invoked when the context menu for this view is
5505     * being built. If this view is not long clickable, it becomes long clickable.
5506     *
5507     * @param l The callback that will run
5508     *
5509     */
5510    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5511        if (!isLongClickable()) {
5512            setLongClickable(true);
5513        }
5514        getListenerInfo().mOnCreateContextMenuListener = l;
5515    }
5516
5517    /**
5518     * Set an observer to collect stats for each frame rendered for this view.
5519     *
5520     * @hide
5521     */
5522    public void addFrameMetricsListener(Window window,
5523            Window.OnFrameMetricsAvailableListener listener,
5524            Handler handler) {
5525        if (mAttachInfo != null) {
5526            if (mAttachInfo.mHardwareRenderer != null) {
5527                if (mFrameMetricsObservers == null) {
5528                    mFrameMetricsObservers = new ArrayList<>();
5529                }
5530
5531                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5532                        handler.getLooper(), listener);
5533                mFrameMetricsObservers.add(fmo);
5534                mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo);
5535            } else {
5536                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5537            }
5538        } else {
5539            if (mFrameMetricsObservers == null) {
5540                mFrameMetricsObservers = new ArrayList<>();
5541            }
5542
5543            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5544                    handler.getLooper(), listener);
5545            mFrameMetricsObservers.add(fmo);
5546        }
5547    }
5548
5549    /**
5550     * Remove observer configured to collect frame stats for this view.
5551     *
5552     * @hide
5553     */
5554    public void removeFrameMetricsListener(
5555            Window.OnFrameMetricsAvailableListener listener) {
5556        ThreadedRenderer renderer = getHardwareRenderer();
5557        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5558        if (fmo == null) {
5559            throw new IllegalArgumentException(
5560                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5561        }
5562
5563        if (mFrameMetricsObservers != null) {
5564            mFrameMetricsObservers.remove(fmo);
5565            if (renderer != null) {
5566                renderer.removeFrameMetricsObserver(fmo);
5567            }
5568        }
5569    }
5570
5571    private void registerPendingFrameMetricsObservers() {
5572        if (mFrameMetricsObservers != null) {
5573            ThreadedRenderer renderer = getHardwareRenderer();
5574            if (renderer != null) {
5575                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5576                    renderer.addFrameMetricsObserver(fmo);
5577                }
5578            } else {
5579                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5580            }
5581        }
5582    }
5583
5584    private FrameMetricsObserver findFrameMetricsObserver(
5585            Window.OnFrameMetricsAvailableListener listener) {
5586        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5587            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5588            if (observer.mListener == listener) {
5589                return observer;
5590            }
5591        }
5592
5593        return null;
5594    }
5595
5596    /**
5597     * Call this view's OnClickListener, if it is defined.  Performs all normal
5598     * actions associated with clicking: reporting accessibility event, playing
5599     * a sound, etc.
5600     *
5601     * @return True there was an assigned OnClickListener that was called, false
5602     *         otherwise is returned.
5603     */
5604    public boolean performClick() {
5605        final boolean result;
5606        final ListenerInfo li = mListenerInfo;
5607        if (li != null && li.mOnClickListener != null) {
5608            playSoundEffect(SoundEffectConstants.CLICK);
5609            li.mOnClickListener.onClick(this);
5610            result = true;
5611        } else {
5612            result = false;
5613        }
5614
5615        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5616        return result;
5617    }
5618
5619    /**
5620     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5621     * this only calls the listener, and does not do any associated clicking
5622     * actions like reporting an accessibility event.
5623     *
5624     * @return True there was an assigned OnClickListener that was called, false
5625     *         otherwise is returned.
5626     */
5627    public boolean callOnClick() {
5628        ListenerInfo li = mListenerInfo;
5629        if (li != null && li.mOnClickListener != null) {
5630            li.mOnClickListener.onClick(this);
5631            return true;
5632        }
5633        return false;
5634    }
5635
5636    /**
5637     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5638     * context menu if the OnLongClickListener did not consume the event.
5639     *
5640     * @return {@code true} if one of the above receivers consumed the event,
5641     *         {@code false} otherwise
5642     */
5643    public boolean performLongClick() {
5644        return performLongClickInternal(mLongClickX, mLongClickY);
5645    }
5646
5647    /**
5648     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5649     * context menu if the OnLongClickListener did not consume the event,
5650     * anchoring it to an (x,y) coordinate.
5651     *
5652     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5653     *          to disable anchoring
5654     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5655     *          to disable anchoring
5656     * @return {@code true} if one of the above receivers consumed the event,
5657     *         {@code false} otherwise
5658     */
5659    public boolean performLongClick(float x, float y) {
5660        mLongClickX = x;
5661        mLongClickY = y;
5662        final boolean handled = performLongClick();
5663        mLongClickX = Float.NaN;
5664        mLongClickY = Float.NaN;
5665        return handled;
5666    }
5667
5668    /**
5669     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5670     * context menu if the OnLongClickListener did not consume the event,
5671     * optionally anchoring it to an (x,y) coordinate.
5672     *
5673     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5674     *          to disable anchoring
5675     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5676     *          to disable anchoring
5677     * @return {@code true} if one of the above receivers consumed the event,
5678     *         {@code false} otherwise
5679     */
5680    private boolean performLongClickInternal(float x, float y) {
5681        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5682
5683        boolean handled = false;
5684        final ListenerInfo li = mListenerInfo;
5685        if (li != null && li.mOnLongClickListener != null) {
5686            handled = li.mOnLongClickListener.onLongClick(View.this);
5687        }
5688        if (!handled) {
5689            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5690            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5691        }
5692        if (handled) {
5693            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5694        }
5695        return handled;
5696    }
5697
5698    /**
5699     * Call this view's OnContextClickListener, if it is defined.
5700     *
5701     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5702     *         otherwise.
5703     */
5704    public boolean performContextClick() {
5705        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5706
5707        boolean handled = false;
5708        ListenerInfo li = mListenerInfo;
5709        if (li != null && li.mOnContextClickListener != null) {
5710            handled = li.mOnContextClickListener.onContextClick(View.this);
5711        }
5712        if (handled) {
5713            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5714        }
5715        return handled;
5716    }
5717
5718    /**
5719     * Performs button-related actions during a touch down event.
5720     *
5721     * @param event The event.
5722     * @return True if the down was consumed.
5723     *
5724     * @hide
5725     */
5726    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5727        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5728            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5729            showContextMenu(event.getX(), event.getY());
5730            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5731            return true;
5732        }
5733        return false;
5734    }
5735
5736    /**
5737     * Shows the context menu for this view.
5738     *
5739     * @return {@code true} if the context menu was shown, {@code false}
5740     *         otherwise
5741     * @see #showContextMenu(float, float)
5742     */
5743    public boolean showContextMenu() {
5744        return getParent().showContextMenuForChild(this);
5745    }
5746
5747    /**
5748     * Shows the context menu for this view anchored to the specified
5749     * view-relative coordinate.
5750     *
5751     * @param x the X coordinate in pixels relative to the view to which the
5752     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5753     * @param y the Y coordinate in pixels relative to the view to which the
5754     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5755     * @return {@code true} if the context menu was shown, {@code false}
5756     *         otherwise
5757     */
5758    public boolean showContextMenu(float x, float y) {
5759        return getParent().showContextMenuForChild(this, x, y);
5760    }
5761
5762    /**
5763     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5764     *
5765     * @param callback Callback that will control the lifecycle of the action mode
5766     * @return The new action mode if it is started, null otherwise
5767     *
5768     * @see ActionMode
5769     * @see #startActionMode(android.view.ActionMode.Callback, int)
5770     */
5771    public ActionMode startActionMode(ActionMode.Callback callback) {
5772        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5773    }
5774
5775    /**
5776     * Start an action mode with the given type.
5777     *
5778     * @param callback Callback that will control the lifecycle of the action mode
5779     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5780     * @return The new action mode if it is started, null otherwise
5781     *
5782     * @see ActionMode
5783     */
5784    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5785        ViewParent parent = getParent();
5786        if (parent == null) return null;
5787        try {
5788            return parent.startActionModeForChild(this, callback, type);
5789        } catch (AbstractMethodError ame) {
5790            // Older implementations of custom views might not implement this.
5791            return parent.startActionModeForChild(this, callback);
5792        }
5793    }
5794
5795    /**
5796     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5797     * Context, creating a unique View identifier to retrieve the result.
5798     *
5799     * @param intent The Intent to be started.
5800     * @param requestCode The request code to use.
5801     * @hide
5802     */
5803    public void startActivityForResult(Intent intent, int requestCode) {
5804        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5805        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5806    }
5807
5808    /**
5809     * If this View corresponds to the calling who, dispatches the activity result.
5810     * @param who The identifier for the targeted View to receive the result.
5811     * @param requestCode The integer request code originally supplied to
5812     *                    startActivityForResult(), allowing you to identify who this
5813     *                    result came from.
5814     * @param resultCode The integer result code returned by the child activity
5815     *                   through its setResult().
5816     * @param data An Intent, which can return result data to the caller
5817     *               (various data can be attached to Intent "extras").
5818     * @return {@code true} if the activity result was dispatched.
5819     * @hide
5820     */
5821    public boolean dispatchActivityResult(
5822            String who, int requestCode, int resultCode, Intent data) {
5823        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5824            onActivityResult(requestCode, resultCode, data);
5825            mStartActivityRequestWho = null;
5826            return true;
5827        }
5828        return false;
5829    }
5830
5831    /**
5832     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5833     *
5834     * @param requestCode The integer request code originally supplied to
5835     *                    startActivityForResult(), allowing you to identify who this
5836     *                    result came from.
5837     * @param resultCode The integer result code returned by the child activity
5838     *                   through its setResult().
5839     * @param data An Intent, which can return result data to the caller
5840     *               (various data can be attached to Intent "extras").
5841     * @hide
5842     */
5843    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5844        // Do nothing.
5845    }
5846
5847    /**
5848     * Register a callback to be invoked when a hardware key is pressed in this view.
5849     * Key presses in software input methods will generally not trigger the methods of
5850     * this listener.
5851     * @param l the key listener to attach to this view
5852     */
5853    public void setOnKeyListener(OnKeyListener l) {
5854        getListenerInfo().mOnKeyListener = l;
5855    }
5856
5857    /**
5858     * Register a callback to be invoked when a touch event is sent to this view.
5859     * @param l the touch listener to attach to this view
5860     */
5861    public void setOnTouchListener(OnTouchListener l) {
5862        getListenerInfo().mOnTouchListener = l;
5863    }
5864
5865    /**
5866     * Register a callback to be invoked when a generic motion event is sent to this view.
5867     * @param l the generic motion listener to attach to this view
5868     */
5869    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5870        getListenerInfo().mOnGenericMotionListener = l;
5871    }
5872
5873    /**
5874     * Register a callback to be invoked when a hover event is sent to this view.
5875     * @param l the hover listener to attach to this view
5876     */
5877    public void setOnHoverListener(OnHoverListener l) {
5878        getListenerInfo().mOnHoverListener = l;
5879    }
5880
5881    /**
5882     * Register a drag event listener callback object for this View. The parameter is
5883     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5884     * View, the system calls the
5885     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5886     * @param l An implementation of {@link android.view.View.OnDragListener}.
5887     */
5888    public void setOnDragListener(OnDragListener l) {
5889        getListenerInfo().mOnDragListener = l;
5890    }
5891
5892    /**
5893     * Give this view focus. This will cause
5894     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5895     *
5896     * Note: this does not check whether this {@link View} should get focus, it just
5897     * gives it focus no matter what.  It should only be called internally by framework
5898     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5899     *
5900     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5901     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5902     *        focus moved when requestFocus() is called. It may not always
5903     *        apply, in which case use the default View.FOCUS_DOWN.
5904     * @param previouslyFocusedRect The rectangle of the view that had focus
5905     *        prior in this View's coordinate system.
5906     */
5907    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5908        if (DBG) {
5909            System.out.println(this + " requestFocus()");
5910        }
5911
5912        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5913            mPrivateFlags |= PFLAG_FOCUSED;
5914
5915            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5916
5917            if (mParent != null) {
5918                mParent.requestChildFocus(this, this);
5919            }
5920
5921            if (mAttachInfo != null) {
5922                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5923            }
5924
5925            onFocusChanged(true, direction, previouslyFocusedRect);
5926            refreshDrawableState();
5927        }
5928    }
5929
5930    /**
5931     * Populates <code>outRect</code> with the hotspot bounds. By default,
5932     * the hotspot bounds are identical to the screen bounds.
5933     *
5934     * @param outRect rect to populate with hotspot bounds
5935     * @hide Only for internal use by views and widgets.
5936     */
5937    public void getHotspotBounds(Rect outRect) {
5938        final Drawable background = getBackground();
5939        if (background != null) {
5940            background.getHotspotBounds(outRect);
5941        } else {
5942            getBoundsOnScreen(outRect);
5943        }
5944    }
5945
5946    /**
5947     * Request that a rectangle of this view be visible on the screen,
5948     * scrolling if necessary just enough.
5949     *
5950     * <p>A View should call this if it maintains some notion of which part
5951     * of its content is interesting.  For example, a text editing view
5952     * should call this when its cursor moves.
5953     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5954     * It should not be affected by which part of the View is currently visible or its scroll
5955     * position.
5956     *
5957     * @param rectangle The rectangle in the View's content coordinate space
5958     * @return Whether any parent scrolled.
5959     */
5960    public boolean requestRectangleOnScreen(Rect rectangle) {
5961        return requestRectangleOnScreen(rectangle, false);
5962    }
5963
5964    /**
5965     * Request that a rectangle of this view be visible on the screen,
5966     * scrolling if necessary just enough.
5967     *
5968     * <p>A View should call this if it maintains some notion of which part
5969     * of its content is interesting.  For example, a text editing view
5970     * should call this when its cursor moves.
5971     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5972     * It should not be affected by which part of the View is currently visible or its scroll
5973     * position.
5974     * <p>When <code>immediate</code> is set to true, scrolling will not be
5975     * animated.
5976     *
5977     * @param rectangle The rectangle in the View's content coordinate space
5978     * @param immediate True to forbid animated scrolling, false otherwise
5979     * @return Whether any parent scrolled.
5980     */
5981    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5982        if (mParent == null) {
5983            return false;
5984        }
5985
5986        View child = this;
5987
5988        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5989        position.set(rectangle);
5990
5991        ViewParent parent = mParent;
5992        boolean scrolled = false;
5993        while (parent != null) {
5994            rectangle.set((int) position.left, (int) position.top,
5995                    (int) position.right, (int) position.bottom);
5996
5997            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
5998
5999            if (!(parent instanceof View)) {
6000                break;
6001            }
6002
6003            // move it from child's content coordinate space to parent's content coordinate space
6004            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6005
6006            child = (View) parent;
6007            parent = child.getParent();
6008        }
6009
6010        return scrolled;
6011    }
6012
6013    /**
6014     * Called when this view wants to give up focus. If focus is cleared
6015     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6016     * <p>
6017     * <strong>Note:</strong> When a View clears focus the framework is trying
6018     * to give focus to the first focusable View from the top. Hence, if this
6019     * View is the first from the top that can take focus, then all callbacks
6020     * related to clearing focus will be invoked after which the framework will
6021     * give focus to this view.
6022     * </p>
6023     */
6024    public void clearFocus() {
6025        if (DBG) {
6026            System.out.println(this + " clearFocus()");
6027        }
6028
6029        clearFocusInternal(null, true, true);
6030    }
6031
6032    /**
6033     * Clears focus from the view, optionally propagating the change up through
6034     * the parent hierarchy and requesting that the root view place new focus.
6035     *
6036     * @param propagate whether to propagate the change up through the parent
6037     *            hierarchy
6038     * @param refocus when propagate is true, specifies whether to request the
6039     *            root view place new focus
6040     */
6041    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6042        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6043            mPrivateFlags &= ~PFLAG_FOCUSED;
6044
6045            if (propagate && mParent != null) {
6046                mParent.clearChildFocus(this);
6047            }
6048
6049            onFocusChanged(false, 0, null);
6050            refreshDrawableState();
6051
6052            if (propagate && (!refocus || !rootViewRequestFocus())) {
6053                notifyGlobalFocusCleared(this);
6054            }
6055        }
6056    }
6057
6058    void notifyGlobalFocusCleared(View oldFocus) {
6059        if (oldFocus != null && mAttachInfo != null) {
6060            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6061        }
6062    }
6063
6064    boolean rootViewRequestFocus() {
6065        final View root = getRootView();
6066        return root != null && root.requestFocus();
6067    }
6068
6069    /**
6070     * Called internally by the view system when a new view is getting focus.
6071     * This is what clears the old focus.
6072     * <p>
6073     * <b>NOTE:</b> The parent view's focused child must be updated manually
6074     * after calling this method. Otherwise, the view hierarchy may be left in
6075     * an inconstent state.
6076     */
6077    void unFocus(View focused) {
6078        if (DBG) {
6079            System.out.println(this + " unFocus()");
6080        }
6081
6082        clearFocusInternal(focused, false, false);
6083    }
6084
6085    /**
6086     * Returns true if this view has focus itself, or is the ancestor of the
6087     * view that has focus.
6088     *
6089     * @return True if this view has or contains focus, false otherwise.
6090     */
6091    @ViewDebug.ExportedProperty(category = "focus")
6092    public boolean hasFocus() {
6093        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6094    }
6095
6096    /**
6097     * Returns true if this view is focusable or if it contains a reachable View
6098     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6099     * is a View whose parents do not block descendants focus.
6100     *
6101     * Only {@link #VISIBLE} views are considered focusable.
6102     *
6103     * @return True if the view is focusable or if the view contains a focusable
6104     *         View, false otherwise.
6105     *
6106     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6107     * @see ViewGroup#getTouchscreenBlocksFocus()
6108     */
6109    public boolean hasFocusable() {
6110        if (!isFocusableInTouchMode()) {
6111            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6112                final ViewGroup g = (ViewGroup) p;
6113                if (g.shouldBlockFocusForTouchscreen()) {
6114                    return false;
6115                }
6116            }
6117        }
6118        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6119    }
6120
6121    /**
6122     * Called by the view system when the focus state of this view changes.
6123     * When the focus change event is caused by directional navigation, direction
6124     * and previouslyFocusedRect provide insight into where the focus is coming from.
6125     * When overriding, be sure to call up through to the super class so that
6126     * the standard focus handling will occur.
6127     *
6128     * @param gainFocus True if the View has focus; false otherwise.
6129     * @param direction The direction focus has moved when requestFocus()
6130     *                  is called to give this view focus. Values are
6131     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6132     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6133     *                  It may not always apply, in which case use the default.
6134     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6135     *        system, of the previously focused view.  If applicable, this will be
6136     *        passed in as finer grained information about where the focus is coming
6137     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6138     */
6139    @CallSuper
6140    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6141            @Nullable Rect previouslyFocusedRect) {
6142        if (gainFocus) {
6143            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6144        } else {
6145            notifyViewAccessibilityStateChangedIfNeeded(
6146                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6147        }
6148
6149        InputMethodManager imm = InputMethodManager.peekInstance();
6150        if (!gainFocus) {
6151            if (isPressed()) {
6152                setPressed(false);
6153            }
6154            if (imm != null && mAttachInfo != null
6155                    && mAttachInfo.mHasWindowFocus) {
6156                imm.focusOut(this);
6157            }
6158            onFocusLost();
6159        } else if (imm != null && mAttachInfo != null
6160                && mAttachInfo.mHasWindowFocus) {
6161            imm.focusIn(this);
6162        }
6163
6164        invalidate(true);
6165        ListenerInfo li = mListenerInfo;
6166        if (li != null && li.mOnFocusChangeListener != null) {
6167            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6168        }
6169
6170        if (mAttachInfo != null) {
6171            mAttachInfo.mKeyDispatchState.reset(this);
6172        }
6173    }
6174
6175    /**
6176     * Sends an accessibility event of the given type. If accessibility is
6177     * not enabled this method has no effect. The default implementation calls
6178     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6179     * to populate information about the event source (this View), then calls
6180     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6181     * populate the text content of the event source including its descendants,
6182     * and last calls
6183     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6184     * on its parent to request sending of the event to interested parties.
6185     * <p>
6186     * If an {@link AccessibilityDelegate} has been specified via calling
6187     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6188     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6189     * responsible for handling this call.
6190     * </p>
6191     *
6192     * @param eventType The type of the event to send, as defined by several types from
6193     * {@link android.view.accessibility.AccessibilityEvent}, such as
6194     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6195     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6196     *
6197     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6198     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6199     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6200     * @see AccessibilityDelegate
6201     */
6202    public void sendAccessibilityEvent(int eventType) {
6203        if (mAccessibilityDelegate != null) {
6204            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6205        } else {
6206            sendAccessibilityEventInternal(eventType);
6207        }
6208    }
6209
6210    /**
6211     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6212     * {@link AccessibilityEvent} to make an announcement which is related to some
6213     * sort of a context change for which none of the events representing UI transitions
6214     * is a good fit. For example, announcing a new page in a book. If accessibility
6215     * is not enabled this method does nothing.
6216     *
6217     * @param text The announcement text.
6218     */
6219    public void announceForAccessibility(CharSequence text) {
6220        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6221            AccessibilityEvent event = AccessibilityEvent.obtain(
6222                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6223            onInitializeAccessibilityEvent(event);
6224            event.getText().add(text);
6225            event.setContentDescription(null);
6226            mParent.requestSendAccessibilityEvent(this, event);
6227        }
6228    }
6229
6230    /**
6231     * @see #sendAccessibilityEvent(int)
6232     *
6233     * Note: Called from the default {@link AccessibilityDelegate}.
6234     *
6235     * @hide
6236     */
6237    public void sendAccessibilityEventInternal(int eventType) {
6238        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6239            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6240        }
6241    }
6242
6243    /**
6244     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6245     * takes as an argument an empty {@link AccessibilityEvent} and does not
6246     * perform a check whether accessibility is enabled.
6247     * <p>
6248     * If an {@link AccessibilityDelegate} has been specified via calling
6249     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6250     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6251     * is responsible for handling this call.
6252     * </p>
6253     *
6254     * @param event The event to send.
6255     *
6256     * @see #sendAccessibilityEvent(int)
6257     */
6258    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6259        if (mAccessibilityDelegate != null) {
6260            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6261        } else {
6262            sendAccessibilityEventUncheckedInternal(event);
6263        }
6264    }
6265
6266    /**
6267     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6268     *
6269     * Note: Called from the default {@link AccessibilityDelegate}.
6270     *
6271     * @hide
6272     */
6273    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6274        if (!isShown()) {
6275            return;
6276        }
6277        onInitializeAccessibilityEvent(event);
6278        // Only a subset of accessibility events populates text content.
6279        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6280            dispatchPopulateAccessibilityEvent(event);
6281        }
6282        // In the beginning we called #isShown(), so we know that getParent() is not null.
6283        getParent().requestSendAccessibilityEvent(this, event);
6284    }
6285
6286    /**
6287     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6288     * to its children for adding their text content to the event. Note that the
6289     * event text is populated in a separate dispatch path since we add to the
6290     * event not only the text of the source but also the text of all its descendants.
6291     * A typical implementation will call
6292     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6293     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6294     * on each child. Override this method if custom population of the event text
6295     * content is required.
6296     * <p>
6297     * If an {@link AccessibilityDelegate} has been specified via calling
6298     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6299     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6300     * is responsible for handling this call.
6301     * </p>
6302     * <p>
6303     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6304     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6305     * </p>
6306     *
6307     * @param event The event.
6308     *
6309     * @return True if the event population was completed.
6310     */
6311    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6312        if (mAccessibilityDelegate != null) {
6313            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6314        } else {
6315            return dispatchPopulateAccessibilityEventInternal(event);
6316        }
6317    }
6318
6319    /**
6320     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6321     *
6322     * Note: Called from the default {@link AccessibilityDelegate}.
6323     *
6324     * @hide
6325     */
6326    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6327        onPopulateAccessibilityEvent(event);
6328        return false;
6329    }
6330
6331    /**
6332     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6333     * giving a chance to this View to populate the accessibility event with its
6334     * text content. While this method is free to modify event
6335     * attributes other than text content, doing so should normally be performed in
6336     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6337     * <p>
6338     * Example: Adding formatted date string to an accessibility event in addition
6339     *          to the text added by the super implementation:
6340     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6341     *     super.onPopulateAccessibilityEvent(event);
6342     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6343     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6344     *         mCurrentDate.getTimeInMillis(), flags);
6345     *     event.getText().add(selectedDateUtterance);
6346     * }</pre>
6347     * <p>
6348     * If an {@link AccessibilityDelegate} has been specified via calling
6349     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6350     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6351     * is responsible for handling this call.
6352     * </p>
6353     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6354     * information to the event, in case the default implementation has basic information to add.
6355     * </p>
6356     *
6357     * @param event The accessibility event which to populate.
6358     *
6359     * @see #sendAccessibilityEvent(int)
6360     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6361     */
6362    @CallSuper
6363    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6364        if (mAccessibilityDelegate != null) {
6365            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6366        } else {
6367            onPopulateAccessibilityEventInternal(event);
6368        }
6369    }
6370
6371    /**
6372     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6373     *
6374     * Note: Called from the default {@link AccessibilityDelegate}.
6375     *
6376     * @hide
6377     */
6378    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6379    }
6380
6381    /**
6382     * Initializes an {@link AccessibilityEvent} with information about
6383     * this View which is the event source. In other words, the source of
6384     * an accessibility event is the view whose state change triggered firing
6385     * the event.
6386     * <p>
6387     * Example: Setting the password property of an event in addition
6388     *          to properties set by the super implementation:
6389     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6390     *     super.onInitializeAccessibilityEvent(event);
6391     *     event.setPassword(true);
6392     * }</pre>
6393     * <p>
6394     * If an {@link AccessibilityDelegate} has been specified via calling
6395     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6396     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6397     * is responsible for handling this call.
6398     * </p>
6399     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6400     * information to the event, in case the default implementation has basic information to add.
6401     * </p>
6402     * @param event The event to initialize.
6403     *
6404     * @see #sendAccessibilityEvent(int)
6405     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6406     */
6407    @CallSuper
6408    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6409        if (mAccessibilityDelegate != null) {
6410            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6411        } else {
6412            onInitializeAccessibilityEventInternal(event);
6413        }
6414    }
6415
6416    /**
6417     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6418     *
6419     * Note: Called from the default {@link AccessibilityDelegate}.
6420     *
6421     * @hide
6422     */
6423    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6424        event.setSource(this);
6425        event.setClassName(getAccessibilityClassName());
6426        event.setPackageName(getContext().getPackageName());
6427        event.setEnabled(isEnabled());
6428        event.setContentDescription(mContentDescription);
6429
6430        switch (event.getEventType()) {
6431            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6432                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6433                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6434                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6435                event.setItemCount(focusablesTempList.size());
6436                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6437                if (mAttachInfo != null) {
6438                    focusablesTempList.clear();
6439                }
6440            } break;
6441            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6442                CharSequence text = getIterableTextForAccessibility();
6443                if (text != null && text.length() > 0) {
6444                    event.setFromIndex(getAccessibilitySelectionStart());
6445                    event.setToIndex(getAccessibilitySelectionEnd());
6446                    event.setItemCount(text.length());
6447                }
6448            } break;
6449        }
6450    }
6451
6452    /**
6453     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6454     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6455     * This method is responsible for obtaining an accessibility node info from a
6456     * pool of reusable instances and calling
6457     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6458     * initialize the former.
6459     * <p>
6460     * Note: The client is responsible for recycling the obtained instance by calling
6461     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6462     * </p>
6463     *
6464     * @return A populated {@link AccessibilityNodeInfo}.
6465     *
6466     * @see AccessibilityNodeInfo
6467     */
6468    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6469        if (mAccessibilityDelegate != null) {
6470            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6471        } else {
6472            return createAccessibilityNodeInfoInternal();
6473        }
6474    }
6475
6476    /**
6477     * @see #createAccessibilityNodeInfo()
6478     *
6479     * @hide
6480     */
6481    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6482        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6483        if (provider != null) {
6484            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6485        } else {
6486            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6487            onInitializeAccessibilityNodeInfo(info);
6488            return info;
6489        }
6490    }
6491
6492    /**
6493     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6494     * The base implementation sets:
6495     * <ul>
6496     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6497     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6498     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6499     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6500     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6501     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6502     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6503     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6504     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6505     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6506     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6507     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6508     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6509     * </ul>
6510     * <p>
6511     * Subclasses should override this method, call the super implementation,
6512     * and set additional attributes.
6513     * </p>
6514     * <p>
6515     * If an {@link AccessibilityDelegate} has been specified via calling
6516     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6517     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6518     * is responsible for handling this call.
6519     * </p>
6520     *
6521     * @param info The instance to initialize.
6522     */
6523    @CallSuper
6524    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6525        if (mAccessibilityDelegate != null) {
6526            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6527        } else {
6528            onInitializeAccessibilityNodeInfoInternal(info);
6529        }
6530    }
6531
6532    /**
6533     * Gets the location of this view in screen coordinates.
6534     *
6535     * @param outRect The output location
6536     * @hide
6537     */
6538    public void getBoundsOnScreen(Rect outRect) {
6539        getBoundsOnScreen(outRect, false);
6540    }
6541
6542    /**
6543     * Gets the location of this view in screen coordinates.
6544     *
6545     * @param outRect The output location
6546     * @param clipToParent Whether to clip child bounds to the parent ones.
6547     * @hide
6548     */
6549    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6550        if (mAttachInfo == null) {
6551            return;
6552        }
6553
6554        RectF position = mAttachInfo.mTmpTransformRect;
6555        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6556
6557        if (!hasIdentityMatrix()) {
6558            getMatrix().mapRect(position);
6559        }
6560
6561        position.offset(mLeft, mTop);
6562
6563        ViewParent parent = mParent;
6564        while (parent instanceof View) {
6565            View parentView = (View) parent;
6566
6567            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6568
6569            if (clipToParent) {
6570                position.left = Math.max(position.left, 0);
6571                position.top = Math.max(position.top, 0);
6572                position.right = Math.min(position.right, parentView.getWidth());
6573                position.bottom = Math.min(position.bottom, parentView.getHeight());
6574            }
6575
6576            if (!parentView.hasIdentityMatrix()) {
6577                parentView.getMatrix().mapRect(position);
6578            }
6579
6580            position.offset(parentView.mLeft, parentView.mTop);
6581
6582            parent = parentView.mParent;
6583        }
6584
6585        if (parent instanceof ViewRootImpl) {
6586            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6587            position.offset(0, -viewRootImpl.mCurScrollY);
6588        }
6589
6590        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6591
6592        outRect.set(Math.round(position.left), Math.round(position.top),
6593                Math.round(position.right), Math.round(position.bottom));
6594    }
6595
6596    /**
6597     * Return the class name of this object to be used for accessibility purposes.
6598     * Subclasses should only override this if they are implementing something that
6599     * should be seen as a completely new class of view when used by accessibility,
6600     * unrelated to the class it is deriving from.  This is used to fill in
6601     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6602     */
6603    public CharSequence getAccessibilityClassName() {
6604        return View.class.getName();
6605    }
6606
6607    /**
6608     * Called when assist structure is being retrieved from a view as part of
6609     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6610     * @param structure Fill in with structured view data.  The default implementation
6611     * fills in all data that can be inferred from the view itself.
6612     */
6613    public void onProvideStructure(ViewStructure structure) {
6614        final int id = mID;
6615        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6616                && (id&0x0000ffff) != 0) {
6617            String pkg, type, entry;
6618            try {
6619                final Resources res = getResources();
6620                entry = res.getResourceEntryName(id);
6621                type = res.getResourceTypeName(id);
6622                pkg = res.getResourcePackageName(id);
6623            } catch (Resources.NotFoundException e) {
6624                entry = type = pkg = null;
6625            }
6626            structure.setId(id, pkg, type, entry);
6627        } else {
6628            structure.setId(id, null, null, null);
6629        }
6630        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6631        if (!hasIdentityMatrix()) {
6632            structure.setTransformation(getMatrix());
6633        }
6634        structure.setElevation(getZ());
6635        structure.setVisibility(getVisibility());
6636        structure.setEnabled(isEnabled());
6637        if (isClickable()) {
6638            structure.setClickable(true);
6639        }
6640        if (isFocusable()) {
6641            structure.setFocusable(true);
6642        }
6643        if (isFocused()) {
6644            structure.setFocused(true);
6645        }
6646        if (isAccessibilityFocused()) {
6647            structure.setAccessibilityFocused(true);
6648        }
6649        if (isSelected()) {
6650            structure.setSelected(true);
6651        }
6652        if (isActivated()) {
6653            structure.setActivated(true);
6654        }
6655        if (isLongClickable()) {
6656            structure.setLongClickable(true);
6657        }
6658        if (this instanceof Checkable) {
6659            structure.setCheckable(true);
6660            if (((Checkable)this).isChecked()) {
6661                structure.setChecked(true);
6662            }
6663        }
6664        if (isContextClickable()) {
6665            structure.setContextClickable(true);
6666        }
6667        structure.setClassName(getAccessibilityClassName().toString());
6668        structure.setContentDescription(getContentDescription());
6669    }
6670
6671    /**
6672     * Called when assist structure is being retrieved from a view as part of
6673     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6674     * generate additional virtual structure under this view.  The defaullt implementation
6675     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6676     * view's virtual accessibility nodes, if any.  You can override this for a more
6677     * optimal implementation providing this data.
6678     */
6679    public void onProvideVirtualStructure(ViewStructure structure) {
6680        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6681        if (provider != null) {
6682            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6683            structure.setChildCount(1);
6684            ViewStructure root = structure.newChild(0);
6685            populateVirtualStructure(root, provider, info);
6686            info.recycle();
6687        }
6688    }
6689
6690    private void populateVirtualStructure(ViewStructure structure,
6691            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6692        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6693                null, null, null);
6694        Rect rect = structure.getTempRect();
6695        info.getBoundsInParent(rect);
6696        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6697        structure.setVisibility(VISIBLE);
6698        structure.setEnabled(info.isEnabled());
6699        if (info.isClickable()) {
6700            structure.setClickable(true);
6701        }
6702        if (info.isFocusable()) {
6703            structure.setFocusable(true);
6704        }
6705        if (info.isFocused()) {
6706            structure.setFocused(true);
6707        }
6708        if (info.isAccessibilityFocused()) {
6709            structure.setAccessibilityFocused(true);
6710        }
6711        if (info.isSelected()) {
6712            structure.setSelected(true);
6713        }
6714        if (info.isLongClickable()) {
6715            structure.setLongClickable(true);
6716        }
6717        if (info.isCheckable()) {
6718            structure.setCheckable(true);
6719            if (info.isChecked()) {
6720                structure.setChecked(true);
6721            }
6722        }
6723        if (info.isContextClickable()) {
6724            structure.setContextClickable(true);
6725        }
6726        CharSequence cname = info.getClassName();
6727        structure.setClassName(cname != null ? cname.toString() : null);
6728        structure.setContentDescription(info.getContentDescription());
6729        if (info.getText() != null || info.getError() != null) {
6730            structure.setText(info.getText(), info.getTextSelectionStart(),
6731                    info.getTextSelectionEnd());
6732        }
6733        final int NCHILDREN = info.getChildCount();
6734        if (NCHILDREN > 0) {
6735            structure.setChildCount(NCHILDREN);
6736            for (int i=0; i<NCHILDREN; i++) {
6737                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6738                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6739                ViewStructure child = structure.newChild(i);
6740                populateVirtualStructure(child, provider, cinfo);
6741                cinfo.recycle();
6742            }
6743        }
6744    }
6745
6746    /**
6747     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6748     * implementation calls {@link #onProvideStructure} and
6749     * {@link #onProvideVirtualStructure}.
6750     */
6751    public void dispatchProvideStructure(ViewStructure structure) {
6752        if (!isAssistBlocked()) {
6753            onProvideStructure(structure);
6754            onProvideVirtualStructure(structure);
6755        } else {
6756            structure.setClassName(getAccessibilityClassName().toString());
6757            structure.setAssistBlocked(true);
6758        }
6759    }
6760
6761    /**
6762     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6763     *
6764     * Note: Called from the default {@link AccessibilityDelegate}.
6765     *
6766     * @hide
6767     */
6768    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6769        if (mAttachInfo == null) {
6770            return;
6771        }
6772
6773        Rect bounds = mAttachInfo.mTmpInvalRect;
6774
6775        getDrawingRect(bounds);
6776        info.setBoundsInParent(bounds);
6777
6778        getBoundsOnScreen(bounds, true);
6779        info.setBoundsInScreen(bounds);
6780
6781        ViewParent parent = getParentForAccessibility();
6782        if (parent instanceof View) {
6783            info.setParent((View) parent);
6784        }
6785
6786        if (mID != View.NO_ID) {
6787            View rootView = getRootView();
6788            if (rootView == null) {
6789                rootView = this;
6790            }
6791
6792            View label = rootView.findLabelForView(this, mID);
6793            if (label != null) {
6794                info.setLabeledBy(label);
6795            }
6796
6797            if ((mAttachInfo.mAccessibilityFetchFlags
6798                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6799                    && Resources.resourceHasPackage(mID)) {
6800                try {
6801                    String viewId = getResources().getResourceName(mID);
6802                    info.setViewIdResourceName(viewId);
6803                } catch (Resources.NotFoundException nfe) {
6804                    /* ignore */
6805                }
6806            }
6807        }
6808
6809        if (mLabelForId != View.NO_ID) {
6810            View rootView = getRootView();
6811            if (rootView == null) {
6812                rootView = this;
6813            }
6814            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6815            if (labeled != null) {
6816                info.setLabelFor(labeled);
6817            }
6818        }
6819
6820        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6821            View rootView = getRootView();
6822            if (rootView == null) {
6823                rootView = this;
6824            }
6825            View next = rootView.findViewInsideOutShouldExist(this,
6826                    mAccessibilityTraversalBeforeId);
6827            if (next != null && next.includeForAccessibility()) {
6828                info.setTraversalBefore(next);
6829            }
6830        }
6831
6832        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6833            View rootView = getRootView();
6834            if (rootView == null) {
6835                rootView = this;
6836            }
6837            View next = rootView.findViewInsideOutShouldExist(this,
6838                    mAccessibilityTraversalAfterId);
6839            if (next != null && next.includeForAccessibility()) {
6840                info.setTraversalAfter(next);
6841            }
6842        }
6843
6844        info.setVisibleToUser(isVisibleToUser());
6845
6846        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6847                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6848            info.setImportantForAccessibility(isImportantForAccessibility());
6849        } else {
6850            info.setImportantForAccessibility(true);
6851        }
6852
6853        info.setPackageName(mContext.getPackageName());
6854        info.setClassName(getAccessibilityClassName());
6855        info.setContentDescription(getContentDescription());
6856
6857        info.setEnabled(isEnabled());
6858        info.setClickable(isClickable());
6859        info.setFocusable(isFocusable());
6860        info.setFocused(isFocused());
6861        info.setAccessibilityFocused(isAccessibilityFocused());
6862        info.setSelected(isSelected());
6863        info.setLongClickable(isLongClickable());
6864        info.setContextClickable(isContextClickable());
6865        info.setLiveRegion(getAccessibilityLiveRegion());
6866
6867        // TODO: These make sense only if we are in an AdapterView but all
6868        // views can be selected. Maybe from accessibility perspective
6869        // we should report as selectable view in an AdapterView.
6870        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6871        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6872
6873        if (isFocusable()) {
6874            if (isFocused()) {
6875                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6876            } else {
6877                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6878            }
6879        }
6880
6881        if (!isAccessibilityFocused()) {
6882            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6883        } else {
6884            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6885        }
6886
6887        if (isClickable() && isEnabled()) {
6888            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6889        }
6890
6891        if (isLongClickable() && isEnabled()) {
6892            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6893        }
6894
6895        if (isContextClickable() && isEnabled()) {
6896            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6897        }
6898
6899        CharSequence text = getIterableTextForAccessibility();
6900        if (text != null && text.length() > 0) {
6901            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6902
6903            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6904            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6905            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6906            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6907                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6908                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6909        }
6910
6911        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6912        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6913    }
6914
6915    /**
6916     * Determine the order in which this view will be drawn relative to its siblings for a11y
6917     *
6918     * @param info The info whose drawing order should be populated
6919     */
6920    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6921        /*
6922         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
6923         * drawing order may not be well-defined, and some Views with custom drawing order may
6924         * not be initialized sufficiently to respond properly getChildDrawingOrder.
6925         */
6926        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
6927            info.setDrawingOrder(0);
6928            return;
6929        }
6930        int drawingOrderInParent = 1;
6931        // Iterate up the hierarchy if parents are not important for a11y
6932        View viewAtDrawingLevel = this;
6933        final ViewParent parent = getParentForAccessibility();
6934        while (viewAtDrawingLevel != parent) {
6935            final ViewParent currentParent = viewAtDrawingLevel.getParent();
6936            if (!(currentParent instanceof ViewGroup)) {
6937                // Should only happen for the Decor
6938                drawingOrderInParent = 0;
6939                break;
6940            } else {
6941                final ViewGroup parentGroup = (ViewGroup) currentParent;
6942                final int childCount = parentGroup.getChildCount();
6943                if (childCount > 1) {
6944                    List<View> preorderedList = parentGroup.buildOrderedChildList();
6945                    if (preorderedList != null) {
6946                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
6947                        for (int i = 0; i < childDrawIndex; i++) {
6948                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
6949                        }
6950                    } else {
6951                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
6952                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
6953                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
6954                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
6955                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
6956                        if (childDrawIndex != 0) {
6957                            for (int i = 0; i < numChildrenToIterate; i++) {
6958                                final int otherDrawIndex = (customOrder ?
6959                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
6960                                if (otherDrawIndex < childDrawIndex) {
6961                                    drawingOrderInParent +=
6962                                            numViewsForAccessibility(parentGroup.getChildAt(i));
6963                                }
6964                            }
6965                        }
6966                    }
6967                }
6968            }
6969            viewAtDrawingLevel = (View) currentParent;
6970        }
6971        info.setDrawingOrder(drawingOrderInParent);
6972    }
6973
6974    private static int numViewsForAccessibility(View view) {
6975        if (view != null) {
6976            if (view.includeForAccessibility()) {
6977                return 1;
6978            } else if (view instanceof ViewGroup) {
6979                return ((ViewGroup) view).getNumChildrenForAccessibility();
6980            }
6981        }
6982        return 0;
6983    }
6984
6985    private View findLabelForView(View view, int labeledId) {
6986        if (mMatchLabelForPredicate == null) {
6987            mMatchLabelForPredicate = new MatchLabelForPredicate();
6988        }
6989        mMatchLabelForPredicate.mLabeledId = labeledId;
6990        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6991    }
6992
6993    /**
6994     * Computes whether this view is visible to the user. Such a view is
6995     * attached, visible, all its predecessors are visible, it is not clipped
6996     * entirely by its predecessors, and has an alpha greater than zero.
6997     *
6998     * @return Whether the view is visible on the screen.
6999     *
7000     * @hide
7001     */
7002    protected boolean isVisibleToUser() {
7003        return isVisibleToUser(null);
7004    }
7005
7006    /**
7007     * Computes whether the given portion of this view is visible to the user.
7008     * Such a view is attached, visible, all its predecessors are visible,
7009     * has an alpha greater than zero, and the specified portion is not
7010     * clipped entirely by its predecessors.
7011     *
7012     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7013     *                    <code>null</code>, and the entire view will be tested in this case.
7014     *                    When <code>true</code> is returned by the function, the actual visible
7015     *                    region will be stored in this parameter; that is, if boundInView is fully
7016     *                    contained within the view, no modification will be made, otherwise regions
7017     *                    outside of the visible area of the view will be clipped.
7018     *
7019     * @return Whether the specified portion of the view is visible on the screen.
7020     *
7021     * @hide
7022     */
7023    protected boolean isVisibleToUser(Rect boundInView) {
7024        if (mAttachInfo != null) {
7025            // Attached to invisible window means this view is not visible.
7026            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7027                return false;
7028            }
7029            // An invisible predecessor or one with alpha zero means
7030            // that this view is not visible to the user.
7031            Object current = this;
7032            while (current instanceof View) {
7033                View view = (View) current;
7034                // We have attach info so this view is attached and there is no
7035                // need to check whether we reach to ViewRootImpl on the way up.
7036                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7037                        view.getVisibility() != VISIBLE) {
7038                    return false;
7039                }
7040                current = view.mParent;
7041            }
7042            // Check if the view is entirely covered by its predecessors.
7043            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7044            Point offset = mAttachInfo.mPoint;
7045            if (!getGlobalVisibleRect(visibleRect, offset)) {
7046                return false;
7047            }
7048            // Check if the visible portion intersects the rectangle of interest.
7049            if (boundInView != null) {
7050                visibleRect.offset(-offset.x, -offset.y);
7051                return boundInView.intersect(visibleRect);
7052            }
7053            return true;
7054        }
7055        return false;
7056    }
7057
7058    /**
7059     * Returns the delegate for implementing accessibility support via
7060     * composition. For more details see {@link AccessibilityDelegate}.
7061     *
7062     * @return The delegate, or null if none set.
7063     *
7064     * @hide
7065     */
7066    public AccessibilityDelegate getAccessibilityDelegate() {
7067        return mAccessibilityDelegate;
7068    }
7069
7070    /**
7071     * Sets a delegate for implementing accessibility support via composition
7072     * (as opposed to inheritance). For more details, see
7073     * {@link AccessibilityDelegate}.
7074     * <p>
7075     * <strong>Note:</strong> On platform versions prior to
7076     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7077     * views in the {@code android.widget.*} package are called <i>before</i>
7078     * host methods. This prevents certain properties such as class name from
7079     * being modified by overriding
7080     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7081     * as any changes will be overwritten by the host class.
7082     * <p>
7083     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7084     * methods are called <i>after</i> host methods, which all properties to be
7085     * modified without being overwritten by the host class.
7086     *
7087     * @param delegate the object to which accessibility method calls should be
7088     *                 delegated
7089     * @see AccessibilityDelegate
7090     */
7091    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7092        mAccessibilityDelegate = delegate;
7093    }
7094
7095    /**
7096     * Gets the provider for managing a virtual view hierarchy rooted at this View
7097     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7098     * that explore the window content.
7099     * <p>
7100     * If this method returns an instance, this instance is responsible for managing
7101     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7102     * View including the one representing the View itself. Similarly the returned
7103     * instance is responsible for performing accessibility actions on any virtual
7104     * view or the root view itself.
7105     * </p>
7106     * <p>
7107     * If an {@link AccessibilityDelegate} has been specified via calling
7108     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7109     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7110     * is responsible for handling this call.
7111     * </p>
7112     *
7113     * @return The provider.
7114     *
7115     * @see AccessibilityNodeProvider
7116     */
7117    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7118        if (mAccessibilityDelegate != null) {
7119            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7120        } else {
7121            return null;
7122        }
7123    }
7124
7125    /**
7126     * Gets the unique identifier of this view on the screen for accessibility purposes.
7127     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7128     *
7129     * @return The view accessibility id.
7130     *
7131     * @hide
7132     */
7133    public int getAccessibilityViewId() {
7134        if (mAccessibilityViewId == NO_ID) {
7135            mAccessibilityViewId = sNextAccessibilityViewId++;
7136        }
7137        return mAccessibilityViewId;
7138    }
7139
7140    /**
7141     * Gets the unique identifier of the window in which this View reseides.
7142     *
7143     * @return The window accessibility id.
7144     *
7145     * @hide
7146     */
7147    public int getAccessibilityWindowId() {
7148        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7149                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7150    }
7151
7152    /**
7153     * Returns the {@link View}'s content description.
7154     * <p>
7155     * <strong>Note:</strong> Do not override this method, as it will have no
7156     * effect on the content description presented to accessibility services.
7157     * You must call {@link #setContentDescription(CharSequence)} to modify the
7158     * content description.
7159     *
7160     * @return the content description
7161     * @see #setContentDescription(CharSequence)
7162     * @attr ref android.R.styleable#View_contentDescription
7163     */
7164    @ViewDebug.ExportedProperty(category = "accessibility")
7165    public CharSequence getContentDescription() {
7166        return mContentDescription;
7167    }
7168
7169    /**
7170     * Sets the {@link View}'s content description.
7171     * <p>
7172     * A content description briefly describes the view and is primarily used
7173     * for accessibility support to determine how a view should be presented to
7174     * the user. In the case of a view with no textual representation, such as
7175     * {@link android.widget.ImageButton}, a useful content description
7176     * explains what the view does. For example, an image button with a phone
7177     * icon that is used to place a call may use "Call" as its content
7178     * description. An image of a floppy disk that is used to save a file may
7179     * use "Save".
7180     *
7181     * @param contentDescription The content description.
7182     * @see #getContentDescription()
7183     * @attr ref android.R.styleable#View_contentDescription
7184     */
7185    @RemotableViewMethod
7186    public void setContentDescription(CharSequence contentDescription) {
7187        if (mContentDescription == null) {
7188            if (contentDescription == null) {
7189                return;
7190            }
7191        } else if (mContentDescription.equals(contentDescription)) {
7192            return;
7193        }
7194        mContentDescription = contentDescription;
7195        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7196        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7197            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7198            notifySubtreeAccessibilityStateChangedIfNeeded();
7199        } else {
7200            notifyViewAccessibilityStateChangedIfNeeded(
7201                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7202        }
7203    }
7204
7205    /**
7206     * Sets the id of a view before which this one is visited in accessibility traversal.
7207     * A screen-reader must visit the content of this view before the content of the one
7208     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7209     * will traverse the entire content of B before traversing the entire content of A,
7210     * regardles of what traversal strategy it is using.
7211     * <p>
7212     * Views that do not have specified before/after relationships are traversed in order
7213     * determined by the screen-reader.
7214     * </p>
7215     * <p>
7216     * Setting that this view is before a view that is not important for accessibility
7217     * or if this view is not important for accessibility will have no effect as the
7218     * screen-reader is not aware of unimportant views.
7219     * </p>
7220     *
7221     * @param beforeId The id of a view this one precedes in accessibility traversal.
7222     *
7223     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7224     *
7225     * @see #setImportantForAccessibility(int)
7226     */
7227    @RemotableViewMethod
7228    public void setAccessibilityTraversalBefore(int beforeId) {
7229        if (mAccessibilityTraversalBeforeId == beforeId) {
7230            return;
7231        }
7232        mAccessibilityTraversalBeforeId = beforeId;
7233        notifyViewAccessibilityStateChangedIfNeeded(
7234                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7235    }
7236
7237    /**
7238     * Gets the id of a view before which this one is visited in accessibility traversal.
7239     *
7240     * @return The id of a view this one precedes in accessibility traversal if
7241     *         specified, otherwise {@link #NO_ID}.
7242     *
7243     * @see #setAccessibilityTraversalBefore(int)
7244     */
7245    public int getAccessibilityTraversalBefore() {
7246        return mAccessibilityTraversalBeforeId;
7247    }
7248
7249    /**
7250     * Sets the id of a view after which this one is visited in accessibility traversal.
7251     * A screen-reader must visit the content of the other view before the content of this
7252     * one. For example, if view B is set to be after view A, then a screen-reader
7253     * will traverse the entire content of A before traversing the entire content of B,
7254     * regardles of what traversal strategy it is using.
7255     * <p>
7256     * Views that do not have specified before/after relationships are traversed in order
7257     * determined by the screen-reader.
7258     * </p>
7259     * <p>
7260     * Setting that this view is after a view that is not important for accessibility
7261     * or if this view is not important for accessibility will have no effect as the
7262     * screen-reader is not aware of unimportant views.
7263     * </p>
7264     *
7265     * @param afterId The id of a view this one succedees in accessibility traversal.
7266     *
7267     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7268     *
7269     * @see #setImportantForAccessibility(int)
7270     */
7271    @RemotableViewMethod
7272    public void setAccessibilityTraversalAfter(int afterId) {
7273        if (mAccessibilityTraversalAfterId == afterId) {
7274            return;
7275        }
7276        mAccessibilityTraversalAfterId = afterId;
7277        notifyViewAccessibilityStateChangedIfNeeded(
7278                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7279    }
7280
7281    /**
7282     * Gets the id of a view after which this one is visited in accessibility traversal.
7283     *
7284     * @return The id of a view this one succeedes in accessibility traversal if
7285     *         specified, otherwise {@link #NO_ID}.
7286     *
7287     * @see #setAccessibilityTraversalAfter(int)
7288     */
7289    public int getAccessibilityTraversalAfter() {
7290        return mAccessibilityTraversalAfterId;
7291    }
7292
7293    /**
7294     * Gets the id of a view for which this view serves as a label for
7295     * accessibility purposes.
7296     *
7297     * @return The labeled view id.
7298     */
7299    @ViewDebug.ExportedProperty(category = "accessibility")
7300    public int getLabelFor() {
7301        return mLabelForId;
7302    }
7303
7304    /**
7305     * Sets the id of a view for which this view serves as a label for
7306     * accessibility purposes.
7307     *
7308     * @param id The labeled view id.
7309     */
7310    @RemotableViewMethod
7311    public void setLabelFor(@IdRes int id) {
7312        if (mLabelForId == id) {
7313            return;
7314        }
7315        mLabelForId = id;
7316        if (mLabelForId != View.NO_ID
7317                && mID == View.NO_ID) {
7318            mID = generateViewId();
7319        }
7320        notifyViewAccessibilityStateChangedIfNeeded(
7321                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7322    }
7323
7324    /**
7325     * Invoked whenever this view loses focus, either by losing window focus or by losing
7326     * focus within its window. This method can be used to clear any state tied to the
7327     * focus. For instance, if a button is held pressed with the trackball and the window
7328     * loses focus, this method can be used to cancel the press.
7329     *
7330     * Subclasses of View overriding this method should always call super.onFocusLost().
7331     *
7332     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7333     * @see #onWindowFocusChanged(boolean)
7334     *
7335     * @hide pending API council approval
7336     */
7337    @CallSuper
7338    protected void onFocusLost() {
7339        resetPressedState();
7340    }
7341
7342    private void resetPressedState() {
7343        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7344            return;
7345        }
7346
7347        if (isPressed()) {
7348            setPressed(false);
7349
7350            if (!mHasPerformedLongPress) {
7351                removeLongPressCallback();
7352            }
7353        }
7354    }
7355
7356    /**
7357     * Returns true if this view has focus
7358     *
7359     * @return True if this view has focus, false otherwise.
7360     */
7361    @ViewDebug.ExportedProperty(category = "focus")
7362    public boolean isFocused() {
7363        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7364    }
7365
7366    /**
7367     * Find the view in the hierarchy rooted at this view that currently has
7368     * focus.
7369     *
7370     * @return The view that currently has focus, or null if no focused view can
7371     *         be found.
7372     */
7373    public View findFocus() {
7374        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7375    }
7376
7377    /**
7378     * Indicates whether this view is one of the set of scrollable containers in
7379     * its window.
7380     *
7381     * @return whether this view is one of the set of scrollable containers in
7382     * its window
7383     *
7384     * @attr ref android.R.styleable#View_isScrollContainer
7385     */
7386    public boolean isScrollContainer() {
7387        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7388    }
7389
7390    /**
7391     * Change whether this view is one of the set of scrollable containers in
7392     * its window.  This will be used to determine whether the window can
7393     * resize or must pan when a soft input area is open -- scrollable
7394     * containers allow the window to use resize mode since the container
7395     * will appropriately shrink.
7396     *
7397     * @attr ref android.R.styleable#View_isScrollContainer
7398     */
7399    public void setScrollContainer(boolean isScrollContainer) {
7400        if (isScrollContainer) {
7401            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7402                mAttachInfo.mScrollContainers.add(this);
7403                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7404            }
7405            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7406        } else {
7407            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7408                mAttachInfo.mScrollContainers.remove(this);
7409            }
7410            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7411        }
7412    }
7413
7414    /**
7415     * Returns the quality of the drawing cache.
7416     *
7417     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7418     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7419     *
7420     * @see #setDrawingCacheQuality(int)
7421     * @see #setDrawingCacheEnabled(boolean)
7422     * @see #isDrawingCacheEnabled()
7423     *
7424     * @attr ref android.R.styleable#View_drawingCacheQuality
7425     */
7426    @DrawingCacheQuality
7427    public int getDrawingCacheQuality() {
7428        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7429    }
7430
7431    /**
7432     * Set the drawing cache quality of this view. This value is used only when the
7433     * drawing cache is enabled
7434     *
7435     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7436     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7437     *
7438     * @see #getDrawingCacheQuality()
7439     * @see #setDrawingCacheEnabled(boolean)
7440     * @see #isDrawingCacheEnabled()
7441     *
7442     * @attr ref android.R.styleable#View_drawingCacheQuality
7443     */
7444    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7445        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7446    }
7447
7448    /**
7449     * Returns whether the screen should remain on, corresponding to the current
7450     * value of {@link #KEEP_SCREEN_ON}.
7451     *
7452     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7453     *
7454     * @see #setKeepScreenOn(boolean)
7455     *
7456     * @attr ref android.R.styleable#View_keepScreenOn
7457     */
7458    public boolean getKeepScreenOn() {
7459        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7460    }
7461
7462    /**
7463     * Controls whether the screen should remain on, modifying the
7464     * value of {@link #KEEP_SCREEN_ON}.
7465     *
7466     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7467     *
7468     * @see #getKeepScreenOn()
7469     *
7470     * @attr ref android.R.styleable#View_keepScreenOn
7471     */
7472    public void setKeepScreenOn(boolean keepScreenOn) {
7473        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7474    }
7475
7476    /**
7477     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7478     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7479     *
7480     * @attr ref android.R.styleable#View_nextFocusLeft
7481     */
7482    public int getNextFocusLeftId() {
7483        return mNextFocusLeftId;
7484    }
7485
7486    /**
7487     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7488     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7489     * decide automatically.
7490     *
7491     * @attr ref android.R.styleable#View_nextFocusLeft
7492     */
7493    public void setNextFocusLeftId(int nextFocusLeftId) {
7494        mNextFocusLeftId = nextFocusLeftId;
7495    }
7496
7497    /**
7498     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7499     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7500     *
7501     * @attr ref android.R.styleable#View_nextFocusRight
7502     */
7503    public int getNextFocusRightId() {
7504        return mNextFocusRightId;
7505    }
7506
7507    /**
7508     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7509     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7510     * decide automatically.
7511     *
7512     * @attr ref android.R.styleable#View_nextFocusRight
7513     */
7514    public void setNextFocusRightId(int nextFocusRightId) {
7515        mNextFocusRightId = nextFocusRightId;
7516    }
7517
7518    /**
7519     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7520     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7521     *
7522     * @attr ref android.R.styleable#View_nextFocusUp
7523     */
7524    public int getNextFocusUpId() {
7525        return mNextFocusUpId;
7526    }
7527
7528    /**
7529     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7530     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7531     * decide automatically.
7532     *
7533     * @attr ref android.R.styleable#View_nextFocusUp
7534     */
7535    public void setNextFocusUpId(int nextFocusUpId) {
7536        mNextFocusUpId = nextFocusUpId;
7537    }
7538
7539    /**
7540     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7541     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7542     *
7543     * @attr ref android.R.styleable#View_nextFocusDown
7544     */
7545    public int getNextFocusDownId() {
7546        return mNextFocusDownId;
7547    }
7548
7549    /**
7550     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7551     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7552     * decide automatically.
7553     *
7554     * @attr ref android.R.styleable#View_nextFocusDown
7555     */
7556    public void setNextFocusDownId(int nextFocusDownId) {
7557        mNextFocusDownId = nextFocusDownId;
7558    }
7559
7560    /**
7561     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7562     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7563     *
7564     * @attr ref android.R.styleable#View_nextFocusForward
7565     */
7566    public int getNextFocusForwardId() {
7567        return mNextFocusForwardId;
7568    }
7569
7570    /**
7571     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7572     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7573     * decide automatically.
7574     *
7575     * @attr ref android.R.styleable#View_nextFocusForward
7576     */
7577    public void setNextFocusForwardId(int nextFocusForwardId) {
7578        mNextFocusForwardId = nextFocusForwardId;
7579    }
7580
7581    /**
7582     * Returns the visibility of this view and all of its ancestors
7583     *
7584     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7585     */
7586    public boolean isShown() {
7587        View current = this;
7588        //noinspection ConstantConditions
7589        do {
7590            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7591                return false;
7592            }
7593            ViewParent parent = current.mParent;
7594            if (parent == null) {
7595                return false; // We are not attached to the view root
7596            }
7597            if (!(parent instanceof View)) {
7598                return true;
7599            }
7600            current = (View) parent;
7601        } while (current != null);
7602
7603        return false;
7604    }
7605
7606    /**
7607     * Called by the view hierarchy when the content insets for a window have
7608     * changed, to allow it to adjust its content to fit within those windows.
7609     * The content insets tell you the space that the status bar, input method,
7610     * and other system windows infringe on the application's window.
7611     *
7612     * <p>You do not normally need to deal with this function, since the default
7613     * window decoration given to applications takes care of applying it to the
7614     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7615     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7616     * and your content can be placed under those system elements.  You can then
7617     * use this method within your view hierarchy if you have parts of your UI
7618     * which you would like to ensure are not being covered.
7619     *
7620     * <p>The default implementation of this method simply applies the content
7621     * insets to the view's padding, consuming that content (modifying the
7622     * insets to be 0), and returning true.  This behavior is off by default, but can
7623     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7624     *
7625     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7626     * insets object is propagated down the hierarchy, so any changes made to it will
7627     * be seen by all following views (including potentially ones above in
7628     * the hierarchy since this is a depth-first traversal).  The first view
7629     * that returns true will abort the entire traversal.
7630     *
7631     * <p>The default implementation works well for a situation where it is
7632     * used with a container that covers the entire window, allowing it to
7633     * apply the appropriate insets to its content on all edges.  If you need
7634     * a more complicated layout (such as two different views fitting system
7635     * windows, one on the top of the window, and one on the bottom),
7636     * you can override the method and handle the insets however you would like.
7637     * Note that the insets provided by the framework are always relative to the
7638     * far edges of the window, not accounting for the location of the called view
7639     * within that window.  (In fact when this method is called you do not yet know
7640     * where the layout will place the view, as it is done before layout happens.)
7641     *
7642     * <p>Note: unlike many View methods, there is no dispatch phase to this
7643     * call.  If you are overriding it in a ViewGroup and want to allow the
7644     * call to continue to your children, you must be sure to call the super
7645     * implementation.
7646     *
7647     * <p>Here is a sample layout that makes use of fitting system windows
7648     * to have controls for a video view placed inside of the window decorations
7649     * that it hides and shows.  This can be used with code like the second
7650     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7651     *
7652     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7653     *
7654     * @param insets Current content insets of the window.  Prior to
7655     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7656     * the insets or else you and Android will be unhappy.
7657     *
7658     * @return {@code true} if this view applied the insets and it should not
7659     * continue propagating further down the hierarchy, {@code false} otherwise.
7660     * @see #getFitsSystemWindows()
7661     * @see #setFitsSystemWindows(boolean)
7662     * @see #setSystemUiVisibility(int)
7663     *
7664     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7665     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7666     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7667     * to implement handling their own insets.
7668     */
7669    protected boolean fitSystemWindows(Rect insets) {
7670        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7671            if (insets == null) {
7672                // Null insets by definition have already been consumed.
7673                // This call cannot apply insets since there are none to apply,
7674                // so return false.
7675                return false;
7676            }
7677            // If we're not in the process of dispatching the newer apply insets call,
7678            // that means we're not in the compatibility path. Dispatch into the newer
7679            // apply insets path and take things from there.
7680            try {
7681                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7682                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7683            } finally {
7684                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7685            }
7686        } else {
7687            // We're being called from the newer apply insets path.
7688            // Perform the standard fallback behavior.
7689            return fitSystemWindowsInt(insets);
7690        }
7691    }
7692
7693    private boolean fitSystemWindowsInt(Rect insets) {
7694        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7695            mUserPaddingStart = UNDEFINED_PADDING;
7696            mUserPaddingEnd = UNDEFINED_PADDING;
7697            Rect localInsets = sThreadLocal.get();
7698            if (localInsets == null) {
7699                localInsets = new Rect();
7700                sThreadLocal.set(localInsets);
7701            }
7702            boolean res = computeFitSystemWindows(insets, localInsets);
7703            mUserPaddingLeftInitial = localInsets.left;
7704            mUserPaddingRightInitial = localInsets.right;
7705            internalSetPadding(localInsets.left, localInsets.top,
7706                    localInsets.right, localInsets.bottom);
7707            return res;
7708        }
7709        return false;
7710    }
7711
7712    /**
7713     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7714     *
7715     * <p>This method should be overridden by views that wish to apply a policy different from or
7716     * in addition to the default behavior. Clients that wish to force a view subtree
7717     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7718     *
7719     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7720     * it will be called during dispatch instead of this method. The listener may optionally
7721     * call this method from its own implementation if it wishes to apply the view's default
7722     * insets policy in addition to its own.</p>
7723     *
7724     * <p>Implementations of this method should either return the insets parameter unchanged
7725     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7726     * that this view applied itself. This allows new inset types added in future platform
7727     * versions to pass through existing implementations unchanged without being erroneously
7728     * consumed.</p>
7729     *
7730     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7731     * property is set then the view will consume the system window insets and apply them
7732     * as padding for the view.</p>
7733     *
7734     * @param insets Insets to apply
7735     * @return The supplied insets with any applied insets consumed
7736     */
7737    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7738        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7739            // We weren't called from within a direct call to fitSystemWindows,
7740            // call into it as a fallback in case we're in a class that overrides it
7741            // and has logic to perform.
7742            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7743                return insets.consumeSystemWindowInsets();
7744            }
7745        } else {
7746            // We were called from within a direct call to fitSystemWindows.
7747            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7748                return insets.consumeSystemWindowInsets();
7749            }
7750        }
7751        return insets;
7752    }
7753
7754    /**
7755     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7756     * window insets to this view. The listener's
7757     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7758     * method will be called instead of the view's
7759     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7760     *
7761     * @param listener Listener to set
7762     *
7763     * @see #onApplyWindowInsets(WindowInsets)
7764     */
7765    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7766        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7767    }
7768
7769    /**
7770     * Request to apply the given window insets to this view or another view in its subtree.
7771     *
7772     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7773     * obscured by window decorations or overlays. This can include the status and navigation bars,
7774     * action bars, input methods and more. New inset categories may be added in the future.
7775     * The method returns the insets provided minus any that were applied by this view or its
7776     * children.</p>
7777     *
7778     * <p>Clients wishing to provide custom behavior should override the
7779     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7780     * {@link OnApplyWindowInsetsListener} via the
7781     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7782     * method.</p>
7783     *
7784     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7785     * </p>
7786     *
7787     * @param insets Insets to apply
7788     * @return The provided insets minus the insets that were consumed
7789     */
7790    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7791        try {
7792            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7793            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7794                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7795            } else {
7796                return onApplyWindowInsets(insets);
7797            }
7798        } finally {
7799            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7800        }
7801    }
7802
7803    /**
7804     * Compute the view's coordinate within the surface.
7805     *
7806     * <p>Computes the coordinates of this view in its surface. The argument
7807     * must be an array of two integers. After the method returns, the array
7808     * contains the x and y location in that order.</p>
7809     * @hide
7810     * @param location an array of two integers in which to hold the coordinates
7811     */
7812    public void getLocationInSurface(@Size(2) int[] location) {
7813        getLocationInWindow(location);
7814        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7815            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7816            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7817        }
7818    }
7819
7820    /**
7821     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7822     * only available if the view is attached.
7823     *
7824     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7825     */
7826    public WindowInsets getRootWindowInsets() {
7827        if (mAttachInfo != null) {
7828            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7829        }
7830        return null;
7831    }
7832
7833    /**
7834     * @hide Compute the insets that should be consumed by this view and the ones
7835     * that should propagate to those under it.
7836     */
7837    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7838        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7839                || mAttachInfo == null
7840                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7841                        && !mAttachInfo.mOverscanRequested)) {
7842            outLocalInsets.set(inoutInsets);
7843            inoutInsets.set(0, 0, 0, 0);
7844            return true;
7845        } else {
7846            // The application wants to take care of fitting system window for
7847            // the content...  however we still need to take care of any overscan here.
7848            final Rect overscan = mAttachInfo.mOverscanInsets;
7849            outLocalInsets.set(overscan);
7850            inoutInsets.left -= overscan.left;
7851            inoutInsets.top -= overscan.top;
7852            inoutInsets.right -= overscan.right;
7853            inoutInsets.bottom -= overscan.bottom;
7854            return false;
7855        }
7856    }
7857
7858    /**
7859     * Compute insets that should be consumed by this view and the ones that should propagate
7860     * to those under it.
7861     *
7862     * @param in Insets currently being processed by this View, likely received as a parameter
7863     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7864     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7865     *                       by this view
7866     * @return Insets that should be passed along to views under this one
7867     */
7868    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7869        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7870                || mAttachInfo == null
7871                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7872            outLocalInsets.set(in.getSystemWindowInsets());
7873            return in.consumeSystemWindowInsets();
7874        } else {
7875            outLocalInsets.set(0, 0, 0, 0);
7876            return in;
7877        }
7878    }
7879
7880    /**
7881     * Sets whether or not this view should account for system screen decorations
7882     * such as the status bar and inset its content; that is, controlling whether
7883     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7884     * executed.  See that method for more details.
7885     *
7886     * <p>Note that if you are providing your own implementation of
7887     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7888     * flag to true -- your implementation will be overriding the default
7889     * implementation that checks this flag.
7890     *
7891     * @param fitSystemWindows If true, then the default implementation of
7892     * {@link #fitSystemWindows(Rect)} will be executed.
7893     *
7894     * @attr ref android.R.styleable#View_fitsSystemWindows
7895     * @see #getFitsSystemWindows()
7896     * @see #fitSystemWindows(Rect)
7897     * @see #setSystemUiVisibility(int)
7898     */
7899    public void setFitsSystemWindows(boolean fitSystemWindows) {
7900        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7901    }
7902
7903    /**
7904     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7905     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7906     * will be executed.
7907     *
7908     * @return {@code true} if the default implementation of
7909     * {@link #fitSystemWindows(Rect)} will be executed.
7910     *
7911     * @attr ref android.R.styleable#View_fitsSystemWindows
7912     * @see #setFitsSystemWindows(boolean)
7913     * @see #fitSystemWindows(Rect)
7914     * @see #setSystemUiVisibility(int)
7915     */
7916    @ViewDebug.ExportedProperty
7917    public boolean getFitsSystemWindows() {
7918        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7919    }
7920
7921    /** @hide */
7922    public boolean fitsSystemWindows() {
7923        return getFitsSystemWindows();
7924    }
7925
7926    /**
7927     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7928     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7929     */
7930    public void requestFitSystemWindows() {
7931        if (mParent != null) {
7932            mParent.requestFitSystemWindows();
7933        }
7934    }
7935
7936    /**
7937     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7938     */
7939    public void requestApplyInsets() {
7940        requestFitSystemWindows();
7941    }
7942
7943    /**
7944     * For use by PhoneWindow to make its own system window fitting optional.
7945     * @hide
7946     */
7947    public void makeOptionalFitsSystemWindows() {
7948        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7949    }
7950
7951    /**
7952     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7953     * treat them as such.
7954     * @hide
7955     */
7956    public void getOutsets(Rect outOutsetRect) {
7957        if (mAttachInfo != null) {
7958            outOutsetRect.set(mAttachInfo.mOutsets);
7959        } else {
7960            outOutsetRect.setEmpty();
7961        }
7962    }
7963
7964    /**
7965     * Returns the visibility status for this view.
7966     *
7967     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7968     * @attr ref android.R.styleable#View_visibility
7969     */
7970    @ViewDebug.ExportedProperty(mapping = {
7971        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7972        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7973        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7974    })
7975    @Visibility
7976    public int getVisibility() {
7977        return mViewFlags & VISIBILITY_MASK;
7978    }
7979
7980    /**
7981     * Set the enabled state of this view.
7982     *
7983     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7984     * @attr ref android.R.styleable#View_visibility
7985     */
7986    @RemotableViewMethod
7987    public void setVisibility(@Visibility int visibility) {
7988        setFlags(visibility, VISIBILITY_MASK);
7989    }
7990
7991    /**
7992     * Returns the enabled status for this view. The interpretation of the
7993     * enabled state varies by subclass.
7994     *
7995     * @return True if this view is enabled, false otherwise.
7996     */
7997    @ViewDebug.ExportedProperty
7998    public boolean isEnabled() {
7999        return (mViewFlags & ENABLED_MASK) == ENABLED;
8000    }
8001
8002    /**
8003     * Set the enabled state of this view. The interpretation of the enabled
8004     * state varies by subclass.
8005     *
8006     * @param enabled True if this view is enabled, false otherwise.
8007     */
8008    @RemotableViewMethod
8009    public void setEnabled(boolean enabled) {
8010        if (enabled == isEnabled()) return;
8011
8012        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8013
8014        /*
8015         * The View most likely has to change its appearance, so refresh
8016         * the drawable state.
8017         */
8018        refreshDrawableState();
8019
8020        // Invalidate too, since the default behavior for views is to be
8021        // be drawn at 50% alpha rather than to change the drawable.
8022        invalidate(true);
8023
8024        if (!enabled) {
8025            cancelPendingInputEvents();
8026        }
8027    }
8028
8029    /**
8030     * Set whether this view can receive the focus.
8031     *
8032     * Setting this to false will also ensure that this view is not focusable
8033     * in touch mode.
8034     *
8035     * @param focusable If true, this view can receive the focus.
8036     *
8037     * @see #setFocusableInTouchMode(boolean)
8038     * @attr ref android.R.styleable#View_focusable
8039     */
8040    public void setFocusable(boolean focusable) {
8041        if (!focusable) {
8042            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8043        }
8044        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8045    }
8046
8047    /**
8048     * Set whether this view can receive focus while in touch mode.
8049     *
8050     * Setting this to true will also ensure that this view is focusable.
8051     *
8052     * @param focusableInTouchMode If true, this view can receive the focus while
8053     *   in touch mode.
8054     *
8055     * @see #setFocusable(boolean)
8056     * @attr ref android.R.styleable#View_focusableInTouchMode
8057     */
8058    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8059        // Focusable in touch mode should always be set before the focusable flag
8060        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8061        // which, in touch mode, will not successfully request focus on this view
8062        // because the focusable in touch mode flag is not set
8063        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8064        if (focusableInTouchMode) {
8065            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8066        }
8067    }
8068
8069    /**
8070     * Set whether this view should have sound effects enabled for events such as
8071     * clicking and touching.
8072     *
8073     * <p>You may wish to disable sound effects for a view if you already play sounds,
8074     * for instance, a dial key that plays dtmf tones.
8075     *
8076     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8077     * @see #isSoundEffectsEnabled()
8078     * @see #playSoundEffect(int)
8079     * @attr ref android.R.styleable#View_soundEffectsEnabled
8080     */
8081    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8082        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8083    }
8084
8085    /**
8086     * @return whether this view should have sound effects enabled for events such as
8087     *     clicking and touching.
8088     *
8089     * @see #setSoundEffectsEnabled(boolean)
8090     * @see #playSoundEffect(int)
8091     * @attr ref android.R.styleable#View_soundEffectsEnabled
8092     */
8093    @ViewDebug.ExportedProperty
8094    public boolean isSoundEffectsEnabled() {
8095        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8096    }
8097
8098    /**
8099     * Set whether this view should have haptic feedback for events such as
8100     * long presses.
8101     *
8102     * <p>You may wish to disable haptic feedback if your view already controls
8103     * its own haptic feedback.
8104     *
8105     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8106     * @see #isHapticFeedbackEnabled()
8107     * @see #performHapticFeedback(int)
8108     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8109     */
8110    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8111        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8112    }
8113
8114    /**
8115     * @return whether this view should have haptic feedback enabled for events
8116     * long presses.
8117     *
8118     * @see #setHapticFeedbackEnabled(boolean)
8119     * @see #performHapticFeedback(int)
8120     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8121     */
8122    @ViewDebug.ExportedProperty
8123    public boolean isHapticFeedbackEnabled() {
8124        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8125    }
8126
8127    /**
8128     * Returns the layout direction for this view.
8129     *
8130     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8131     *   {@link #LAYOUT_DIRECTION_RTL},
8132     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8133     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8134     *
8135     * @attr ref android.R.styleable#View_layoutDirection
8136     *
8137     * @hide
8138     */
8139    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8140        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8141        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8142        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8143        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8144    })
8145    @LayoutDir
8146    public int getRawLayoutDirection() {
8147        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8148    }
8149
8150    /**
8151     * Set the layout direction for this view. This will propagate a reset of layout direction
8152     * resolution to the view's children and resolve layout direction for this view.
8153     *
8154     * @param layoutDirection the layout direction to set. Should be one of:
8155     *
8156     * {@link #LAYOUT_DIRECTION_LTR},
8157     * {@link #LAYOUT_DIRECTION_RTL},
8158     * {@link #LAYOUT_DIRECTION_INHERIT},
8159     * {@link #LAYOUT_DIRECTION_LOCALE}.
8160     *
8161     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8162     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8163     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8164     *
8165     * @attr ref android.R.styleable#View_layoutDirection
8166     */
8167    @RemotableViewMethod
8168    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8169        if (getRawLayoutDirection() != layoutDirection) {
8170            // Reset the current layout direction and the resolved one
8171            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8172            resetRtlProperties();
8173            // Set the new layout direction (filtered)
8174            mPrivateFlags2 |=
8175                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8176            // We need to resolve all RTL properties as they all depend on layout direction
8177            resolveRtlPropertiesIfNeeded();
8178            requestLayout();
8179            invalidate(true);
8180        }
8181    }
8182
8183    /**
8184     * Returns the resolved layout direction for this view.
8185     *
8186     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8187     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8188     *
8189     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8190     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8191     *
8192     * @attr ref android.R.styleable#View_layoutDirection
8193     */
8194    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8195        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8196        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8197    })
8198    @ResolvedLayoutDir
8199    public int getLayoutDirection() {
8200        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8201        if (targetSdkVersion < JELLY_BEAN_MR1) {
8202            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8203            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8204        }
8205        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8206                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8207    }
8208
8209    /**
8210     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8211     * layout attribute and/or the inherited value from the parent
8212     *
8213     * @return true if the layout is right-to-left.
8214     *
8215     * @hide
8216     */
8217    @ViewDebug.ExportedProperty(category = "layout")
8218    public boolean isLayoutRtl() {
8219        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8220    }
8221
8222    /**
8223     * Indicates whether the view is currently tracking transient state that the
8224     * app should not need to concern itself with saving and restoring, but that
8225     * the framework should take special note to preserve when possible.
8226     *
8227     * <p>A view with transient state cannot be trivially rebound from an external
8228     * data source, such as an adapter binding item views in a list. This may be
8229     * because the view is performing an animation, tracking user selection
8230     * of content, or similar.</p>
8231     *
8232     * @return true if the view has transient state
8233     */
8234    @ViewDebug.ExportedProperty(category = "layout")
8235    public boolean hasTransientState() {
8236        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8237    }
8238
8239    /**
8240     * Set whether this view is currently tracking transient state that the
8241     * framework should attempt to preserve when possible. This flag is reference counted,
8242     * so every call to setHasTransientState(true) should be paired with a later call
8243     * to setHasTransientState(false).
8244     *
8245     * <p>A view with transient state cannot be trivially rebound from an external
8246     * data source, such as an adapter binding item views in a list. This may be
8247     * because the view is performing an animation, tracking user selection
8248     * of content, or similar.</p>
8249     *
8250     * @param hasTransientState true if this view has transient state
8251     */
8252    public void setHasTransientState(boolean hasTransientState) {
8253        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8254                mTransientStateCount - 1;
8255        if (mTransientStateCount < 0) {
8256            mTransientStateCount = 0;
8257            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8258                    "unmatched pair of setHasTransientState calls");
8259        } else if ((hasTransientState && mTransientStateCount == 1) ||
8260                (!hasTransientState && mTransientStateCount == 0)) {
8261            // update flag if we've just incremented up from 0 or decremented down to 0
8262            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8263                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8264            if (mParent != null) {
8265                try {
8266                    mParent.childHasTransientStateChanged(this, hasTransientState);
8267                } catch (AbstractMethodError e) {
8268                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8269                            " does not fully implement ViewParent", e);
8270                }
8271            }
8272        }
8273    }
8274
8275    /**
8276     * Returns true if this view is currently attached to a window.
8277     */
8278    public boolean isAttachedToWindow() {
8279        return mAttachInfo != null;
8280    }
8281
8282    /**
8283     * Returns true if this view has been through at least one layout since it
8284     * was last attached to or detached from a window.
8285     */
8286    public boolean isLaidOut() {
8287        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8288    }
8289
8290    /**
8291     * If this view doesn't do any drawing on its own, set this flag to
8292     * allow further optimizations. By default, this flag is not set on
8293     * View, but could be set on some View subclasses such as ViewGroup.
8294     *
8295     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8296     * you should clear this flag.
8297     *
8298     * @param willNotDraw whether or not this View draw on its own
8299     */
8300    public void setWillNotDraw(boolean willNotDraw) {
8301        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8302    }
8303
8304    /**
8305     * Returns whether or not this View draws on its own.
8306     *
8307     * @return true if this view has nothing to draw, false otherwise
8308     */
8309    @ViewDebug.ExportedProperty(category = "drawing")
8310    public boolean willNotDraw() {
8311        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8312    }
8313
8314    /**
8315     * When a View's drawing cache is enabled, drawing is redirected to an
8316     * offscreen bitmap. Some views, like an ImageView, must be able to
8317     * bypass this mechanism if they already draw a single bitmap, to avoid
8318     * unnecessary usage of the memory.
8319     *
8320     * @param willNotCacheDrawing true if this view does not cache its
8321     *        drawing, false otherwise
8322     */
8323    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8324        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8325    }
8326
8327    /**
8328     * Returns whether or not this View can cache its drawing or not.
8329     *
8330     * @return true if this view does not cache its drawing, false otherwise
8331     */
8332    @ViewDebug.ExportedProperty(category = "drawing")
8333    public boolean willNotCacheDrawing() {
8334        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8335    }
8336
8337    /**
8338     * Indicates whether this view reacts to click events or not.
8339     *
8340     * @return true if the view is clickable, false otherwise
8341     *
8342     * @see #setClickable(boolean)
8343     * @attr ref android.R.styleable#View_clickable
8344     */
8345    @ViewDebug.ExportedProperty
8346    public boolean isClickable() {
8347        return (mViewFlags & CLICKABLE) == CLICKABLE;
8348    }
8349
8350    /**
8351     * Enables or disables click events for this view. When a view
8352     * is clickable it will change its state to "pressed" on every click.
8353     * Subclasses should set the view clickable to visually react to
8354     * user's clicks.
8355     *
8356     * @param clickable true to make the view clickable, false otherwise
8357     *
8358     * @see #isClickable()
8359     * @attr ref android.R.styleable#View_clickable
8360     */
8361    public void setClickable(boolean clickable) {
8362        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8363    }
8364
8365    /**
8366     * Indicates whether this view reacts to long click events or not.
8367     *
8368     * @return true if the view is long clickable, false otherwise
8369     *
8370     * @see #setLongClickable(boolean)
8371     * @attr ref android.R.styleable#View_longClickable
8372     */
8373    public boolean isLongClickable() {
8374        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8375    }
8376
8377    /**
8378     * Enables or disables long click events for this view. When a view is long
8379     * clickable it reacts to the user holding down the button for a longer
8380     * duration than a tap. This event can either launch the listener or a
8381     * context menu.
8382     *
8383     * @param longClickable true to make the view long clickable, false otherwise
8384     * @see #isLongClickable()
8385     * @attr ref android.R.styleable#View_longClickable
8386     */
8387    public void setLongClickable(boolean longClickable) {
8388        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8389    }
8390
8391    /**
8392     * Indicates whether this view reacts to context clicks or not.
8393     *
8394     * @return true if the view is context clickable, false otherwise
8395     * @see #setContextClickable(boolean)
8396     * @attr ref android.R.styleable#View_contextClickable
8397     */
8398    public boolean isContextClickable() {
8399        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8400    }
8401
8402    /**
8403     * Enables or disables context clicking for this view. This event can launch the listener.
8404     *
8405     * @param contextClickable true to make the view react to a context click, false otherwise
8406     * @see #isContextClickable()
8407     * @attr ref android.R.styleable#View_contextClickable
8408     */
8409    public void setContextClickable(boolean contextClickable) {
8410        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8411    }
8412
8413    /**
8414     * Sets the pressed state for this view and provides a touch coordinate for
8415     * animation hinting.
8416     *
8417     * @param pressed Pass true to set the View's internal state to "pressed",
8418     *            or false to reverts the View's internal state from a
8419     *            previously set "pressed" state.
8420     * @param x The x coordinate of the touch that caused the press
8421     * @param y The y coordinate of the touch that caused the press
8422     */
8423    private void setPressed(boolean pressed, float x, float y) {
8424        if (pressed) {
8425            drawableHotspotChanged(x, y);
8426        }
8427
8428        setPressed(pressed);
8429    }
8430
8431    /**
8432     * Sets the pressed state for this view.
8433     *
8434     * @see #isClickable()
8435     * @see #setClickable(boolean)
8436     *
8437     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8438     *        the View's internal state from a previously set "pressed" state.
8439     */
8440    public void setPressed(boolean pressed) {
8441        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8442
8443        if (pressed) {
8444            mPrivateFlags |= PFLAG_PRESSED;
8445        } else {
8446            mPrivateFlags &= ~PFLAG_PRESSED;
8447        }
8448
8449        if (needsRefresh) {
8450            refreshDrawableState();
8451        }
8452        dispatchSetPressed(pressed);
8453    }
8454
8455    /**
8456     * Dispatch setPressed to all of this View's children.
8457     *
8458     * @see #setPressed(boolean)
8459     *
8460     * @param pressed The new pressed state
8461     */
8462    protected void dispatchSetPressed(boolean pressed) {
8463    }
8464
8465    /**
8466     * Indicates whether the view is currently in pressed state. Unless
8467     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8468     * the pressed state.
8469     *
8470     * @see #setPressed(boolean)
8471     * @see #isClickable()
8472     * @see #setClickable(boolean)
8473     *
8474     * @return true if the view is currently pressed, false otherwise
8475     */
8476    @ViewDebug.ExportedProperty
8477    public boolean isPressed() {
8478        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8479    }
8480
8481    /**
8482     * @hide
8483     * Indicates whether this view will participate in data collection through
8484     * {@link ViewStructure}.  If true, it will not provide any data
8485     * for itself or its children.  If false, the normal data collection will be allowed.
8486     *
8487     * @return Returns false if assist data collection is not blocked, else true.
8488     *
8489     * @see #setAssistBlocked(boolean)
8490     * @attr ref android.R.styleable#View_assistBlocked
8491     */
8492    public boolean isAssistBlocked() {
8493        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8494    }
8495
8496    /**
8497     * @hide
8498     * Controls whether assist data collection from this view and its children is enabled
8499     * (that is, whether {@link #onProvideStructure} and
8500     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8501     * allowing normal assist collection.  Setting this to false will disable assist collection.
8502     *
8503     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8504     * (the default) to allow it.
8505     *
8506     * @see #isAssistBlocked()
8507     * @see #onProvideStructure
8508     * @see #onProvideVirtualStructure
8509     * @attr ref android.R.styleable#View_assistBlocked
8510     */
8511    public void setAssistBlocked(boolean enabled) {
8512        if (enabled) {
8513            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8514        } else {
8515            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8516        }
8517    }
8518
8519    /**
8520     * Indicates whether this view will save its state (that is,
8521     * whether its {@link #onSaveInstanceState} method will be called).
8522     *
8523     * @return Returns true if the view state saving is enabled, else false.
8524     *
8525     * @see #setSaveEnabled(boolean)
8526     * @attr ref android.R.styleable#View_saveEnabled
8527     */
8528    public boolean isSaveEnabled() {
8529        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8530    }
8531
8532    /**
8533     * Controls whether the saving of this view's state is
8534     * enabled (that is, whether its {@link #onSaveInstanceState} method
8535     * will be called).  Note that even if freezing is enabled, the
8536     * view still must have an id assigned to it (via {@link #setId(int)})
8537     * for its state to be saved.  This flag can only disable the
8538     * saving of this view; any child views may still have their state saved.
8539     *
8540     * @param enabled Set to false to <em>disable</em> state saving, or true
8541     * (the default) to allow it.
8542     *
8543     * @see #isSaveEnabled()
8544     * @see #setId(int)
8545     * @see #onSaveInstanceState()
8546     * @attr ref android.R.styleable#View_saveEnabled
8547     */
8548    public void setSaveEnabled(boolean enabled) {
8549        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8550    }
8551
8552    /**
8553     * Gets whether the framework should discard touches when the view's
8554     * window is obscured by another visible window.
8555     * Refer to the {@link View} security documentation for more details.
8556     *
8557     * @return True if touch filtering is enabled.
8558     *
8559     * @see #setFilterTouchesWhenObscured(boolean)
8560     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8561     */
8562    @ViewDebug.ExportedProperty
8563    public boolean getFilterTouchesWhenObscured() {
8564        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8565    }
8566
8567    /**
8568     * Sets whether the framework should discard touches when the view's
8569     * window is obscured by another visible window.
8570     * Refer to the {@link View} security documentation for more details.
8571     *
8572     * @param enabled True if touch filtering should be enabled.
8573     *
8574     * @see #getFilterTouchesWhenObscured
8575     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8576     */
8577    public void setFilterTouchesWhenObscured(boolean enabled) {
8578        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8579                FILTER_TOUCHES_WHEN_OBSCURED);
8580    }
8581
8582    /**
8583     * Indicates whether the entire hierarchy under this view will save its
8584     * state when a state saving traversal occurs from its parent.  The default
8585     * is true; if false, these views will not be saved unless
8586     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8587     *
8588     * @return Returns true if the view state saving from parent is enabled, else false.
8589     *
8590     * @see #setSaveFromParentEnabled(boolean)
8591     */
8592    public boolean isSaveFromParentEnabled() {
8593        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8594    }
8595
8596    /**
8597     * Controls whether the entire hierarchy under this view will save its
8598     * state when a state saving traversal occurs from its parent.  The default
8599     * is true; if false, these views will not be saved unless
8600     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8601     *
8602     * @param enabled Set to false to <em>disable</em> state saving, or true
8603     * (the default) to allow it.
8604     *
8605     * @see #isSaveFromParentEnabled()
8606     * @see #setId(int)
8607     * @see #onSaveInstanceState()
8608     */
8609    public void setSaveFromParentEnabled(boolean enabled) {
8610        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8611    }
8612
8613
8614    /**
8615     * Returns whether this View is able to take focus.
8616     *
8617     * @return True if this view can take focus, or false otherwise.
8618     * @attr ref android.R.styleable#View_focusable
8619     */
8620    @ViewDebug.ExportedProperty(category = "focus")
8621    public final boolean isFocusable() {
8622        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8623    }
8624
8625    /**
8626     * When a view is focusable, it may not want to take focus when in touch mode.
8627     * For example, a button would like focus when the user is navigating via a D-pad
8628     * so that the user can click on it, but once the user starts touching the screen,
8629     * the button shouldn't take focus
8630     * @return Whether the view is focusable in touch mode.
8631     * @attr ref android.R.styleable#View_focusableInTouchMode
8632     */
8633    @ViewDebug.ExportedProperty
8634    public final boolean isFocusableInTouchMode() {
8635        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8636    }
8637
8638    /**
8639     * Find the nearest view in the specified direction that can take focus.
8640     * This does not actually give focus to that view.
8641     *
8642     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8643     *
8644     * @return The nearest focusable in the specified direction, or null if none
8645     *         can be found.
8646     */
8647    public View focusSearch(@FocusRealDirection int direction) {
8648        if (mParent != null) {
8649            return mParent.focusSearch(this, direction);
8650        } else {
8651            return null;
8652        }
8653    }
8654
8655    /**
8656     * This method is the last chance for the focused view and its ancestors to
8657     * respond to an arrow key. This is called when the focused view did not
8658     * consume the key internally, nor could the view system find a new view in
8659     * the requested direction to give focus to.
8660     *
8661     * @param focused The currently focused view.
8662     * @param direction The direction focus wants to move. One of FOCUS_UP,
8663     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8664     * @return True if the this view consumed this unhandled move.
8665     */
8666    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8667        return false;
8668    }
8669
8670    /**
8671     * If a user manually specified the next view id for a particular direction,
8672     * use the root to look up the view.
8673     * @param root The root view of the hierarchy containing this view.
8674     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8675     * or FOCUS_BACKWARD.
8676     * @return The user specified next view, or null if there is none.
8677     */
8678    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8679        switch (direction) {
8680            case FOCUS_LEFT:
8681                if (mNextFocusLeftId == View.NO_ID) return null;
8682                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8683            case FOCUS_RIGHT:
8684                if (mNextFocusRightId == View.NO_ID) return null;
8685                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8686            case FOCUS_UP:
8687                if (mNextFocusUpId == View.NO_ID) return null;
8688                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8689            case FOCUS_DOWN:
8690                if (mNextFocusDownId == View.NO_ID) return null;
8691                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8692            case FOCUS_FORWARD:
8693                if (mNextFocusForwardId == View.NO_ID) return null;
8694                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8695            case FOCUS_BACKWARD: {
8696                if (mID == View.NO_ID) return null;
8697                final int id = mID;
8698                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8699                    @Override
8700                    public boolean apply(View t) {
8701                        return t.mNextFocusForwardId == id;
8702                    }
8703                });
8704            }
8705        }
8706        return null;
8707    }
8708
8709    private View findViewInsideOutShouldExist(View root, int id) {
8710        if (mMatchIdPredicate == null) {
8711            mMatchIdPredicate = new MatchIdPredicate();
8712        }
8713        mMatchIdPredicate.mId = id;
8714        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8715        if (result == null) {
8716            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8717        }
8718        return result;
8719    }
8720
8721    /**
8722     * Find and return all focusable views that are descendants of this view,
8723     * possibly including this view if it is focusable itself.
8724     *
8725     * @param direction The direction of the focus
8726     * @return A list of focusable views
8727     */
8728    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8729        ArrayList<View> result = new ArrayList<View>(24);
8730        addFocusables(result, direction);
8731        return result;
8732    }
8733
8734    /**
8735     * Add any focusable views that are descendants of this view (possibly
8736     * including this view if it is focusable itself) to views.  If we are in touch mode,
8737     * only add views that are also focusable in touch mode.
8738     *
8739     * @param views Focusable views found so far
8740     * @param direction The direction of the focus
8741     */
8742    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8743        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
8744    }
8745
8746    /**
8747     * Adds any focusable views that are descendants of this view (possibly
8748     * including this view if it is focusable itself) to views. This method
8749     * adds all focusable views regardless if we are in touch mode or
8750     * only views focusable in touch mode if we are in touch mode or
8751     * only views that can take accessibility focus if accessibility is enabled
8752     * depending on the focusable mode parameter.
8753     *
8754     * @param views Focusable views found so far or null if all we are interested is
8755     *        the number of focusables.
8756     * @param direction The direction of the focus.
8757     * @param focusableMode The type of focusables to be added.
8758     *
8759     * @see #FOCUSABLES_ALL
8760     * @see #FOCUSABLES_TOUCH_MODE
8761     */
8762    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8763            @FocusableMode int focusableMode) {
8764        if (views == null) {
8765            return;
8766        }
8767        if (!isFocusable()) {
8768            return;
8769        }
8770        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8771                && isInTouchMode() && !isFocusableInTouchMode()) {
8772            return;
8773        }
8774        views.add(this);
8775    }
8776
8777    /**
8778     * Finds the Views that contain given text. The containment is case insensitive.
8779     * The search is performed by either the text that the View renders or the content
8780     * description that describes the view for accessibility purposes and the view does
8781     * not render or both. Clients can specify how the search is to be performed via
8782     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8783     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8784     *
8785     * @param outViews The output list of matching Views.
8786     * @param searched The text to match against.
8787     *
8788     * @see #FIND_VIEWS_WITH_TEXT
8789     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8790     * @see #setContentDescription(CharSequence)
8791     */
8792    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8793            @FindViewFlags int flags) {
8794        if (getAccessibilityNodeProvider() != null) {
8795            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8796                outViews.add(this);
8797            }
8798        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8799                && (searched != null && searched.length() > 0)
8800                && (mContentDescription != null && mContentDescription.length() > 0)) {
8801            String searchedLowerCase = searched.toString().toLowerCase();
8802            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8803            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8804                outViews.add(this);
8805            }
8806        }
8807    }
8808
8809    /**
8810     * Find and return all touchable views that are descendants of this view,
8811     * possibly including this view if it is touchable itself.
8812     *
8813     * @return A list of touchable views
8814     */
8815    public ArrayList<View> getTouchables() {
8816        ArrayList<View> result = new ArrayList<View>();
8817        addTouchables(result);
8818        return result;
8819    }
8820
8821    /**
8822     * Add any touchable views that are descendants of this view (possibly
8823     * including this view if it is touchable itself) to views.
8824     *
8825     * @param views Touchable views found so far
8826     */
8827    public void addTouchables(ArrayList<View> views) {
8828        final int viewFlags = mViewFlags;
8829
8830        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8831                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8832                && (viewFlags & ENABLED_MASK) == ENABLED) {
8833            views.add(this);
8834        }
8835    }
8836
8837    /**
8838     * Returns whether this View is accessibility focused.
8839     *
8840     * @return True if this View is accessibility focused.
8841     */
8842    public boolean isAccessibilityFocused() {
8843        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8844    }
8845
8846    /**
8847     * Call this to try to give accessibility focus to this view.
8848     *
8849     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8850     * returns false or the view is no visible or the view already has accessibility
8851     * focus.
8852     *
8853     * See also {@link #focusSearch(int)}, which is what you call to say that you
8854     * have focus, and you want your parent to look for the next one.
8855     *
8856     * @return Whether this view actually took accessibility focus.
8857     *
8858     * @hide
8859     */
8860    public boolean requestAccessibilityFocus() {
8861        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8862        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8863            return false;
8864        }
8865        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8866            return false;
8867        }
8868        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8869            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8870            ViewRootImpl viewRootImpl = getViewRootImpl();
8871            if (viewRootImpl != null) {
8872                viewRootImpl.setAccessibilityFocus(this, null);
8873            }
8874            invalidate();
8875            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8876            return true;
8877        }
8878        return false;
8879    }
8880
8881    /**
8882     * Call this to try to clear accessibility focus of this view.
8883     *
8884     * See also {@link #focusSearch(int)}, which is what you call to say that you
8885     * have focus, and you want your parent to look for the next one.
8886     *
8887     * @hide
8888     */
8889    public void clearAccessibilityFocus() {
8890        clearAccessibilityFocusNoCallbacks(0);
8891
8892        // Clear the global reference of accessibility focus if this view or
8893        // any of its descendants had accessibility focus. This will NOT send
8894        // an event or update internal state if focus is cleared from a
8895        // descendant view, which may leave views in inconsistent states.
8896        final ViewRootImpl viewRootImpl = getViewRootImpl();
8897        if (viewRootImpl != null) {
8898            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8899            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8900                viewRootImpl.setAccessibilityFocus(null, null);
8901            }
8902        }
8903    }
8904
8905    private void sendAccessibilityHoverEvent(int eventType) {
8906        // Since we are not delivering to a client accessibility events from not
8907        // important views (unless the clinet request that) we need to fire the
8908        // event from the deepest view exposed to the client. As a consequence if
8909        // the user crosses a not exposed view the client will see enter and exit
8910        // of the exposed predecessor followed by and enter and exit of that same
8911        // predecessor when entering and exiting the not exposed descendant. This
8912        // is fine since the client has a clear idea which view is hovered at the
8913        // price of a couple more events being sent. This is a simple and
8914        // working solution.
8915        View source = this;
8916        while (true) {
8917            if (source.includeForAccessibility()) {
8918                source.sendAccessibilityEvent(eventType);
8919                return;
8920            }
8921            ViewParent parent = source.getParent();
8922            if (parent instanceof View) {
8923                source = (View) parent;
8924            } else {
8925                return;
8926            }
8927        }
8928    }
8929
8930    /**
8931     * Clears accessibility focus without calling any callback methods
8932     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8933     * is used separately from that one for clearing accessibility focus when
8934     * giving this focus to another view.
8935     *
8936     * @param action The action, if any, that led to focus being cleared. Set to
8937     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
8938     * the window.
8939     */
8940    void clearAccessibilityFocusNoCallbacks(int action) {
8941        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8942            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8943            invalidate();
8944            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8945                AccessibilityEvent event = AccessibilityEvent.obtain(
8946                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8947                event.setAction(action);
8948                if (mAccessibilityDelegate != null) {
8949                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
8950                } else {
8951                    sendAccessibilityEventUnchecked(event);
8952                }
8953            }
8954        }
8955    }
8956
8957    /**
8958     * Call this to try to give focus to a specific view or to one of its
8959     * descendants.
8960     *
8961     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8962     * false), or if it is focusable and it is not focusable in touch mode
8963     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8964     *
8965     * See also {@link #focusSearch(int)}, which is what you call to say that you
8966     * have focus, and you want your parent to look for the next one.
8967     *
8968     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8969     * {@link #FOCUS_DOWN} and <code>null</code>.
8970     *
8971     * @return Whether this view or one of its descendants actually took focus.
8972     */
8973    public final boolean requestFocus() {
8974        return requestFocus(View.FOCUS_DOWN);
8975    }
8976
8977    /**
8978     * Call this to try to give focus to a specific view or to one of its
8979     * descendants and give it a hint about what direction focus is heading.
8980     *
8981     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8982     * false), or if it is focusable and it is not focusable in touch mode
8983     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8984     *
8985     * See also {@link #focusSearch(int)}, which is what you call to say that you
8986     * have focus, and you want your parent to look for the next one.
8987     *
8988     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8989     * <code>null</code> set for the previously focused rectangle.
8990     *
8991     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8992     * @return Whether this view or one of its descendants actually took focus.
8993     */
8994    public final boolean requestFocus(int direction) {
8995        return requestFocus(direction, null);
8996    }
8997
8998    /**
8999     * Call this to try to give focus to a specific view or to one of its descendants
9000     * and give it hints about the direction and a specific rectangle that the focus
9001     * is coming from.  The rectangle can help give larger views a finer grained hint
9002     * about where focus is coming from, and therefore, where to show selection, or
9003     * forward focus change internally.
9004     *
9005     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9006     * false), or if it is focusable and it is not focusable in touch mode
9007     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9008     *
9009     * A View will not take focus if it is not visible.
9010     *
9011     * A View will not take focus if one of its parents has
9012     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9013     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9014     *
9015     * See also {@link #focusSearch(int)}, which is what you call to say that you
9016     * have focus, and you want your parent to look for the next one.
9017     *
9018     * You may wish to override this method if your custom {@link View} has an internal
9019     * {@link View} that it wishes to forward the request to.
9020     *
9021     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9022     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9023     *        to give a finer grained hint about where focus is coming from.  May be null
9024     *        if there is no hint.
9025     * @return Whether this view or one of its descendants actually took focus.
9026     */
9027    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9028        return requestFocusNoSearch(direction, previouslyFocusedRect);
9029    }
9030
9031    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9032        // need to be focusable
9033        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9034                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9035            return false;
9036        }
9037
9038        // need to be focusable in touch mode if in touch mode
9039        if (isInTouchMode() &&
9040            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9041               return false;
9042        }
9043
9044        // need to not have any parents blocking us
9045        if (hasAncestorThatBlocksDescendantFocus()) {
9046            return false;
9047        }
9048
9049        handleFocusGainInternal(direction, previouslyFocusedRect);
9050        return true;
9051    }
9052
9053    /**
9054     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9055     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9056     * touch mode to request focus when they are touched.
9057     *
9058     * @return Whether this view or one of its descendants actually took focus.
9059     *
9060     * @see #isInTouchMode()
9061     *
9062     */
9063    public final boolean requestFocusFromTouch() {
9064        // Leave touch mode if we need to
9065        if (isInTouchMode()) {
9066            ViewRootImpl viewRoot = getViewRootImpl();
9067            if (viewRoot != null) {
9068                viewRoot.ensureTouchMode(false);
9069            }
9070        }
9071        return requestFocus(View.FOCUS_DOWN);
9072    }
9073
9074    /**
9075     * @return Whether any ancestor of this view blocks descendant focus.
9076     */
9077    private boolean hasAncestorThatBlocksDescendantFocus() {
9078        final boolean focusableInTouchMode = isFocusableInTouchMode();
9079        ViewParent ancestor = mParent;
9080        while (ancestor instanceof ViewGroup) {
9081            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9082            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9083                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9084                return true;
9085            } else {
9086                ancestor = vgAncestor.getParent();
9087            }
9088        }
9089        return false;
9090    }
9091
9092    /**
9093     * Gets the mode for determining whether this View is important for accessibility
9094     * which is if it fires accessibility events and if it is reported to
9095     * accessibility services that query the screen.
9096     *
9097     * @return The mode for determining whether a View is important for accessibility.
9098     *
9099     * @attr ref android.R.styleable#View_importantForAccessibility
9100     *
9101     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9102     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9103     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9104     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9105     */
9106    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9107            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9108            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9109            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9110            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9111                    to = "noHideDescendants")
9112        })
9113    public int getImportantForAccessibility() {
9114        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9115                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9116    }
9117
9118    /**
9119     * Sets the live region mode for this view. This indicates to accessibility
9120     * services whether they should automatically notify the user about changes
9121     * to the view's content description or text, or to the content descriptions
9122     * or text of the view's children (where applicable).
9123     * <p>
9124     * For example, in a login screen with a TextView that displays an "incorrect
9125     * password" notification, that view should be marked as a live region with
9126     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9127     * <p>
9128     * To disable change notifications for this view, use
9129     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9130     * mode for most views.
9131     * <p>
9132     * To indicate that the user should be notified of changes, use
9133     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9134     * <p>
9135     * If the view's changes should interrupt ongoing speech and notify the user
9136     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9137     *
9138     * @param mode The live region mode for this view, one of:
9139     *        <ul>
9140     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9141     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9142     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9143     *        </ul>
9144     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9145     */
9146    public void setAccessibilityLiveRegion(int mode) {
9147        if (mode != getAccessibilityLiveRegion()) {
9148            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9149            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9150                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9151            notifyViewAccessibilityStateChangedIfNeeded(
9152                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9153        }
9154    }
9155
9156    /**
9157     * Gets the live region mode for this View.
9158     *
9159     * @return The live region mode for the view.
9160     *
9161     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9162     *
9163     * @see #setAccessibilityLiveRegion(int)
9164     */
9165    public int getAccessibilityLiveRegion() {
9166        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9167                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9168    }
9169
9170    /**
9171     * Sets how to determine whether this view is important for accessibility
9172     * which is if it fires accessibility events and if it is reported to
9173     * accessibility services that query the screen.
9174     *
9175     * @param mode How to determine whether this view is important for accessibility.
9176     *
9177     * @attr ref android.R.styleable#View_importantForAccessibility
9178     *
9179     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9180     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9181     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9182     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9183     */
9184    public void setImportantForAccessibility(int mode) {
9185        final int oldMode = getImportantForAccessibility();
9186        if (mode != oldMode) {
9187            final boolean hideDescendants =
9188                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9189
9190            // If this node or its descendants are no longer important, try to
9191            // clear accessibility focus.
9192            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9193                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9194                if (focusHost != null) {
9195                    focusHost.clearAccessibilityFocus();
9196                }
9197            }
9198
9199            // If we're moving between AUTO and another state, we might not need
9200            // to send a subtree changed notification. We'll store the computed
9201            // importance, since we'll need to check it later to make sure.
9202            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9203                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9204            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9205            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9206            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9207                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9208            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9209                notifySubtreeAccessibilityStateChangedIfNeeded();
9210            } else {
9211                notifyViewAccessibilityStateChangedIfNeeded(
9212                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9213            }
9214        }
9215    }
9216
9217    /**
9218     * Returns the view within this view's hierarchy that is hosting
9219     * accessibility focus.
9220     *
9221     * @param searchDescendants whether to search for focus in descendant views
9222     * @return the view hosting accessibility focus, or {@code null}
9223     */
9224    private View findAccessibilityFocusHost(boolean searchDescendants) {
9225        if (isAccessibilityFocusedViewOrHost()) {
9226            return this;
9227        }
9228
9229        if (searchDescendants) {
9230            final ViewRootImpl viewRoot = getViewRootImpl();
9231            if (viewRoot != null) {
9232                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9233                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9234                    return focusHost;
9235                }
9236            }
9237        }
9238
9239        return null;
9240    }
9241
9242    /**
9243     * Computes whether this view should be exposed for accessibility. In
9244     * general, views that are interactive or provide information are exposed
9245     * while views that serve only as containers are hidden.
9246     * <p>
9247     * If an ancestor of this view has importance
9248     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9249     * returns <code>false</code>.
9250     * <p>
9251     * Otherwise, the value is computed according to the view's
9252     * {@link #getImportantForAccessibility()} value:
9253     * <ol>
9254     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9255     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9256     * </code>
9257     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9258     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9259     * view satisfies any of the following:
9260     * <ul>
9261     * <li>Is actionable, e.g. {@link #isClickable()},
9262     * {@link #isLongClickable()}, or {@link #isFocusable()}
9263     * <li>Has an {@link AccessibilityDelegate}
9264     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9265     * {@link OnKeyListener}, etc.
9266     * <li>Is an accessibility live region, e.g.
9267     * {@link #getAccessibilityLiveRegion()} is not
9268     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9269     * </ul>
9270     * </ol>
9271     *
9272     * @return Whether the view is exposed for accessibility.
9273     * @see #setImportantForAccessibility(int)
9274     * @see #getImportantForAccessibility()
9275     */
9276    public boolean isImportantForAccessibility() {
9277        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9278                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9279        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9280                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9281            return false;
9282        }
9283
9284        // Check parent mode to ensure we're not hidden.
9285        ViewParent parent = mParent;
9286        while (parent instanceof View) {
9287            if (((View) parent).getImportantForAccessibility()
9288                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9289                return false;
9290            }
9291            parent = parent.getParent();
9292        }
9293
9294        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9295                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9296                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9297    }
9298
9299    /**
9300     * Gets the parent for accessibility purposes. Note that the parent for
9301     * accessibility is not necessary the immediate parent. It is the first
9302     * predecessor that is important for accessibility.
9303     *
9304     * @return The parent for accessibility purposes.
9305     */
9306    public ViewParent getParentForAccessibility() {
9307        if (mParent instanceof View) {
9308            View parentView = (View) mParent;
9309            if (parentView.includeForAccessibility()) {
9310                return mParent;
9311            } else {
9312                return mParent.getParentForAccessibility();
9313            }
9314        }
9315        return null;
9316    }
9317
9318    /**
9319     * Adds the children of this View relevant for accessibility to the given list
9320     * as output. Since some Views are not important for accessibility the added
9321     * child views are not necessarily direct children of this view, rather they are
9322     * the first level of descendants important for accessibility.
9323     *
9324     * @param outChildren The output list that will receive children for accessibility.
9325     */
9326    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9327
9328    }
9329
9330    /**
9331     * Whether to regard this view for accessibility. A view is regarded for
9332     * accessibility if it is important for accessibility or the querying
9333     * accessibility service has explicitly requested that view not
9334     * important for accessibility are regarded.
9335     *
9336     * @return Whether to regard the view for accessibility.
9337     *
9338     * @hide
9339     */
9340    public boolean includeForAccessibility() {
9341        if (mAttachInfo != null) {
9342            return (mAttachInfo.mAccessibilityFetchFlags
9343                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9344                    || isImportantForAccessibility();
9345        }
9346        return false;
9347    }
9348
9349    /**
9350     * Returns whether the View is considered actionable from
9351     * accessibility perspective. Such view are important for
9352     * accessibility.
9353     *
9354     * @return True if the view is actionable for accessibility.
9355     *
9356     * @hide
9357     */
9358    public boolean isActionableForAccessibility() {
9359        return (isClickable() || isLongClickable() || isFocusable());
9360    }
9361
9362    /**
9363     * Returns whether the View has registered callbacks which makes it
9364     * important for accessibility.
9365     *
9366     * @return True if the view is actionable for accessibility.
9367     */
9368    private boolean hasListenersForAccessibility() {
9369        ListenerInfo info = getListenerInfo();
9370        return mTouchDelegate != null || info.mOnKeyListener != null
9371                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9372                || info.mOnHoverListener != null || info.mOnDragListener != null;
9373    }
9374
9375    /**
9376     * Notifies that the accessibility state of this view changed. The change
9377     * is local to this view and does not represent structural changes such
9378     * as children and parent. For example, the view became focusable. The
9379     * notification is at at most once every
9380     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9381     * to avoid unnecessary load to the system. Also once a view has a pending
9382     * notification this method is a NOP until the notification has been sent.
9383     *
9384     * @hide
9385     */
9386    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9387        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9388            return;
9389        }
9390        if (mSendViewStateChangedAccessibilityEvent == null) {
9391            mSendViewStateChangedAccessibilityEvent =
9392                    new SendViewStateChangedAccessibilityEvent();
9393        }
9394        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9395    }
9396
9397    /**
9398     * Notifies that the accessibility state of this view changed. The change
9399     * is *not* local to this view and does represent structural changes such
9400     * as children and parent. For example, the view size changed. The
9401     * notification is at at most once every
9402     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9403     * to avoid unnecessary load to the system. Also once a view has a pending
9404     * notification this method is a NOP until the notification has been sent.
9405     *
9406     * @hide
9407     */
9408    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9409        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9410            return;
9411        }
9412        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9413            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9414            if (mParent != null) {
9415                try {
9416                    mParent.notifySubtreeAccessibilityStateChanged(
9417                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9418                } catch (AbstractMethodError e) {
9419                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9420                            " does not fully implement ViewParent", e);
9421                }
9422            }
9423        }
9424    }
9425
9426    /**
9427     * Change the visibility of the View without triggering any other changes. This is
9428     * important for transitions, where visibility changes should not adjust focus or
9429     * trigger a new layout. This is only used when the visibility has already been changed
9430     * and we need a transient value during an animation. When the animation completes,
9431     * the original visibility value is always restored.
9432     *
9433     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9434     * @hide
9435     */
9436    public void setTransitionVisibility(@Visibility int visibility) {
9437        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9438    }
9439
9440    /**
9441     * Reset the flag indicating the accessibility state of the subtree rooted
9442     * at this view changed.
9443     */
9444    void resetSubtreeAccessibilityStateChanged() {
9445        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9446    }
9447
9448    /**
9449     * Report an accessibility action to this view's parents for delegated processing.
9450     *
9451     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9452     * call this method to delegate an accessibility action to a supporting parent. If the parent
9453     * returns true from its
9454     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9455     * method this method will return true to signify that the action was consumed.</p>
9456     *
9457     * <p>This method is useful for implementing nested scrolling child views. If
9458     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9459     * a custom view implementation may invoke this method to allow a parent to consume the
9460     * scroll first. If this method returns true the custom view should skip its own scrolling
9461     * behavior.</p>
9462     *
9463     * @param action Accessibility action to delegate
9464     * @param arguments Optional action arguments
9465     * @return true if the action was consumed by a parent
9466     */
9467    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9468        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9469            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9470                return true;
9471            }
9472        }
9473        return false;
9474    }
9475
9476    /**
9477     * Performs the specified accessibility action on the view. For
9478     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9479     * <p>
9480     * If an {@link AccessibilityDelegate} has been specified via calling
9481     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9482     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9483     * is responsible for handling this call.
9484     * </p>
9485     *
9486     * <p>The default implementation will delegate
9487     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9488     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9489     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9490     *
9491     * @param action The action to perform.
9492     * @param arguments Optional action arguments.
9493     * @return Whether the action was performed.
9494     */
9495    public boolean performAccessibilityAction(int action, Bundle arguments) {
9496      if (mAccessibilityDelegate != null) {
9497          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9498      } else {
9499          return performAccessibilityActionInternal(action, arguments);
9500      }
9501    }
9502
9503   /**
9504    * @see #performAccessibilityAction(int, Bundle)
9505    *
9506    * Note: Called from the default {@link AccessibilityDelegate}.
9507    *
9508    * @hide
9509    */
9510    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9511        if (isNestedScrollingEnabled()
9512                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9513                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9514                || action == R.id.accessibilityActionScrollUp
9515                || action == R.id.accessibilityActionScrollLeft
9516                || action == R.id.accessibilityActionScrollDown
9517                || action == R.id.accessibilityActionScrollRight)) {
9518            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9519                return true;
9520            }
9521        }
9522
9523        switch (action) {
9524            case AccessibilityNodeInfo.ACTION_CLICK: {
9525                if (isClickable()) {
9526                    performClick();
9527                    return true;
9528                }
9529            } break;
9530            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9531                if (isLongClickable()) {
9532                    performLongClick();
9533                    return true;
9534                }
9535            } break;
9536            case AccessibilityNodeInfo.ACTION_FOCUS: {
9537                if (!hasFocus()) {
9538                    // Get out of touch mode since accessibility
9539                    // wants to move focus around.
9540                    getViewRootImpl().ensureTouchMode(false);
9541                    return requestFocus();
9542                }
9543            } break;
9544            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9545                if (hasFocus()) {
9546                    clearFocus();
9547                    return !isFocused();
9548                }
9549            } break;
9550            case AccessibilityNodeInfo.ACTION_SELECT: {
9551                if (!isSelected()) {
9552                    setSelected(true);
9553                    return isSelected();
9554                }
9555            } break;
9556            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9557                if (isSelected()) {
9558                    setSelected(false);
9559                    return !isSelected();
9560                }
9561            } break;
9562            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9563                if (!isAccessibilityFocused()) {
9564                    return requestAccessibilityFocus();
9565                }
9566            } break;
9567            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9568                if (isAccessibilityFocused()) {
9569                    clearAccessibilityFocus();
9570                    return true;
9571                }
9572            } break;
9573            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9574                if (arguments != null) {
9575                    final int granularity = arguments.getInt(
9576                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9577                    final boolean extendSelection = arguments.getBoolean(
9578                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9579                    return traverseAtGranularity(granularity, true, extendSelection);
9580                }
9581            } break;
9582            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9583                if (arguments != null) {
9584                    final int granularity = arguments.getInt(
9585                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9586                    final boolean extendSelection = arguments.getBoolean(
9587                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9588                    return traverseAtGranularity(granularity, false, extendSelection);
9589                }
9590            } break;
9591            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9592                CharSequence text = getIterableTextForAccessibility();
9593                if (text == null) {
9594                    return false;
9595                }
9596                final int start = (arguments != null) ? arguments.getInt(
9597                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9598                final int end = (arguments != null) ? arguments.getInt(
9599                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9600                // Only cursor position can be specified (selection length == 0)
9601                if ((getAccessibilitySelectionStart() != start
9602                        || getAccessibilitySelectionEnd() != end)
9603                        && (start == end)) {
9604                    setAccessibilitySelection(start, end);
9605                    notifyViewAccessibilityStateChangedIfNeeded(
9606                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9607                    return true;
9608                }
9609            } break;
9610            case R.id.accessibilityActionShowOnScreen: {
9611                if (mAttachInfo != null) {
9612                    final Rect r = mAttachInfo.mTmpInvalRect;
9613                    getDrawingRect(r);
9614                    return requestRectangleOnScreen(r, true);
9615                }
9616            } break;
9617            case R.id.accessibilityActionContextClick: {
9618                if (isContextClickable()) {
9619                    performContextClick();
9620                    return true;
9621                }
9622            } break;
9623        }
9624        return false;
9625    }
9626
9627    private boolean traverseAtGranularity(int granularity, boolean forward,
9628            boolean extendSelection) {
9629        CharSequence text = getIterableTextForAccessibility();
9630        if (text == null || text.length() == 0) {
9631            return false;
9632        }
9633        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9634        if (iterator == null) {
9635            return false;
9636        }
9637        int current = getAccessibilitySelectionEnd();
9638        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9639            current = forward ? 0 : text.length();
9640        }
9641        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9642        if (range == null) {
9643            return false;
9644        }
9645        final int segmentStart = range[0];
9646        final int segmentEnd = range[1];
9647        int selectionStart;
9648        int selectionEnd;
9649        if (extendSelection && isAccessibilitySelectionExtendable()) {
9650            selectionStart = getAccessibilitySelectionStart();
9651            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9652                selectionStart = forward ? segmentStart : segmentEnd;
9653            }
9654            selectionEnd = forward ? segmentEnd : segmentStart;
9655        } else {
9656            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9657        }
9658        setAccessibilitySelection(selectionStart, selectionEnd);
9659        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9660                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9661        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9662        return true;
9663    }
9664
9665    /**
9666     * Gets the text reported for accessibility purposes.
9667     *
9668     * @return The accessibility text.
9669     *
9670     * @hide
9671     */
9672    public CharSequence getIterableTextForAccessibility() {
9673        return getContentDescription();
9674    }
9675
9676    /**
9677     * Gets whether accessibility selection can be extended.
9678     *
9679     * @return If selection is extensible.
9680     *
9681     * @hide
9682     */
9683    public boolean isAccessibilitySelectionExtendable() {
9684        return false;
9685    }
9686
9687    /**
9688     * @hide
9689     */
9690    public int getAccessibilitySelectionStart() {
9691        return mAccessibilityCursorPosition;
9692    }
9693
9694    /**
9695     * @hide
9696     */
9697    public int getAccessibilitySelectionEnd() {
9698        return getAccessibilitySelectionStart();
9699    }
9700
9701    /**
9702     * @hide
9703     */
9704    public void setAccessibilitySelection(int start, int end) {
9705        if (start ==  end && end == mAccessibilityCursorPosition) {
9706            return;
9707        }
9708        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9709            mAccessibilityCursorPosition = start;
9710        } else {
9711            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9712        }
9713        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9714    }
9715
9716    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9717            int fromIndex, int toIndex) {
9718        if (mParent == null) {
9719            return;
9720        }
9721        AccessibilityEvent event = AccessibilityEvent.obtain(
9722                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9723        onInitializeAccessibilityEvent(event);
9724        onPopulateAccessibilityEvent(event);
9725        event.setFromIndex(fromIndex);
9726        event.setToIndex(toIndex);
9727        event.setAction(action);
9728        event.setMovementGranularity(granularity);
9729        mParent.requestSendAccessibilityEvent(this, event);
9730    }
9731
9732    /**
9733     * @hide
9734     */
9735    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9736        switch (granularity) {
9737            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9738                CharSequence text = getIterableTextForAccessibility();
9739                if (text != null && text.length() > 0) {
9740                    CharacterTextSegmentIterator iterator =
9741                        CharacterTextSegmentIterator.getInstance(
9742                                mContext.getResources().getConfiguration().locale);
9743                    iterator.initialize(text.toString());
9744                    return iterator;
9745                }
9746            } break;
9747            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9748                CharSequence text = getIterableTextForAccessibility();
9749                if (text != null && text.length() > 0) {
9750                    WordTextSegmentIterator iterator =
9751                        WordTextSegmentIterator.getInstance(
9752                                mContext.getResources().getConfiguration().locale);
9753                    iterator.initialize(text.toString());
9754                    return iterator;
9755                }
9756            } break;
9757            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9758                CharSequence text = getIterableTextForAccessibility();
9759                if (text != null && text.length() > 0) {
9760                    ParagraphTextSegmentIterator iterator =
9761                        ParagraphTextSegmentIterator.getInstance();
9762                    iterator.initialize(text.toString());
9763                    return iterator;
9764                }
9765            } break;
9766        }
9767        return null;
9768    }
9769
9770    /**
9771     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9772     * and {@link #onFinishTemporaryDetach()}.
9773     */
9774    public final boolean isTemporarilyDetached() {
9775        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9776    }
9777
9778    /**
9779     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9780     * a container View.
9781     */
9782    @CallSuper
9783    public void dispatchStartTemporaryDetach() {
9784        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9785        onStartTemporaryDetach();
9786    }
9787
9788    /**
9789     * This is called when a container is going to temporarily detach a child, with
9790     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9791     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9792     * {@link #onDetachedFromWindow()} when the container is done.
9793     */
9794    public void onStartTemporaryDetach() {
9795        removeUnsetPressCallback();
9796        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9797    }
9798
9799    /**
9800     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9801     * a container View.
9802     */
9803    @CallSuper
9804    public void dispatchFinishTemporaryDetach() {
9805        onFinishTemporaryDetach();
9806        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9807    }
9808
9809    /**
9810     * Called after {@link #onStartTemporaryDetach} when the container is done
9811     * changing the view.
9812     */
9813    public void onFinishTemporaryDetach() {
9814    }
9815
9816    /**
9817     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9818     * for this view's window.  Returns null if the view is not currently attached
9819     * to the window.  Normally you will not need to use this directly, but
9820     * just use the standard high-level event callbacks like
9821     * {@link #onKeyDown(int, KeyEvent)}.
9822     */
9823    public KeyEvent.DispatcherState getKeyDispatcherState() {
9824        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9825    }
9826
9827    /**
9828     * Dispatch a key event before it is processed by any input method
9829     * associated with the view hierarchy.  This can be used to intercept
9830     * key events in special situations before the IME consumes them; a
9831     * typical example would be handling the BACK key to update the application's
9832     * UI instead of allowing the IME to see it and close itself.
9833     *
9834     * @param event The key event to be dispatched.
9835     * @return True if the event was handled, false otherwise.
9836     */
9837    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9838        return onKeyPreIme(event.getKeyCode(), event);
9839    }
9840
9841    /**
9842     * Dispatch a key event to the next view on the focus path. This path runs
9843     * from the top of the view tree down to the currently focused view. If this
9844     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9845     * the next node down the focus path. This method also fires any key
9846     * listeners.
9847     *
9848     * @param event The key event to be dispatched.
9849     * @return True if the event was handled, false otherwise.
9850     */
9851    public boolean dispatchKeyEvent(KeyEvent event) {
9852        if (mInputEventConsistencyVerifier != null) {
9853            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9854        }
9855
9856        // Give any attached key listener a first crack at the event.
9857        //noinspection SimplifiableIfStatement
9858        ListenerInfo li = mListenerInfo;
9859        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9860                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9861            return true;
9862        }
9863
9864        if (event.dispatch(this, mAttachInfo != null
9865                ? mAttachInfo.mKeyDispatchState : null, this)) {
9866            return true;
9867        }
9868
9869        if (mInputEventConsistencyVerifier != null) {
9870            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9871        }
9872        return false;
9873    }
9874
9875    /**
9876     * Dispatches a key shortcut event.
9877     *
9878     * @param event The key event to be dispatched.
9879     * @return True if the event was handled by the view, false otherwise.
9880     */
9881    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9882        return onKeyShortcut(event.getKeyCode(), event);
9883    }
9884
9885    /**
9886     * Pass the touch screen motion event down to the target view, or this
9887     * view if it is the target.
9888     *
9889     * @param event The motion event to be dispatched.
9890     * @return True if the event was handled by the view, false otherwise.
9891     */
9892    public boolean dispatchTouchEvent(MotionEvent event) {
9893        // If the event should be handled by accessibility focus first.
9894        if (event.isTargetAccessibilityFocus()) {
9895            // We don't have focus or no virtual descendant has it, do not handle the event.
9896            if (!isAccessibilityFocusedViewOrHost()) {
9897                return false;
9898            }
9899            // We have focus and got the event, then use normal event dispatch.
9900            event.setTargetAccessibilityFocus(false);
9901        }
9902
9903        boolean result = false;
9904
9905        if (mInputEventConsistencyVerifier != null) {
9906            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9907        }
9908
9909        final int actionMasked = event.getActionMasked();
9910        if (actionMasked == MotionEvent.ACTION_DOWN) {
9911            // Defensive cleanup for new gesture
9912            stopNestedScroll();
9913        }
9914
9915        if (onFilterTouchEventForSecurity(event)) {
9916            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
9917                result = true;
9918            }
9919            //noinspection SimplifiableIfStatement
9920            ListenerInfo li = mListenerInfo;
9921            if (li != null && li.mOnTouchListener != null
9922                    && (mViewFlags & ENABLED_MASK) == ENABLED
9923                    && li.mOnTouchListener.onTouch(this, event)) {
9924                result = true;
9925            }
9926
9927            if (!result && onTouchEvent(event)) {
9928                result = true;
9929            }
9930        }
9931
9932        if (!result && mInputEventConsistencyVerifier != null) {
9933            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9934        }
9935
9936        // Clean up after nested scrolls if this is the end of a gesture;
9937        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9938        // of the gesture.
9939        if (actionMasked == MotionEvent.ACTION_UP ||
9940                actionMasked == MotionEvent.ACTION_CANCEL ||
9941                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9942            stopNestedScroll();
9943        }
9944
9945        return result;
9946    }
9947
9948    boolean isAccessibilityFocusedViewOrHost() {
9949        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9950                .getAccessibilityFocusedHost() == this);
9951    }
9952
9953    /**
9954     * Filter the touch event to apply security policies.
9955     *
9956     * @param event The motion event to be filtered.
9957     * @return True if the event should be dispatched, false if the event should be dropped.
9958     *
9959     * @see #getFilterTouchesWhenObscured
9960     */
9961    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9962        //noinspection RedundantIfStatement
9963        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9964                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9965            // Window is obscured, drop this touch.
9966            return false;
9967        }
9968        return true;
9969    }
9970
9971    /**
9972     * Pass a trackball motion event down to the focused view.
9973     *
9974     * @param event The motion event to be dispatched.
9975     * @return True if the event was handled by the view, false otherwise.
9976     */
9977    public boolean dispatchTrackballEvent(MotionEvent event) {
9978        if (mInputEventConsistencyVerifier != null) {
9979            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9980        }
9981
9982        return onTrackballEvent(event);
9983    }
9984
9985    /**
9986     * Dispatch a generic motion event.
9987     * <p>
9988     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9989     * are delivered to the view under the pointer.  All other generic motion events are
9990     * delivered to the focused view.  Hover events are handled specially and are delivered
9991     * to {@link #onHoverEvent(MotionEvent)}.
9992     * </p>
9993     *
9994     * @param event The motion event to be dispatched.
9995     * @return True if the event was handled by the view, false otherwise.
9996     */
9997    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9998        if (mInputEventConsistencyVerifier != null) {
9999            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10000        }
10001
10002        final int source = event.getSource();
10003        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10004            final int action = event.getAction();
10005            if (action == MotionEvent.ACTION_HOVER_ENTER
10006                    || action == MotionEvent.ACTION_HOVER_MOVE
10007                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10008                if (dispatchHoverEvent(event)) {
10009                    return true;
10010                }
10011            } else if (dispatchGenericPointerEvent(event)) {
10012                return true;
10013            }
10014        } else if (dispatchGenericFocusedEvent(event)) {
10015            return true;
10016        }
10017
10018        if (dispatchGenericMotionEventInternal(event)) {
10019            return true;
10020        }
10021
10022        if (mInputEventConsistencyVerifier != null) {
10023            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10024        }
10025        return false;
10026    }
10027
10028    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10029        //noinspection SimplifiableIfStatement
10030        ListenerInfo li = mListenerInfo;
10031        if (li != null && li.mOnGenericMotionListener != null
10032                && (mViewFlags & ENABLED_MASK) == ENABLED
10033                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10034            return true;
10035        }
10036
10037        if (onGenericMotionEvent(event)) {
10038            return true;
10039        }
10040
10041        final int actionButton = event.getActionButton();
10042        switch (event.getActionMasked()) {
10043            case MotionEvent.ACTION_BUTTON_PRESS:
10044                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10045                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10046                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10047                    if (performContextClick()) {
10048                        mInContextButtonPress = true;
10049                        setPressed(true, event.getX(), event.getY());
10050                        removeTapCallback();
10051                        removeLongPressCallback();
10052                        return true;
10053                    }
10054                }
10055                break;
10056
10057            case MotionEvent.ACTION_BUTTON_RELEASE:
10058                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10059                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10060                    mInContextButtonPress = false;
10061                    mIgnoreNextUpEvent = true;
10062                }
10063                break;
10064        }
10065
10066        if (mInputEventConsistencyVerifier != null) {
10067            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10068        }
10069        return false;
10070    }
10071
10072    /**
10073     * Dispatch a hover event.
10074     * <p>
10075     * Do not call this method directly.
10076     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10077     * </p>
10078     *
10079     * @param event The motion event to be dispatched.
10080     * @return True if the event was handled by the view, false otherwise.
10081     */
10082    protected boolean dispatchHoverEvent(MotionEvent event) {
10083        ListenerInfo li = mListenerInfo;
10084        //noinspection SimplifiableIfStatement
10085        if (li != null && li.mOnHoverListener != null
10086                && (mViewFlags & ENABLED_MASK) == ENABLED
10087                && li.mOnHoverListener.onHover(this, event)) {
10088            return true;
10089        }
10090
10091        return onHoverEvent(event);
10092    }
10093
10094    /**
10095     * Returns true if the view has a child to which it has recently sent
10096     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10097     * it does not have a hovered child, then it must be the innermost hovered view.
10098     * @hide
10099     */
10100    protected boolean hasHoveredChild() {
10101        return false;
10102    }
10103
10104    /**
10105     * Dispatch a generic motion event to the view under the first pointer.
10106     * <p>
10107     * Do not call this method directly.
10108     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10109     * </p>
10110     *
10111     * @param event The motion event to be dispatched.
10112     * @return True if the event was handled by the view, false otherwise.
10113     */
10114    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10115        return false;
10116    }
10117
10118    /**
10119     * Dispatch a generic motion event to the currently focused view.
10120     * <p>
10121     * Do not call this method directly.
10122     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10123     * </p>
10124     *
10125     * @param event The motion event to be dispatched.
10126     * @return True if the event was handled by the view, false otherwise.
10127     */
10128    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10129        return false;
10130    }
10131
10132    /**
10133     * Dispatch a pointer event.
10134     * <p>
10135     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10136     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10137     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10138     * and should not be expected to handle other pointing device features.
10139     * </p>
10140     *
10141     * @param event The motion event to be dispatched.
10142     * @return True if the event was handled by the view, false otherwise.
10143     * @hide
10144     */
10145    public final boolean dispatchPointerEvent(MotionEvent event) {
10146        if (event.isTouchEvent()) {
10147            return dispatchTouchEvent(event);
10148        } else {
10149            return dispatchGenericMotionEvent(event);
10150        }
10151    }
10152
10153    /**
10154     * Called when the window containing this view gains or loses window focus.
10155     * ViewGroups should override to route to their children.
10156     *
10157     * @param hasFocus True if the window containing this view now has focus,
10158     *        false otherwise.
10159     */
10160    public void dispatchWindowFocusChanged(boolean hasFocus) {
10161        onWindowFocusChanged(hasFocus);
10162    }
10163
10164    /**
10165     * Called when the window containing this view gains or loses focus.  Note
10166     * that this is separate from view focus: to receive key events, both
10167     * your view and its window must have focus.  If a window is displayed
10168     * on top of yours that takes input focus, then your own window will lose
10169     * focus but the view focus will remain unchanged.
10170     *
10171     * @param hasWindowFocus True if the window containing this view now has
10172     *        focus, false otherwise.
10173     */
10174    public void onWindowFocusChanged(boolean hasWindowFocus) {
10175        InputMethodManager imm = InputMethodManager.peekInstance();
10176        if (!hasWindowFocus) {
10177            if (isPressed()) {
10178                setPressed(false);
10179            }
10180            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10181                imm.focusOut(this);
10182            }
10183            removeLongPressCallback();
10184            removeTapCallback();
10185            onFocusLost();
10186        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10187            imm.focusIn(this);
10188        }
10189        refreshDrawableState();
10190    }
10191
10192    /**
10193     * Returns true if this view is in a window that currently has window focus.
10194     * Note that this is not the same as the view itself having focus.
10195     *
10196     * @return True if this view is in a window that currently has window focus.
10197     */
10198    public boolean hasWindowFocus() {
10199        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10200    }
10201
10202    /**
10203     * Dispatch a view visibility change down the view hierarchy.
10204     * ViewGroups should override to route to their children.
10205     * @param changedView The view whose visibility changed. Could be 'this' or
10206     * an ancestor view.
10207     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10208     * {@link #INVISIBLE} or {@link #GONE}.
10209     */
10210    protected void dispatchVisibilityChanged(@NonNull View changedView,
10211            @Visibility int visibility) {
10212        onVisibilityChanged(changedView, visibility);
10213    }
10214
10215    /**
10216     * Called when the visibility of the view or an ancestor of the view has
10217     * changed.
10218     *
10219     * @param changedView The view whose visibility changed. May be
10220     *                    {@code this} or an ancestor view.
10221     * @param visibility The new visibility, one of {@link #VISIBLE},
10222     *                   {@link #INVISIBLE} or {@link #GONE}.
10223     */
10224    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10225    }
10226
10227    /**
10228     * Dispatch a hint about whether this view is displayed. For instance, when
10229     * a View moves out of the screen, it might receives a display hint indicating
10230     * the view is not displayed. Applications should not <em>rely</em> on this hint
10231     * as there is no guarantee that they will receive one.
10232     *
10233     * @param hint A hint about whether or not this view is displayed:
10234     * {@link #VISIBLE} or {@link #INVISIBLE}.
10235     */
10236    public void dispatchDisplayHint(@Visibility int hint) {
10237        onDisplayHint(hint);
10238    }
10239
10240    /**
10241     * Gives this view a hint about whether is displayed or not. For instance, when
10242     * a View moves out of the screen, it might receives a display hint indicating
10243     * the view is not displayed. Applications should not <em>rely</em> on this hint
10244     * as there is no guarantee that they will receive one.
10245     *
10246     * @param hint A hint about whether or not this view is displayed:
10247     * {@link #VISIBLE} or {@link #INVISIBLE}.
10248     */
10249    protected void onDisplayHint(@Visibility int hint) {
10250    }
10251
10252    /**
10253     * Dispatch a window visibility change down the view hierarchy.
10254     * ViewGroups should override to route to their children.
10255     *
10256     * @param visibility The new visibility of the window.
10257     *
10258     * @see #onWindowVisibilityChanged(int)
10259     */
10260    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10261        onWindowVisibilityChanged(visibility);
10262    }
10263
10264    /**
10265     * Called when the window containing has change its visibility
10266     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10267     * that this tells you whether or not your window is being made visible
10268     * to the window manager; this does <em>not</em> tell you whether or not
10269     * your window is obscured by other windows on the screen, even if it
10270     * is itself visible.
10271     *
10272     * @param visibility The new visibility of the window.
10273     */
10274    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10275        if (visibility == VISIBLE) {
10276            initialAwakenScrollBars();
10277        }
10278    }
10279
10280    /**
10281     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10282     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10283     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10284     *
10285     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10286     *                  ancestors or by window visibility
10287     * @return true if this view is visible to the user, not counting clipping or overlapping
10288     */
10289    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10290        final boolean thisVisible = getVisibility() == VISIBLE;
10291        // If we're not visible but something is telling us we are, ignore it.
10292        if (thisVisible || !isVisible) {
10293            onVisibilityAggregated(isVisible);
10294        }
10295        return thisVisible && isVisible;
10296    }
10297
10298    /**
10299     * Called when the user-visibility of this View is potentially affected by a change
10300     * to this view itself, an ancestor view or the window this view is attached to.
10301     *
10302     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10303     *                  and this view's window is also visible
10304     */
10305    @CallSuper
10306    public void onVisibilityAggregated(boolean isVisible) {
10307        if (isVisible && mAttachInfo != null) {
10308            initialAwakenScrollBars();
10309        }
10310
10311        final Drawable dr = mBackground;
10312        if (dr != null && isVisible != dr.isVisible()) {
10313            dr.setVisible(isVisible, false);
10314        }
10315        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10316        if (fg != null && isVisible != fg.isVisible()) {
10317            fg.setVisible(isVisible, false);
10318        }
10319    }
10320
10321    /**
10322     * Returns the current visibility of the window this view is attached to
10323     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10324     *
10325     * @return Returns the current visibility of the view's window.
10326     */
10327    @Visibility
10328    public int getWindowVisibility() {
10329        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10330    }
10331
10332    /**
10333     * Retrieve the overall visible display size in which the window this view is
10334     * attached to has been positioned in.  This takes into account screen
10335     * decorations above the window, for both cases where the window itself
10336     * is being position inside of them or the window is being placed under
10337     * then and covered insets are used for the window to position its content
10338     * inside.  In effect, this tells you the available area where content can
10339     * be placed and remain visible to users.
10340     *
10341     * <p>This function requires an IPC back to the window manager to retrieve
10342     * the requested information, so should not be used in performance critical
10343     * code like drawing.
10344     *
10345     * @param outRect Filled in with the visible display frame.  If the view
10346     * is not attached to a window, this is simply the raw display size.
10347     */
10348    public void getWindowVisibleDisplayFrame(Rect outRect) {
10349        if (mAttachInfo != null) {
10350            try {
10351                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10352            } catch (RemoteException e) {
10353                return;
10354            }
10355            // XXX This is really broken, and probably all needs to be done
10356            // in the window manager, and we need to know more about whether
10357            // we want the area behind or in front of the IME.
10358            final Rect insets = mAttachInfo.mVisibleInsets;
10359            outRect.left += insets.left;
10360            outRect.top += insets.top;
10361            outRect.right -= insets.right;
10362            outRect.bottom -= insets.bottom;
10363            return;
10364        }
10365        // The view is not attached to a display so we don't have a context.
10366        // Make a best guess about the display size.
10367        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10368        d.getRectSize(outRect);
10369    }
10370
10371    /**
10372     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10373     * is currently in without any insets.
10374     *
10375     * @hide
10376     */
10377    public void getWindowDisplayFrame(Rect outRect) {
10378        if (mAttachInfo != null) {
10379            try {
10380                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10381            } catch (RemoteException e) {
10382                return;
10383            }
10384            return;
10385        }
10386        // The view is not attached to a display so we don't have a context.
10387        // Make a best guess about the display size.
10388        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10389        d.getRectSize(outRect);
10390    }
10391
10392    /**
10393     * Dispatch a notification about a resource configuration change down
10394     * the view hierarchy.
10395     * ViewGroups should override to route to their children.
10396     *
10397     * @param newConfig The new resource configuration.
10398     *
10399     * @see #onConfigurationChanged(android.content.res.Configuration)
10400     */
10401    public void dispatchConfigurationChanged(Configuration newConfig) {
10402        onConfigurationChanged(newConfig);
10403    }
10404
10405    /**
10406     * Called when the current configuration of the resources being used
10407     * by the application have changed.  You can use this to decide when
10408     * to reload resources that can changed based on orientation and other
10409     * configuration characteristics.  You only need to use this if you are
10410     * not relying on the normal {@link android.app.Activity} mechanism of
10411     * recreating the activity instance upon a configuration change.
10412     *
10413     * @param newConfig The new resource configuration.
10414     */
10415    protected void onConfigurationChanged(Configuration newConfig) {
10416    }
10417
10418    /**
10419     * Private function to aggregate all per-view attributes in to the view
10420     * root.
10421     */
10422    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10423        performCollectViewAttributes(attachInfo, visibility);
10424    }
10425
10426    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10427        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10428            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10429                attachInfo.mKeepScreenOn = true;
10430            }
10431            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10432            ListenerInfo li = mListenerInfo;
10433            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10434                attachInfo.mHasSystemUiListeners = true;
10435            }
10436        }
10437    }
10438
10439    void needGlobalAttributesUpdate(boolean force) {
10440        final AttachInfo ai = mAttachInfo;
10441        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10442            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10443                    || ai.mHasSystemUiListeners) {
10444                ai.mRecomputeGlobalAttributes = true;
10445            }
10446        }
10447    }
10448
10449    /**
10450     * Returns whether the device is currently in touch mode.  Touch mode is entered
10451     * once the user begins interacting with the device by touch, and affects various
10452     * things like whether focus is always visible to the user.
10453     *
10454     * @return Whether the device is in touch mode.
10455     */
10456    @ViewDebug.ExportedProperty
10457    public boolean isInTouchMode() {
10458        if (mAttachInfo != null) {
10459            return mAttachInfo.mInTouchMode;
10460        } else {
10461            return ViewRootImpl.isInTouchMode();
10462        }
10463    }
10464
10465    /**
10466     * Returns the context the view is running in, through which it can
10467     * access the current theme, resources, etc.
10468     *
10469     * @return The view's Context.
10470     */
10471    @ViewDebug.CapturedViewProperty
10472    public final Context getContext() {
10473        return mContext;
10474    }
10475
10476    /**
10477     * Handle a key event before it is processed by any input method
10478     * associated with the view hierarchy.  This can be used to intercept
10479     * key events in special situations before the IME consumes them; a
10480     * typical example would be handling the BACK key to update the application's
10481     * UI instead of allowing the IME to see it and close itself.
10482     *
10483     * @param keyCode The value in event.getKeyCode().
10484     * @param event Description of the key event.
10485     * @return If you handled the event, return true. If you want to allow the
10486     *         event to be handled by the next receiver, return false.
10487     */
10488    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10489        return false;
10490    }
10491
10492    /**
10493     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10494     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10495     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10496     * is released, if the view is enabled and clickable.
10497     * <p>
10498     * Key presses in software keyboards will generally NOT trigger this
10499     * listener, although some may elect to do so in some situations. Do not
10500     * rely on this to 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 onKeyDown(int keyCode, KeyEvent event) {
10507        if (KeyEvent.isConfirmKey(keyCode)) {
10508            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10509                return true;
10510            }
10511
10512            // Long clickable items don't necessarily have to be clickable.
10513            if (((mViewFlags & CLICKABLE) == CLICKABLE
10514                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10515                    && (event.getRepeatCount() == 0)) {
10516                // For the purposes of menu anchoring and drawable hotspots,
10517                // key events are considered to be at the center of the view.
10518                final float x = getWidth() / 2f;
10519                final float y = getHeight() / 2f;
10520                setPressed(true, x, y);
10521                checkForLongClick(0, x, y);
10522                return true;
10523            }
10524        }
10525
10526        return false;
10527    }
10528
10529    /**
10530     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10531     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10532     * the event).
10533     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10534     * although some may elect to do so in some situations. Do not rely on this to
10535     * catch software key presses.
10536     */
10537    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10538        return false;
10539    }
10540
10541    /**
10542     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10543     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10544     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10545     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10546     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10547     * although some may elect to do so in some situations. Do not rely on this to
10548     * catch software key presses.
10549     *
10550     * @param keyCode A key code that represents the button pressed, from
10551     *                {@link android.view.KeyEvent}.
10552     * @param event   The KeyEvent object that defines the button action.
10553     */
10554    public boolean onKeyUp(int keyCode, KeyEvent event) {
10555        if (KeyEvent.isConfirmKey(keyCode)) {
10556            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10557                return true;
10558            }
10559            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10560                setPressed(false);
10561
10562                if (!mHasPerformedLongPress) {
10563                    // This is a tap, so remove the longpress check
10564                    removeLongPressCallback();
10565                    return performClick();
10566                }
10567            }
10568        }
10569        return false;
10570    }
10571
10572    /**
10573     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10574     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10575     * the event).
10576     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10577     * although some may elect to do so in some situations. Do not rely on this to
10578     * catch software key presses.
10579     *
10580     * @param keyCode     A key code that represents the button pressed, from
10581     *                    {@link android.view.KeyEvent}.
10582     * @param repeatCount The number of times the action was made.
10583     * @param event       The KeyEvent object that defines the button action.
10584     */
10585    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10586        return false;
10587    }
10588
10589    /**
10590     * Called on the focused view when a key shortcut event is not handled.
10591     * Override this method to implement local key shortcuts for the View.
10592     * Key shortcuts can also be implemented by setting the
10593     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10594     *
10595     * @param keyCode The value in event.getKeyCode().
10596     * @param event Description of the key event.
10597     * @return If you handled the event, return true. If you want to allow the
10598     *         event to be handled by the next receiver, return false.
10599     */
10600    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10601        return false;
10602    }
10603
10604    /**
10605     * Check whether the called view is a text editor, in which case it
10606     * would make sense to automatically display a soft input window for
10607     * it.  Subclasses should override this if they implement
10608     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10609     * a call on that method would return a non-null InputConnection, and
10610     * they are really a first-class editor that the user would normally
10611     * start typing on when the go into a window containing your view.
10612     *
10613     * <p>The default implementation always returns false.  This does
10614     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10615     * will not be called or the user can not otherwise perform edits on your
10616     * view; it is just a hint to the system that this is not the primary
10617     * purpose of this view.
10618     *
10619     * @return Returns true if this view is a text editor, else false.
10620     */
10621    public boolean onCheckIsTextEditor() {
10622        return false;
10623    }
10624
10625    /**
10626     * Create a new InputConnection for an InputMethod to interact
10627     * with the view.  The default implementation returns null, since it doesn't
10628     * support input methods.  You can override this to implement such support.
10629     * This is only needed for views that take focus and text input.
10630     *
10631     * <p>When implementing this, you probably also want to implement
10632     * {@link #onCheckIsTextEditor()} to indicate you will return a
10633     * non-null InputConnection.</p>
10634     *
10635     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10636     * object correctly and in its entirety, so that the connected IME can rely
10637     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10638     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10639     * must be filled in with the correct cursor position for IMEs to work correctly
10640     * with your application.</p>
10641     *
10642     * @param outAttrs Fill in with attribute information about the connection.
10643     */
10644    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10645        return null;
10646    }
10647
10648    /**
10649     * Called by the {@link android.view.inputmethod.InputMethodManager}
10650     * when a view who is not the current
10651     * input connection target is trying to make a call on the manager.  The
10652     * default implementation returns false; you can override this to return
10653     * true for certain views if you are performing InputConnection proxying
10654     * to them.
10655     * @param view The View that is making the InputMethodManager call.
10656     * @return Return true to allow the call, false to reject.
10657     */
10658    public boolean checkInputConnectionProxy(View view) {
10659        return false;
10660    }
10661
10662    /**
10663     * Show the context menu for this view. It is not safe to hold on to the
10664     * menu after returning from this method.
10665     *
10666     * You should normally not overload this method. Overload
10667     * {@link #onCreateContextMenu(ContextMenu)} or define an
10668     * {@link OnCreateContextMenuListener} to add items to the context menu.
10669     *
10670     * @param menu The context menu to populate
10671     */
10672    public void createContextMenu(ContextMenu menu) {
10673        ContextMenuInfo menuInfo = getContextMenuInfo();
10674
10675        // Sets the current menu info so all items added to menu will have
10676        // my extra info set.
10677        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10678
10679        onCreateContextMenu(menu);
10680        ListenerInfo li = mListenerInfo;
10681        if (li != null && li.mOnCreateContextMenuListener != null) {
10682            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10683        }
10684
10685        // Clear the extra information so subsequent items that aren't mine don't
10686        // have my extra info.
10687        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10688
10689        if (mParent != null) {
10690            mParent.createContextMenu(menu);
10691        }
10692    }
10693
10694    /**
10695     * Views should implement this if they have extra information to associate
10696     * with the context menu. The return result is supplied as a parameter to
10697     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10698     * callback.
10699     *
10700     * @return Extra information about the item for which the context menu
10701     *         should be shown. This information will vary across different
10702     *         subclasses of View.
10703     */
10704    protected ContextMenuInfo getContextMenuInfo() {
10705        return null;
10706    }
10707
10708    /**
10709     * Views should implement this if the view itself is going to add items to
10710     * the context menu.
10711     *
10712     * @param menu the context menu to populate
10713     */
10714    protected void onCreateContextMenu(ContextMenu menu) {
10715    }
10716
10717    /**
10718     * Implement this method to handle trackball motion events.  The
10719     * <em>relative</em> movement of the trackball since the last event
10720     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10721     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10722     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10723     * they will often be fractional values, representing the more fine-grained
10724     * movement information available from a trackball).
10725     *
10726     * @param event The motion event.
10727     * @return True if the event was handled, false otherwise.
10728     */
10729    public boolean onTrackballEvent(MotionEvent event) {
10730        return false;
10731    }
10732
10733    /**
10734     * Implement this method to handle generic motion events.
10735     * <p>
10736     * Generic motion events describe joystick movements, mouse hovers, track pad
10737     * touches, scroll wheel movements and other input events.  The
10738     * {@link MotionEvent#getSource() source} of the motion event specifies
10739     * the class of input that was received.  Implementations of this method
10740     * must examine the bits in the source before processing the event.
10741     * The following code example shows how this is done.
10742     * </p><p>
10743     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10744     * are delivered to the view under the pointer.  All other generic motion events are
10745     * delivered to the focused view.
10746     * </p>
10747     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10748     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10749     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10750     *             // process the joystick movement...
10751     *             return true;
10752     *         }
10753     *     }
10754     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10755     *         switch (event.getAction()) {
10756     *             case MotionEvent.ACTION_HOVER_MOVE:
10757     *                 // process the mouse hover movement...
10758     *                 return true;
10759     *             case MotionEvent.ACTION_SCROLL:
10760     *                 // process the scroll wheel movement...
10761     *                 return true;
10762     *         }
10763     *     }
10764     *     return super.onGenericMotionEvent(event);
10765     * }</pre>
10766     *
10767     * @param event The generic motion event being processed.
10768     * @return True if the event was handled, false otherwise.
10769     */
10770    public boolean onGenericMotionEvent(MotionEvent event) {
10771        return false;
10772    }
10773
10774    /**
10775     * Implement this method to handle hover events.
10776     * <p>
10777     * This method is called whenever a pointer is hovering into, over, or out of the
10778     * bounds of a view and the view is not currently being touched.
10779     * Hover events are represented as pointer events with action
10780     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10781     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10782     * </p>
10783     * <ul>
10784     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10785     * when the pointer enters the bounds of the view.</li>
10786     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10787     * when the pointer has already entered the bounds of the view and has moved.</li>
10788     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10789     * when the pointer has exited the bounds of the view or when the pointer is
10790     * about to go down due to a button click, tap, or similar user action that
10791     * causes the view to be touched.</li>
10792     * </ul>
10793     * <p>
10794     * The view should implement this method to return true to indicate that it is
10795     * handling the hover event, such as by changing its drawable state.
10796     * </p><p>
10797     * The default implementation calls {@link #setHovered} to update the hovered state
10798     * of the view when a hover enter or hover exit event is received, if the view
10799     * is enabled and is clickable.  The default implementation also sends hover
10800     * accessibility events.
10801     * </p>
10802     *
10803     * @param event The motion event that describes the hover.
10804     * @return True if the view handled the hover event.
10805     *
10806     * @see #isHovered
10807     * @see #setHovered
10808     * @see #onHoverChanged
10809     */
10810    public boolean onHoverEvent(MotionEvent event) {
10811        // The root view may receive hover (or touch) events that are outside the bounds of
10812        // the window.  This code ensures that we only send accessibility events for
10813        // hovers that are actually within the bounds of the root view.
10814        final int action = event.getActionMasked();
10815        if (!mSendingHoverAccessibilityEvents) {
10816            if ((action == MotionEvent.ACTION_HOVER_ENTER
10817                    || action == MotionEvent.ACTION_HOVER_MOVE)
10818                    && !hasHoveredChild()
10819                    && pointInView(event.getX(), event.getY())) {
10820                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10821                mSendingHoverAccessibilityEvents = true;
10822            }
10823        } else {
10824            if (action == MotionEvent.ACTION_HOVER_EXIT
10825                    || (action == MotionEvent.ACTION_MOVE
10826                            && !pointInView(event.getX(), event.getY()))) {
10827                mSendingHoverAccessibilityEvents = false;
10828                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10829            }
10830        }
10831
10832        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10833                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10834                && isOnScrollbar(event.getX(), event.getY())) {
10835            awakenScrollBars();
10836        }
10837        if (isHoverable()) {
10838            switch (action) {
10839                case MotionEvent.ACTION_HOVER_ENTER:
10840                    setHovered(true);
10841                    break;
10842                case MotionEvent.ACTION_HOVER_EXIT:
10843                    setHovered(false);
10844                    break;
10845            }
10846
10847            // Dispatch the event to onGenericMotionEvent before returning true.
10848            // This is to provide compatibility with existing applications that
10849            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10850            // break because of the new default handling for hoverable views
10851            // in onHoverEvent.
10852            // Note that onGenericMotionEvent will be called by default when
10853            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10854            dispatchGenericMotionEventInternal(event);
10855            // The event was already handled by calling setHovered(), so always
10856            // return true.
10857            return true;
10858        }
10859
10860        return false;
10861    }
10862
10863    /**
10864     * Returns true if the view should handle {@link #onHoverEvent}
10865     * by calling {@link #setHovered} to change its hovered state.
10866     *
10867     * @return True if the view is hoverable.
10868     */
10869    private boolean isHoverable() {
10870        final int viewFlags = mViewFlags;
10871        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10872            return false;
10873        }
10874
10875        return (viewFlags & CLICKABLE) == CLICKABLE
10876                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10877                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10878    }
10879
10880    /**
10881     * Returns true if the view is currently hovered.
10882     *
10883     * @return True if the view is currently hovered.
10884     *
10885     * @see #setHovered
10886     * @see #onHoverChanged
10887     */
10888    @ViewDebug.ExportedProperty
10889    public boolean isHovered() {
10890        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10891    }
10892
10893    /**
10894     * Sets whether the view is currently hovered.
10895     * <p>
10896     * Calling this method also changes the drawable state of the view.  This
10897     * enables the view to react to hover by using different drawable resources
10898     * to change its appearance.
10899     * </p><p>
10900     * The {@link #onHoverChanged} method is called when the hovered state changes.
10901     * </p>
10902     *
10903     * @param hovered True if the view is hovered.
10904     *
10905     * @see #isHovered
10906     * @see #onHoverChanged
10907     */
10908    public void setHovered(boolean hovered) {
10909        if (hovered) {
10910            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10911                mPrivateFlags |= PFLAG_HOVERED;
10912                refreshDrawableState();
10913                onHoverChanged(true);
10914            }
10915        } else {
10916            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10917                mPrivateFlags &= ~PFLAG_HOVERED;
10918                refreshDrawableState();
10919                onHoverChanged(false);
10920            }
10921        }
10922    }
10923
10924    /**
10925     * Implement this method to handle hover state changes.
10926     * <p>
10927     * This method is called whenever the hover state changes as a result of a
10928     * call to {@link #setHovered}.
10929     * </p>
10930     *
10931     * @param hovered The current hover state, as returned by {@link #isHovered}.
10932     *
10933     * @see #isHovered
10934     * @see #setHovered
10935     */
10936    public void onHoverChanged(boolean hovered) {
10937    }
10938
10939    /**
10940     * Handles scroll bar dragging by mouse input.
10941     *
10942     * @hide
10943     * @param event The motion event.
10944     *
10945     * @return true if the event was handled as a scroll bar dragging, false otherwise.
10946     */
10947    protected boolean handleScrollBarDragging(MotionEvent event) {
10948        if (mScrollCache == null) {
10949            return false;
10950        }
10951        final float x = event.getX();
10952        final float y = event.getY();
10953        final int action = event.getAction();
10954        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
10955                && action != MotionEvent.ACTION_DOWN)
10956                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
10957                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
10958            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10959            return false;
10960        }
10961
10962        switch (action) {
10963            case MotionEvent.ACTION_MOVE:
10964                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
10965                    return false;
10966                }
10967                if (mScrollCache.mScrollBarDraggingState
10968                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
10969                    final Rect bounds = mScrollCache.mScrollBarBounds;
10970                    getVerticalScrollBarBounds(bounds);
10971                    final int range = computeVerticalScrollRange();
10972                    final int offset = computeVerticalScrollOffset();
10973                    final int extent = computeVerticalScrollExtent();
10974
10975                    final int thumbLength = ScrollBarUtils.getThumbLength(
10976                            bounds.height(), bounds.width(), extent, range);
10977                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10978                            bounds.height(), thumbLength, extent, range, offset);
10979
10980                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
10981                    final float maxThumbOffset = bounds.height() - thumbLength;
10982                    final float newThumbOffset =
10983                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
10984                    final int height = getHeight();
10985                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
10986                            && height > 0 && extent > 0) {
10987                        final int newY = Math.round((range - extent)
10988                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
10989                        if (newY != getScrollY()) {
10990                            mScrollCache.mScrollBarDraggingPos = y;
10991                            setScrollY(newY);
10992                        }
10993                    }
10994                    return true;
10995                }
10996                if (mScrollCache.mScrollBarDraggingState
10997                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
10998                    final Rect bounds = mScrollCache.mScrollBarBounds;
10999                    getHorizontalScrollBarBounds(bounds);
11000                    final int range = computeHorizontalScrollRange();
11001                    final int offset = computeHorizontalScrollOffset();
11002                    final int extent = computeHorizontalScrollExtent();
11003
11004                    final int thumbLength = ScrollBarUtils.getThumbLength(
11005                            bounds.width(), bounds.height(), extent, range);
11006                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11007                            bounds.width(), thumbLength, extent, range, offset);
11008
11009                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11010                    final float maxThumbOffset = bounds.width() - thumbLength;
11011                    final float newThumbOffset =
11012                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11013                    final int width = getWidth();
11014                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11015                            && width > 0 && extent > 0) {
11016                        final int newX = Math.round((range - extent)
11017                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11018                        if (newX != getScrollX()) {
11019                            mScrollCache.mScrollBarDraggingPos = x;
11020                            setScrollX(newX);
11021                        }
11022                    }
11023                    return true;
11024                }
11025            case MotionEvent.ACTION_DOWN:
11026                if (mScrollCache.state == ScrollabilityCache.OFF) {
11027                    return false;
11028                }
11029                if (isOnVerticalScrollbarThumb(x, y)) {
11030                    mScrollCache.mScrollBarDraggingState =
11031                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11032                    mScrollCache.mScrollBarDraggingPos = y;
11033                    return true;
11034                }
11035                if (isOnHorizontalScrollbarThumb(x, y)) {
11036                    mScrollCache.mScrollBarDraggingState =
11037                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11038                    mScrollCache.mScrollBarDraggingPos = x;
11039                    return true;
11040                }
11041        }
11042        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11043        return false;
11044    }
11045
11046    /**
11047     * Implement this method to handle touch screen motion events.
11048     * <p>
11049     * If this method is used to detect click actions, it is recommended that
11050     * the actions be performed by implementing and calling
11051     * {@link #performClick()}. This will ensure consistent system behavior,
11052     * including:
11053     * <ul>
11054     * <li>obeying click sound preferences
11055     * <li>dispatching OnClickListener calls
11056     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11057     * accessibility features are enabled
11058     * </ul>
11059     *
11060     * @param event The motion event.
11061     * @return True if the event was handled, false otherwise.
11062     */
11063    public boolean onTouchEvent(MotionEvent event) {
11064        final float x = event.getX();
11065        final float y = event.getY();
11066        final int viewFlags = mViewFlags;
11067        final int action = event.getAction();
11068
11069        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11070            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11071                setPressed(false);
11072            }
11073            // A disabled view that is clickable still consumes the touch
11074            // events, it just doesn't respond to them.
11075            return (((viewFlags & CLICKABLE) == CLICKABLE
11076                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11077                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11078        }
11079        if (mTouchDelegate != null) {
11080            if (mTouchDelegate.onTouchEvent(event)) {
11081                return true;
11082            }
11083        }
11084
11085        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11086                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11087                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11088            switch (action) {
11089                case MotionEvent.ACTION_UP:
11090                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11091                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11092                        // take focus if we don't have it already and we should in
11093                        // touch mode.
11094                        boolean focusTaken = false;
11095                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11096                            focusTaken = requestFocus();
11097                        }
11098
11099                        if (prepressed) {
11100                            // The button is being released before we actually
11101                            // showed it as pressed.  Make it show the pressed
11102                            // state now (before scheduling the click) to ensure
11103                            // the user sees it.
11104                            setPressed(true, x, y);
11105                       }
11106
11107                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11108                            // This is a tap, so remove the longpress check
11109                            removeLongPressCallback();
11110
11111                            // Only perform take click actions if we were in the pressed state
11112                            if (!focusTaken) {
11113                                // Use a Runnable and post this rather than calling
11114                                // performClick directly. This lets other visual state
11115                                // of the view update before click actions start.
11116                                if (mPerformClick == null) {
11117                                    mPerformClick = new PerformClick();
11118                                }
11119                                if (!post(mPerformClick)) {
11120                                    performClick();
11121                                }
11122                            }
11123                        }
11124
11125                        if (mUnsetPressedState == null) {
11126                            mUnsetPressedState = new UnsetPressedState();
11127                        }
11128
11129                        if (prepressed) {
11130                            postDelayed(mUnsetPressedState,
11131                                    ViewConfiguration.getPressedStateDuration());
11132                        } else if (!post(mUnsetPressedState)) {
11133                            // If the post failed, unpress right now
11134                            mUnsetPressedState.run();
11135                        }
11136
11137                        removeTapCallback();
11138                    }
11139                    mIgnoreNextUpEvent = false;
11140                    break;
11141
11142                case MotionEvent.ACTION_DOWN:
11143                    mHasPerformedLongPress = false;
11144
11145                    if (performButtonActionOnTouchDown(event)) {
11146                        break;
11147                    }
11148
11149                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11150                    boolean isInScrollingContainer = isInScrollingContainer();
11151
11152                    // For views inside a scrolling container, delay the pressed feedback for
11153                    // a short period in case this is a scroll.
11154                    if (isInScrollingContainer) {
11155                        mPrivateFlags |= PFLAG_PREPRESSED;
11156                        if (mPendingCheckForTap == null) {
11157                            mPendingCheckForTap = new CheckForTap();
11158                        }
11159                        mPendingCheckForTap.x = event.getX();
11160                        mPendingCheckForTap.y = event.getY();
11161                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11162                    } else {
11163                        // Not inside a scrolling container, so show the feedback right away
11164                        setPressed(true, x, y);
11165                        checkForLongClick(0, x, y);
11166                    }
11167                    break;
11168
11169                case MotionEvent.ACTION_CANCEL:
11170                    setPressed(false);
11171                    removeTapCallback();
11172                    removeLongPressCallback();
11173                    mInContextButtonPress = false;
11174                    mHasPerformedLongPress = false;
11175                    mIgnoreNextUpEvent = false;
11176                    break;
11177
11178                case MotionEvent.ACTION_MOVE:
11179                    drawableHotspotChanged(x, y);
11180
11181                    // Be lenient about moving outside of buttons
11182                    if (!pointInView(x, y, mTouchSlop)) {
11183                        // Outside button
11184                        removeTapCallback();
11185                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11186                            // Remove any future long press/tap checks
11187                            removeLongPressCallback();
11188
11189                            setPressed(false);
11190                        }
11191                    }
11192                    break;
11193            }
11194
11195            return true;
11196        }
11197
11198        return false;
11199    }
11200
11201    /**
11202     * @hide
11203     */
11204    public boolean isInScrollingContainer() {
11205        ViewParent p = getParent();
11206        while (p != null && p instanceof ViewGroup) {
11207            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11208                return true;
11209            }
11210            p = p.getParent();
11211        }
11212        return false;
11213    }
11214
11215    /**
11216     * Remove the longpress detection timer.
11217     */
11218    private void removeLongPressCallback() {
11219        if (mPendingCheckForLongPress != null) {
11220          removeCallbacks(mPendingCheckForLongPress);
11221        }
11222    }
11223
11224    /**
11225     * Remove the pending click action
11226     */
11227    private void removePerformClickCallback() {
11228        if (mPerformClick != null) {
11229            removeCallbacks(mPerformClick);
11230        }
11231    }
11232
11233    /**
11234     * Remove the prepress detection timer.
11235     */
11236    private void removeUnsetPressCallback() {
11237        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11238            setPressed(false);
11239            removeCallbacks(mUnsetPressedState);
11240        }
11241    }
11242
11243    /**
11244     * Remove the tap detection timer.
11245     */
11246    private void removeTapCallback() {
11247        if (mPendingCheckForTap != null) {
11248            mPrivateFlags &= ~PFLAG_PREPRESSED;
11249            removeCallbacks(mPendingCheckForTap);
11250        }
11251    }
11252
11253    /**
11254     * Cancels a pending long press.  Your subclass can use this if you
11255     * want the context menu to come up if the user presses and holds
11256     * at the same place, but you don't want it to come up if they press
11257     * and then move around enough to cause scrolling.
11258     */
11259    public void cancelLongPress() {
11260        removeLongPressCallback();
11261
11262        /*
11263         * The prepressed state handled by the tap callback is a display
11264         * construct, but the tap callback will post a long press callback
11265         * less its own timeout. Remove it here.
11266         */
11267        removeTapCallback();
11268    }
11269
11270    /**
11271     * Remove the pending callback for sending a
11272     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11273     */
11274    private void removeSendViewScrolledAccessibilityEventCallback() {
11275        if (mSendViewScrolledAccessibilityEvent != null) {
11276            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11277            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11278        }
11279    }
11280
11281    /**
11282     * Sets the TouchDelegate for this View.
11283     */
11284    public void setTouchDelegate(TouchDelegate delegate) {
11285        mTouchDelegate = delegate;
11286    }
11287
11288    /**
11289     * Gets the TouchDelegate for this View.
11290     */
11291    public TouchDelegate getTouchDelegate() {
11292        return mTouchDelegate;
11293    }
11294
11295    /**
11296     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11297     *
11298     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11299     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11300     * available. This method should only be called for touch events.
11301     *
11302     * <p class="note">This api is not intended for most applications. Buffered dispatch
11303     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11304     * streams will not improve your input latency. Side effects include: increased latency,
11305     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11306     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11307     * you.</p>
11308     */
11309    public final void requestUnbufferedDispatch(MotionEvent event) {
11310        final int action = event.getAction();
11311        if (mAttachInfo == null
11312                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11313                || !event.isTouchEvent()) {
11314            return;
11315        }
11316        mAttachInfo.mUnbufferedDispatchRequested = true;
11317    }
11318
11319    /**
11320     * Set flags controlling behavior of this view.
11321     *
11322     * @param flags Constant indicating the value which should be set
11323     * @param mask Constant indicating the bit range that should be changed
11324     */
11325    void setFlags(int flags, int mask) {
11326        final boolean accessibilityEnabled =
11327                AccessibilityManager.getInstance(mContext).isEnabled();
11328        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11329
11330        int old = mViewFlags;
11331        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11332
11333        int changed = mViewFlags ^ old;
11334        if (changed == 0) {
11335            return;
11336        }
11337        int privateFlags = mPrivateFlags;
11338
11339        /* Check if the FOCUSABLE bit has changed */
11340        if (((changed & FOCUSABLE_MASK) != 0) &&
11341                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11342            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11343                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11344                /* Give up focus if we are no longer focusable */
11345                clearFocus();
11346            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11347                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11348                /*
11349                 * Tell the view system that we are now available to take focus
11350                 * if no one else already has it.
11351                 */
11352                if (mParent != null) mParent.focusableViewAvailable(this);
11353            }
11354        }
11355
11356        final int newVisibility = flags & VISIBILITY_MASK;
11357        if (newVisibility == VISIBLE) {
11358            if ((changed & VISIBILITY_MASK) != 0) {
11359                /*
11360                 * If this view is becoming visible, invalidate it in case it changed while
11361                 * it was not visible. Marking it drawn ensures that the invalidation will
11362                 * go through.
11363                 */
11364                mPrivateFlags |= PFLAG_DRAWN;
11365                invalidate(true);
11366
11367                needGlobalAttributesUpdate(true);
11368
11369                // a view becoming visible is worth notifying the parent
11370                // about in case nothing has focus.  even if this specific view
11371                // isn't focusable, it may contain something that is, so let
11372                // the root view try to give this focus if nothing else does.
11373                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11374                    mParent.focusableViewAvailable(this);
11375                }
11376            }
11377        }
11378
11379        /* Check if the GONE bit has changed */
11380        if ((changed & GONE) != 0) {
11381            needGlobalAttributesUpdate(false);
11382            requestLayout();
11383
11384            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11385                if (hasFocus()) clearFocus();
11386                clearAccessibilityFocus();
11387                destroyDrawingCache();
11388                if (mParent instanceof View) {
11389                    // GONE views noop invalidation, so invalidate the parent
11390                    ((View) mParent).invalidate(true);
11391                }
11392                // Mark the view drawn to ensure that it gets invalidated properly the next
11393                // time it is visible and gets invalidated
11394                mPrivateFlags |= PFLAG_DRAWN;
11395            }
11396            if (mAttachInfo != null) {
11397                mAttachInfo.mViewVisibilityChanged = true;
11398            }
11399        }
11400
11401        /* Check if the VISIBLE bit has changed */
11402        if ((changed & INVISIBLE) != 0) {
11403            needGlobalAttributesUpdate(false);
11404            /*
11405             * If this view is becoming invisible, set the DRAWN flag so that
11406             * the next invalidate() will not be skipped.
11407             */
11408            mPrivateFlags |= PFLAG_DRAWN;
11409
11410            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11411                // root view becoming invisible shouldn't clear focus and accessibility focus
11412                if (getRootView() != this) {
11413                    if (hasFocus()) clearFocus();
11414                    clearAccessibilityFocus();
11415                }
11416            }
11417            if (mAttachInfo != null) {
11418                mAttachInfo.mViewVisibilityChanged = true;
11419            }
11420        }
11421
11422        if ((changed & VISIBILITY_MASK) != 0) {
11423            // If the view is invisible, cleanup its display list to free up resources
11424            if (newVisibility != VISIBLE && mAttachInfo != null) {
11425                cleanupDraw();
11426            }
11427
11428            if (mParent instanceof ViewGroup) {
11429                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11430                        (changed & VISIBILITY_MASK), newVisibility);
11431                ((View) mParent).invalidate(true);
11432            } else if (mParent != null) {
11433                mParent.invalidateChild(this, null);
11434            }
11435
11436            if (mAttachInfo != null) {
11437                dispatchVisibilityChanged(this, newVisibility);
11438
11439                // Aggregated visibility changes are dispatched to attached views
11440                // in visible windows where the parent is currently shown/drawn
11441                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11442                // discounting clipping or overlapping. This makes it a good place
11443                // to change animation states.
11444                if (mParent != null && getWindowVisibility() == VISIBLE &&
11445                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11446                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11447                }
11448                notifySubtreeAccessibilityStateChangedIfNeeded();
11449            }
11450        }
11451
11452        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11453            destroyDrawingCache();
11454        }
11455
11456        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11457            destroyDrawingCache();
11458            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11459            invalidateParentCaches();
11460        }
11461
11462        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11463            destroyDrawingCache();
11464            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11465        }
11466
11467        if ((changed & DRAW_MASK) != 0) {
11468            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11469                if (mBackground != null
11470                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11471                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11472                } else {
11473                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11474                }
11475            } else {
11476                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11477            }
11478            requestLayout();
11479            invalidate(true);
11480        }
11481
11482        if ((changed & KEEP_SCREEN_ON) != 0) {
11483            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11484                mParent.recomputeViewAttributes(this);
11485            }
11486        }
11487
11488        if (accessibilityEnabled) {
11489            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11490                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11491                    || (changed & CONTEXT_CLICKABLE) != 0) {
11492                if (oldIncludeForAccessibility != includeForAccessibility()) {
11493                    notifySubtreeAccessibilityStateChangedIfNeeded();
11494                } else {
11495                    notifyViewAccessibilityStateChangedIfNeeded(
11496                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11497                }
11498            } else if ((changed & ENABLED_MASK) != 0) {
11499                notifyViewAccessibilityStateChangedIfNeeded(
11500                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11501            }
11502        }
11503    }
11504
11505    /**
11506     * Change the view's z order in the tree, so it's on top of other sibling
11507     * views. This ordering change may affect layout, if the parent container
11508     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11509     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11510     * method should be followed by calls to {@link #requestLayout()} and
11511     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11512     * with the new child ordering.
11513     *
11514     * @see ViewGroup#bringChildToFront(View)
11515     */
11516    public void bringToFront() {
11517        if (mParent != null) {
11518            mParent.bringChildToFront(this);
11519        }
11520    }
11521
11522    /**
11523     * This is called in response to an internal scroll in this view (i.e., the
11524     * view scrolled its own contents). This is typically as a result of
11525     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11526     * called.
11527     *
11528     * @param l Current horizontal scroll origin.
11529     * @param t Current vertical scroll origin.
11530     * @param oldl Previous horizontal scroll origin.
11531     * @param oldt Previous vertical scroll origin.
11532     */
11533    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11534        notifySubtreeAccessibilityStateChangedIfNeeded();
11535
11536        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11537            postSendViewScrolledAccessibilityEventCallback();
11538        }
11539
11540        mBackgroundSizeChanged = true;
11541        if (mForegroundInfo != null) {
11542            mForegroundInfo.mBoundsChanged = true;
11543        }
11544
11545        final AttachInfo ai = mAttachInfo;
11546        if (ai != null) {
11547            ai.mViewScrollChanged = true;
11548        }
11549
11550        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11551            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11552        }
11553    }
11554
11555    /**
11556     * Interface definition for a callback to be invoked when the scroll
11557     * X or Y positions of a view change.
11558     * <p>
11559     * <b>Note:</b> Some views handle scrolling independently from View and may
11560     * have their own separate listeners for scroll-type events. For example,
11561     * {@link android.widget.ListView ListView} allows clients to register an
11562     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11563     * to listen for changes in list scroll position.
11564     *
11565     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11566     */
11567    public interface OnScrollChangeListener {
11568        /**
11569         * Called when the scroll position of a view changes.
11570         *
11571         * @param v The view whose scroll position has changed.
11572         * @param scrollX Current horizontal scroll origin.
11573         * @param scrollY Current vertical scroll origin.
11574         * @param oldScrollX Previous horizontal scroll origin.
11575         * @param oldScrollY Previous vertical scroll origin.
11576         */
11577        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11578    }
11579
11580    /**
11581     * Interface definition for a callback to be invoked when the layout bounds of a view
11582     * changes due to layout processing.
11583     */
11584    public interface OnLayoutChangeListener {
11585        /**
11586         * Called when the layout bounds of a view changes due to layout processing.
11587         *
11588         * @param v The view whose bounds have changed.
11589         * @param left The new value of the view's left property.
11590         * @param top The new value of the view's top property.
11591         * @param right The new value of the view's right property.
11592         * @param bottom The new value of the view's bottom property.
11593         * @param oldLeft The previous value of the view's left property.
11594         * @param oldTop The previous value of the view's top property.
11595         * @param oldRight The previous value of the view's right property.
11596         * @param oldBottom The previous value of the view's bottom property.
11597         */
11598        void onLayoutChange(View v, int left, int top, int right, int bottom,
11599            int oldLeft, int oldTop, int oldRight, int oldBottom);
11600    }
11601
11602    /**
11603     * This is called during layout when the size of this view has changed. If
11604     * you were just added to the view hierarchy, you're called with the old
11605     * values of 0.
11606     *
11607     * @param w Current width of this view.
11608     * @param h Current height of this view.
11609     * @param oldw Old width of this view.
11610     * @param oldh Old height of this view.
11611     */
11612    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11613    }
11614
11615    /**
11616     * Called by draw to draw the child views. This may be overridden
11617     * by derived classes to gain control just before its children are drawn
11618     * (but after its own view has been drawn).
11619     * @param canvas the canvas on which to draw the view
11620     */
11621    protected void dispatchDraw(Canvas canvas) {
11622
11623    }
11624
11625    /**
11626     * Gets the parent of this view. Note that the parent is a
11627     * ViewParent and not necessarily a View.
11628     *
11629     * @return Parent of this view.
11630     */
11631    public final ViewParent getParent() {
11632        return mParent;
11633    }
11634
11635    /**
11636     * Set the horizontal scrolled position of your view. This will cause a call to
11637     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11638     * invalidated.
11639     * @param value the x position to scroll to
11640     */
11641    public void setScrollX(int value) {
11642        scrollTo(value, mScrollY);
11643    }
11644
11645    /**
11646     * Set the vertical scrolled position of your view. This will cause a call to
11647     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11648     * invalidated.
11649     * @param value the y position to scroll to
11650     */
11651    public void setScrollY(int value) {
11652        scrollTo(mScrollX, value);
11653    }
11654
11655    /**
11656     * Return the scrolled left position of this view. This is the left edge of
11657     * the displayed part of your view. You do not need to draw any pixels
11658     * farther left, since those are outside of the frame of your view on
11659     * screen.
11660     *
11661     * @return The left edge of the displayed part of your view, in pixels.
11662     */
11663    public final int getScrollX() {
11664        return mScrollX;
11665    }
11666
11667    /**
11668     * Return the scrolled top position of this view. This is the top edge of
11669     * the displayed part of your view. You do not need to draw any pixels above
11670     * it, since those are outside of the frame of your view on screen.
11671     *
11672     * @return The top edge of the displayed part of your view, in pixels.
11673     */
11674    public final int getScrollY() {
11675        return mScrollY;
11676    }
11677
11678    /**
11679     * Return the width of the your view.
11680     *
11681     * @return The width of your view, in pixels.
11682     */
11683    @ViewDebug.ExportedProperty(category = "layout")
11684    public final int getWidth() {
11685        return mRight - mLeft;
11686    }
11687
11688    /**
11689     * Return the height of your view.
11690     *
11691     * @return The height of your view, in pixels.
11692     */
11693    @ViewDebug.ExportedProperty(category = "layout")
11694    public final int getHeight() {
11695        return mBottom - mTop;
11696    }
11697
11698    /**
11699     * Return the visible drawing bounds of your view. Fills in the output
11700     * rectangle with the values from getScrollX(), getScrollY(),
11701     * getWidth(), and getHeight(). These bounds do not account for any
11702     * transformation properties currently set on the view, such as
11703     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11704     *
11705     * @param outRect The (scrolled) drawing bounds of the view.
11706     */
11707    public void getDrawingRect(Rect outRect) {
11708        outRect.left = mScrollX;
11709        outRect.top = mScrollY;
11710        outRect.right = mScrollX + (mRight - mLeft);
11711        outRect.bottom = mScrollY + (mBottom - mTop);
11712    }
11713
11714    /**
11715     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11716     * raw width component (that is the result is masked by
11717     * {@link #MEASURED_SIZE_MASK}).
11718     *
11719     * @return The raw measured width of this view.
11720     */
11721    public final int getMeasuredWidth() {
11722        return mMeasuredWidth & MEASURED_SIZE_MASK;
11723    }
11724
11725    /**
11726     * Return the full width measurement information for this view as computed
11727     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11728     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11729     * This should be used during measurement and layout calculations only. Use
11730     * {@link #getWidth()} to see how wide a view is after layout.
11731     *
11732     * @return The measured width of this view as a bit mask.
11733     */
11734    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11735            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11736                    name = "MEASURED_STATE_TOO_SMALL"),
11737    })
11738    public final int getMeasuredWidthAndState() {
11739        return mMeasuredWidth;
11740    }
11741
11742    /**
11743     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11744     * raw width component (that is the result is masked by
11745     * {@link #MEASURED_SIZE_MASK}).
11746     *
11747     * @return The raw measured height of this view.
11748     */
11749    public final int getMeasuredHeight() {
11750        return mMeasuredHeight & MEASURED_SIZE_MASK;
11751    }
11752
11753    /**
11754     * Return the full height measurement information for this view as computed
11755     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11756     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11757     * This should be used during measurement and layout calculations only. Use
11758     * {@link #getHeight()} to see how wide a view is after layout.
11759     *
11760     * @return The measured width of this view as a bit mask.
11761     */
11762    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11763            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11764                    name = "MEASURED_STATE_TOO_SMALL"),
11765    })
11766    public final int getMeasuredHeightAndState() {
11767        return mMeasuredHeight;
11768    }
11769
11770    /**
11771     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11772     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11773     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11774     * and the height component is at the shifted bits
11775     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11776     */
11777    public final int getMeasuredState() {
11778        return (mMeasuredWidth&MEASURED_STATE_MASK)
11779                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11780                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11781    }
11782
11783    /**
11784     * The transform matrix of this view, which is calculated based on the current
11785     * rotation, scale, and pivot properties.
11786     *
11787     * @see #getRotation()
11788     * @see #getScaleX()
11789     * @see #getScaleY()
11790     * @see #getPivotX()
11791     * @see #getPivotY()
11792     * @return The current transform matrix for the view
11793     */
11794    public Matrix getMatrix() {
11795        ensureTransformationInfo();
11796        final Matrix matrix = mTransformationInfo.mMatrix;
11797        mRenderNode.getMatrix(matrix);
11798        return matrix;
11799    }
11800
11801    /**
11802     * Returns true if the transform matrix is the identity matrix.
11803     * Recomputes the matrix if necessary.
11804     *
11805     * @return True if the transform matrix is the identity matrix, false otherwise.
11806     */
11807    final boolean hasIdentityMatrix() {
11808        return mRenderNode.hasIdentityMatrix();
11809    }
11810
11811    void ensureTransformationInfo() {
11812        if (mTransformationInfo == null) {
11813            mTransformationInfo = new TransformationInfo();
11814        }
11815    }
11816
11817    /**
11818     * Utility method to retrieve the inverse of the current mMatrix property.
11819     * We cache the matrix to avoid recalculating it when transform properties
11820     * have not changed.
11821     *
11822     * @return The inverse of the current matrix of this view.
11823     * @hide
11824     */
11825    public final Matrix getInverseMatrix() {
11826        ensureTransformationInfo();
11827        if (mTransformationInfo.mInverseMatrix == null) {
11828            mTransformationInfo.mInverseMatrix = new Matrix();
11829        }
11830        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11831        mRenderNode.getInverseMatrix(matrix);
11832        return matrix;
11833    }
11834
11835    /**
11836     * Gets the distance along the Z axis from the camera to this view.
11837     *
11838     * @see #setCameraDistance(float)
11839     *
11840     * @return The distance along the Z axis.
11841     */
11842    public float getCameraDistance() {
11843        final float dpi = mResources.getDisplayMetrics().densityDpi;
11844        return -(mRenderNode.getCameraDistance() * dpi);
11845    }
11846
11847    /**
11848     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11849     * views are drawn) from the camera to this view. The camera's distance
11850     * affects 3D transformations, for instance rotations around the X and Y
11851     * axis. If the rotationX or rotationY properties are changed and this view is
11852     * large (more than half the size of the screen), it is recommended to always
11853     * use a camera distance that's greater than the height (X axis rotation) or
11854     * the width (Y axis rotation) of this view.</p>
11855     *
11856     * <p>The distance of the camera from the view plane can have an affect on the
11857     * perspective distortion of the view when it is rotated around the x or y axis.
11858     * For example, a large distance will result in a large viewing angle, and there
11859     * will not be much perspective distortion of the view as it rotates. A short
11860     * distance may cause much more perspective distortion upon rotation, and can
11861     * also result in some drawing artifacts if the rotated view ends up partially
11862     * behind the camera (which is why the recommendation is to use a distance at
11863     * least as far as the size of the view, if the view is to be rotated.)</p>
11864     *
11865     * <p>The distance is expressed in "depth pixels." The default distance depends
11866     * on the screen density. For instance, on a medium density display, the
11867     * default distance is 1280. On a high density display, the default distance
11868     * is 1920.</p>
11869     *
11870     * <p>If you want to specify a distance that leads to visually consistent
11871     * results across various densities, use the following formula:</p>
11872     * <pre>
11873     * float scale = context.getResources().getDisplayMetrics().density;
11874     * view.setCameraDistance(distance * scale);
11875     * </pre>
11876     *
11877     * <p>The density scale factor of a high density display is 1.5,
11878     * and 1920 = 1280 * 1.5.</p>
11879     *
11880     * @param distance The distance in "depth pixels", if negative the opposite
11881     *        value is used
11882     *
11883     * @see #setRotationX(float)
11884     * @see #setRotationY(float)
11885     */
11886    public void setCameraDistance(float distance) {
11887        final float dpi = mResources.getDisplayMetrics().densityDpi;
11888
11889        invalidateViewProperty(true, false);
11890        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11891        invalidateViewProperty(false, false);
11892
11893        invalidateParentIfNeededAndWasQuickRejected();
11894    }
11895
11896    /**
11897     * The degrees that the view is rotated around the pivot point.
11898     *
11899     * @see #setRotation(float)
11900     * @see #getPivotX()
11901     * @see #getPivotY()
11902     *
11903     * @return The degrees of rotation.
11904     */
11905    @ViewDebug.ExportedProperty(category = "drawing")
11906    public float getRotation() {
11907        return mRenderNode.getRotation();
11908    }
11909
11910    /**
11911     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11912     * result in clockwise rotation.
11913     *
11914     * @param rotation The degrees of rotation.
11915     *
11916     * @see #getRotation()
11917     * @see #getPivotX()
11918     * @see #getPivotY()
11919     * @see #setRotationX(float)
11920     * @see #setRotationY(float)
11921     *
11922     * @attr ref android.R.styleable#View_rotation
11923     */
11924    public void setRotation(float rotation) {
11925        if (rotation != getRotation()) {
11926            // Double-invalidation is necessary to capture view's old and new areas
11927            invalidateViewProperty(true, false);
11928            mRenderNode.setRotation(rotation);
11929            invalidateViewProperty(false, true);
11930
11931            invalidateParentIfNeededAndWasQuickRejected();
11932            notifySubtreeAccessibilityStateChangedIfNeeded();
11933        }
11934    }
11935
11936    /**
11937     * The degrees that the view is rotated around the vertical axis through the pivot point.
11938     *
11939     * @see #getPivotX()
11940     * @see #getPivotY()
11941     * @see #setRotationY(float)
11942     *
11943     * @return The degrees of Y rotation.
11944     */
11945    @ViewDebug.ExportedProperty(category = "drawing")
11946    public float getRotationY() {
11947        return mRenderNode.getRotationY();
11948    }
11949
11950    /**
11951     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11952     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11953     * down the y axis.
11954     *
11955     * When rotating large views, it is recommended to adjust the camera distance
11956     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11957     *
11958     * @param rotationY The degrees of Y rotation.
11959     *
11960     * @see #getRotationY()
11961     * @see #getPivotX()
11962     * @see #getPivotY()
11963     * @see #setRotation(float)
11964     * @see #setRotationX(float)
11965     * @see #setCameraDistance(float)
11966     *
11967     * @attr ref android.R.styleable#View_rotationY
11968     */
11969    public void setRotationY(float rotationY) {
11970        if (rotationY != getRotationY()) {
11971            invalidateViewProperty(true, false);
11972            mRenderNode.setRotationY(rotationY);
11973            invalidateViewProperty(false, true);
11974
11975            invalidateParentIfNeededAndWasQuickRejected();
11976            notifySubtreeAccessibilityStateChangedIfNeeded();
11977        }
11978    }
11979
11980    /**
11981     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11982     *
11983     * @see #getPivotX()
11984     * @see #getPivotY()
11985     * @see #setRotationX(float)
11986     *
11987     * @return The degrees of X rotation.
11988     */
11989    @ViewDebug.ExportedProperty(category = "drawing")
11990    public float getRotationX() {
11991        return mRenderNode.getRotationX();
11992    }
11993
11994    /**
11995     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
11996     * Increasing values result in clockwise rotation from the viewpoint of looking down the
11997     * x axis.
11998     *
11999     * When rotating large views, it is recommended to adjust the camera distance
12000     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12001     *
12002     * @param rotationX The degrees of X rotation.
12003     *
12004     * @see #getRotationX()
12005     * @see #getPivotX()
12006     * @see #getPivotY()
12007     * @see #setRotation(float)
12008     * @see #setRotationY(float)
12009     * @see #setCameraDistance(float)
12010     *
12011     * @attr ref android.R.styleable#View_rotationX
12012     */
12013    public void setRotationX(float rotationX) {
12014        if (rotationX != getRotationX()) {
12015            invalidateViewProperty(true, false);
12016            mRenderNode.setRotationX(rotationX);
12017            invalidateViewProperty(false, true);
12018
12019            invalidateParentIfNeededAndWasQuickRejected();
12020            notifySubtreeAccessibilityStateChangedIfNeeded();
12021        }
12022    }
12023
12024    /**
12025     * The amount that the view is scaled in x around the pivot point, as a proportion of
12026     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12027     *
12028     * <p>By default, this is 1.0f.
12029     *
12030     * @see #getPivotX()
12031     * @see #getPivotY()
12032     * @return The scaling factor.
12033     */
12034    @ViewDebug.ExportedProperty(category = "drawing")
12035    public float getScaleX() {
12036        return mRenderNode.getScaleX();
12037    }
12038
12039    /**
12040     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12041     * the view's unscaled width. A value of 1 means that no scaling is applied.
12042     *
12043     * @param scaleX The scaling factor.
12044     * @see #getPivotX()
12045     * @see #getPivotY()
12046     *
12047     * @attr ref android.R.styleable#View_scaleX
12048     */
12049    public void setScaleX(float scaleX) {
12050        if (scaleX != getScaleX()) {
12051            invalidateViewProperty(true, false);
12052            mRenderNode.setScaleX(scaleX);
12053            invalidateViewProperty(false, true);
12054
12055            invalidateParentIfNeededAndWasQuickRejected();
12056            notifySubtreeAccessibilityStateChangedIfNeeded();
12057        }
12058    }
12059
12060    /**
12061     * The amount that the view is scaled in y around the pivot point, as a proportion of
12062     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12063     *
12064     * <p>By default, this is 1.0f.
12065     *
12066     * @see #getPivotX()
12067     * @see #getPivotY()
12068     * @return The scaling factor.
12069     */
12070    @ViewDebug.ExportedProperty(category = "drawing")
12071    public float getScaleY() {
12072        return mRenderNode.getScaleY();
12073    }
12074
12075    /**
12076     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12077     * the view's unscaled width. A value of 1 means that no scaling is applied.
12078     *
12079     * @param scaleY The scaling factor.
12080     * @see #getPivotX()
12081     * @see #getPivotY()
12082     *
12083     * @attr ref android.R.styleable#View_scaleY
12084     */
12085    public void setScaleY(float scaleY) {
12086        if (scaleY != getScaleY()) {
12087            invalidateViewProperty(true, false);
12088            mRenderNode.setScaleY(scaleY);
12089            invalidateViewProperty(false, true);
12090
12091            invalidateParentIfNeededAndWasQuickRejected();
12092            notifySubtreeAccessibilityStateChangedIfNeeded();
12093        }
12094    }
12095
12096    /**
12097     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12098     * and {@link #setScaleX(float) scaled}.
12099     *
12100     * @see #getRotation()
12101     * @see #getScaleX()
12102     * @see #getScaleY()
12103     * @see #getPivotY()
12104     * @return The x location of the pivot point.
12105     *
12106     * @attr ref android.R.styleable#View_transformPivotX
12107     */
12108    @ViewDebug.ExportedProperty(category = "drawing")
12109    public float getPivotX() {
12110        return mRenderNode.getPivotX();
12111    }
12112
12113    /**
12114     * Sets the x location of the point around which the view is
12115     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12116     * By default, the pivot point is centered on the object.
12117     * Setting this property disables this behavior and causes the view to use only the
12118     * explicitly set pivotX and pivotY values.
12119     *
12120     * @param pivotX The x location of the pivot point.
12121     * @see #getRotation()
12122     * @see #getScaleX()
12123     * @see #getScaleY()
12124     * @see #getPivotY()
12125     *
12126     * @attr ref android.R.styleable#View_transformPivotX
12127     */
12128    public void setPivotX(float pivotX) {
12129        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12130            invalidateViewProperty(true, false);
12131            mRenderNode.setPivotX(pivotX);
12132            invalidateViewProperty(false, true);
12133
12134            invalidateParentIfNeededAndWasQuickRejected();
12135        }
12136    }
12137
12138    /**
12139     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12140     * and {@link #setScaleY(float) scaled}.
12141     *
12142     * @see #getRotation()
12143     * @see #getScaleX()
12144     * @see #getScaleY()
12145     * @see #getPivotY()
12146     * @return The y location of the pivot point.
12147     *
12148     * @attr ref android.R.styleable#View_transformPivotY
12149     */
12150    @ViewDebug.ExportedProperty(category = "drawing")
12151    public float getPivotY() {
12152        return mRenderNode.getPivotY();
12153    }
12154
12155    /**
12156     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12157     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12158     * Setting this property disables this behavior and causes the view to use only the
12159     * explicitly set pivotX and pivotY values.
12160     *
12161     * @param pivotY The y location of the pivot point.
12162     * @see #getRotation()
12163     * @see #getScaleX()
12164     * @see #getScaleY()
12165     * @see #getPivotY()
12166     *
12167     * @attr ref android.R.styleable#View_transformPivotY
12168     */
12169    public void setPivotY(float pivotY) {
12170        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12171            invalidateViewProperty(true, false);
12172            mRenderNode.setPivotY(pivotY);
12173            invalidateViewProperty(false, true);
12174
12175            invalidateParentIfNeededAndWasQuickRejected();
12176        }
12177    }
12178
12179    /**
12180     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12181     * completely transparent and 1 means the view is completely opaque.
12182     *
12183     * <p>By default this is 1.0f.
12184     * @return The opacity of the view.
12185     */
12186    @ViewDebug.ExportedProperty(category = "drawing")
12187    public float getAlpha() {
12188        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12189    }
12190
12191    /**
12192     * Sets the behavior for overlapping rendering for this view (see {@link
12193     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12194     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12195     * providing the value which is then used internally. That is, when {@link
12196     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12197     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12198     * instead.
12199     *
12200     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12201     * instead of that returned by {@link #hasOverlappingRendering()}.
12202     *
12203     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12204     */
12205    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12206        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12207        if (hasOverlappingRendering) {
12208            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12209        } else {
12210            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12211        }
12212    }
12213
12214    /**
12215     * Returns the value for overlapping rendering that is used internally. This is either
12216     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12217     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12218     *
12219     * @return The value for overlapping rendering being used internally.
12220     */
12221    public final boolean getHasOverlappingRendering() {
12222        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12223                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12224                hasOverlappingRendering();
12225    }
12226
12227    /**
12228     * Returns whether this View has content which overlaps.
12229     *
12230     * <p>This function, intended to be overridden by specific View types, is an optimization when
12231     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12232     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12233     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12234     * directly. An example of overlapping rendering is a TextView with a background image, such as
12235     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12236     * ImageView with only the foreground image. The default implementation returns true; subclasses
12237     * should override if they have cases which can be optimized.</p>
12238     *
12239     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12240     * necessitates that a View return true if it uses the methods internally without passing the
12241     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12242     *
12243     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12244     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12245     *
12246     * @return true if the content in this view might overlap, false otherwise.
12247     */
12248    @ViewDebug.ExportedProperty(category = "drawing")
12249    public boolean hasOverlappingRendering() {
12250        return true;
12251    }
12252
12253    /**
12254     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12255     * completely transparent and 1 means the view is completely opaque.
12256     *
12257     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12258     * can have significant performance implications, especially for large views. It is best to use
12259     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12260     *
12261     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12262     * strongly recommended for performance reasons to either override
12263     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12264     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12265     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12266     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12267     * of rendering cost, even for simple or small views. Starting with
12268     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12269     * applied to the view at the rendering level.</p>
12270     *
12271     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12272     * responsible for applying the opacity itself.</p>
12273     *
12274     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12275     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12276     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12277     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12278     *
12279     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12280     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12281     * {@link #hasOverlappingRendering}.</p>
12282     *
12283     * @param alpha The opacity of the view.
12284     *
12285     * @see #hasOverlappingRendering()
12286     * @see #setLayerType(int, android.graphics.Paint)
12287     *
12288     * @attr ref android.R.styleable#View_alpha
12289     */
12290    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12291        ensureTransformationInfo();
12292        if (mTransformationInfo.mAlpha != alpha) {
12293            mTransformationInfo.mAlpha = alpha;
12294            if (onSetAlpha((int) (alpha * 255))) {
12295                mPrivateFlags |= PFLAG_ALPHA_SET;
12296                // subclass is handling alpha - don't optimize rendering cache invalidation
12297                invalidateParentCaches();
12298                invalidate(true);
12299            } else {
12300                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12301                invalidateViewProperty(true, false);
12302                mRenderNode.setAlpha(getFinalAlpha());
12303                notifyViewAccessibilityStateChangedIfNeeded(
12304                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12305            }
12306        }
12307    }
12308
12309    /**
12310     * Faster version of setAlpha() which performs the same steps except there are
12311     * no calls to invalidate(). The caller of this function should perform proper invalidation
12312     * on the parent and this object. The return value indicates whether the subclass handles
12313     * alpha (the return value for onSetAlpha()).
12314     *
12315     * @param alpha The new value for the alpha property
12316     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12317     *         the new value for the alpha property is different from the old value
12318     */
12319    boolean setAlphaNoInvalidation(float alpha) {
12320        ensureTransformationInfo();
12321        if (mTransformationInfo.mAlpha != alpha) {
12322            mTransformationInfo.mAlpha = alpha;
12323            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12324            if (subclassHandlesAlpha) {
12325                mPrivateFlags |= PFLAG_ALPHA_SET;
12326                return true;
12327            } else {
12328                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12329                mRenderNode.setAlpha(getFinalAlpha());
12330            }
12331        }
12332        return false;
12333    }
12334
12335    /**
12336     * This property is hidden and intended only for use by the Fade transition, which
12337     * animates it to produce a visual translucency that does not side-effect (or get
12338     * affected by) the real alpha property. This value is composited with the other
12339     * alpha value (and the AlphaAnimation value, when that is present) to produce
12340     * a final visual translucency result, which is what is passed into the DisplayList.
12341     *
12342     * @hide
12343     */
12344    public void setTransitionAlpha(float alpha) {
12345        ensureTransformationInfo();
12346        if (mTransformationInfo.mTransitionAlpha != alpha) {
12347            mTransformationInfo.mTransitionAlpha = alpha;
12348            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12349            invalidateViewProperty(true, false);
12350            mRenderNode.setAlpha(getFinalAlpha());
12351        }
12352    }
12353
12354    /**
12355     * Calculates the visual alpha of this view, which is a combination of the actual
12356     * alpha value and the transitionAlpha value (if set).
12357     */
12358    private float getFinalAlpha() {
12359        if (mTransformationInfo != null) {
12360            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12361        }
12362        return 1;
12363    }
12364
12365    /**
12366     * This property is hidden and intended only for use by the Fade transition, which
12367     * animates it to produce a visual translucency that does not side-effect (or get
12368     * affected by) the real alpha property. This value is composited with the other
12369     * alpha value (and the AlphaAnimation value, when that is present) to produce
12370     * a final visual translucency result, which is what is passed into the DisplayList.
12371     *
12372     * @hide
12373     */
12374    @ViewDebug.ExportedProperty(category = "drawing")
12375    public float getTransitionAlpha() {
12376        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12377    }
12378
12379    /**
12380     * Top position of this view relative to its parent.
12381     *
12382     * @return The top of this view, in pixels.
12383     */
12384    @ViewDebug.CapturedViewProperty
12385    public final int getTop() {
12386        return mTop;
12387    }
12388
12389    /**
12390     * Sets the top position of this view relative to its parent. This method is meant to be called
12391     * by the layout system and should not generally be called otherwise, because the property
12392     * may be changed at any time by the layout.
12393     *
12394     * @param top The top of this view, in pixels.
12395     */
12396    public final void setTop(int top) {
12397        if (top != mTop) {
12398            final boolean matrixIsIdentity = hasIdentityMatrix();
12399            if (matrixIsIdentity) {
12400                if (mAttachInfo != null) {
12401                    int minTop;
12402                    int yLoc;
12403                    if (top < mTop) {
12404                        minTop = top;
12405                        yLoc = top - mTop;
12406                    } else {
12407                        minTop = mTop;
12408                        yLoc = 0;
12409                    }
12410                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12411                }
12412            } else {
12413                // Double-invalidation is necessary to capture view's old and new areas
12414                invalidate(true);
12415            }
12416
12417            int width = mRight - mLeft;
12418            int oldHeight = mBottom - mTop;
12419
12420            mTop = top;
12421            mRenderNode.setTop(mTop);
12422
12423            sizeChange(width, mBottom - mTop, width, oldHeight);
12424
12425            if (!matrixIsIdentity) {
12426                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12427                invalidate(true);
12428            }
12429            mBackgroundSizeChanged = true;
12430            if (mForegroundInfo != null) {
12431                mForegroundInfo.mBoundsChanged = true;
12432            }
12433            invalidateParentIfNeeded();
12434            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12435                // View was rejected last time it was drawn by its parent; this may have changed
12436                invalidateParentIfNeeded();
12437            }
12438        }
12439    }
12440
12441    /**
12442     * Bottom position of this view relative to its parent.
12443     *
12444     * @return The bottom of this view, in pixels.
12445     */
12446    @ViewDebug.CapturedViewProperty
12447    public final int getBottom() {
12448        return mBottom;
12449    }
12450
12451    /**
12452     * True if this view has changed since the last time being drawn.
12453     *
12454     * @return The dirty state of this view.
12455     */
12456    public boolean isDirty() {
12457        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12458    }
12459
12460    /**
12461     * Sets the bottom position of this view relative to its parent. This method is meant to be
12462     * called by the layout system and should not generally be called otherwise, because the
12463     * property may be changed at any time by the layout.
12464     *
12465     * @param bottom The bottom of this view, in pixels.
12466     */
12467    public final void setBottom(int bottom) {
12468        if (bottom != mBottom) {
12469            final boolean matrixIsIdentity = hasIdentityMatrix();
12470            if (matrixIsIdentity) {
12471                if (mAttachInfo != null) {
12472                    int maxBottom;
12473                    if (bottom < mBottom) {
12474                        maxBottom = mBottom;
12475                    } else {
12476                        maxBottom = bottom;
12477                    }
12478                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12479                }
12480            } else {
12481                // Double-invalidation is necessary to capture view's old and new areas
12482                invalidate(true);
12483            }
12484
12485            int width = mRight - mLeft;
12486            int oldHeight = mBottom - mTop;
12487
12488            mBottom = bottom;
12489            mRenderNode.setBottom(mBottom);
12490
12491            sizeChange(width, mBottom - mTop, width, oldHeight);
12492
12493            if (!matrixIsIdentity) {
12494                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12495                invalidate(true);
12496            }
12497            mBackgroundSizeChanged = true;
12498            if (mForegroundInfo != null) {
12499                mForegroundInfo.mBoundsChanged = true;
12500            }
12501            invalidateParentIfNeeded();
12502            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12503                // View was rejected last time it was drawn by its parent; this may have changed
12504                invalidateParentIfNeeded();
12505            }
12506        }
12507    }
12508
12509    /**
12510     * Left position of this view relative to its parent.
12511     *
12512     * @return The left edge of this view, in pixels.
12513     */
12514    @ViewDebug.CapturedViewProperty
12515    public final int getLeft() {
12516        return mLeft;
12517    }
12518
12519    /**
12520     * Sets the left position of this view relative to its parent. This method is meant to be called
12521     * by the layout system and should not generally be called otherwise, because the property
12522     * may be changed at any time by the layout.
12523     *
12524     * @param left The left of this view, in pixels.
12525     */
12526    public final void setLeft(int left) {
12527        if (left != mLeft) {
12528            final boolean matrixIsIdentity = hasIdentityMatrix();
12529            if (matrixIsIdentity) {
12530                if (mAttachInfo != null) {
12531                    int minLeft;
12532                    int xLoc;
12533                    if (left < mLeft) {
12534                        minLeft = left;
12535                        xLoc = left - mLeft;
12536                    } else {
12537                        minLeft = mLeft;
12538                        xLoc = 0;
12539                    }
12540                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12541                }
12542            } else {
12543                // Double-invalidation is necessary to capture view's old and new areas
12544                invalidate(true);
12545            }
12546
12547            int oldWidth = mRight - mLeft;
12548            int height = mBottom - mTop;
12549
12550            mLeft = left;
12551            mRenderNode.setLeft(left);
12552
12553            sizeChange(mRight - mLeft, height, oldWidth, height);
12554
12555            if (!matrixIsIdentity) {
12556                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12557                invalidate(true);
12558            }
12559            mBackgroundSizeChanged = true;
12560            if (mForegroundInfo != null) {
12561                mForegroundInfo.mBoundsChanged = true;
12562            }
12563            invalidateParentIfNeeded();
12564            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12565                // View was rejected last time it was drawn by its parent; this may have changed
12566                invalidateParentIfNeeded();
12567            }
12568        }
12569    }
12570
12571    /**
12572     * Right position of this view relative to its parent.
12573     *
12574     * @return The right edge of this view, in pixels.
12575     */
12576    @ViewDebug.CapturedViewProperty
12577    public final int getRight() {
12578        return mRight;
12579    }
12580
12581    /**
12582     * Sets the right position of this view relative to its parent. This method is meant to be called
12583     * by the layout system and should not generally be called otherwise, because the property
12584     * may be changed at any time by the layout.
12585     *
12586     * @param right The right of this view, in pixels.
12587     */
12588    public final void setRight(int right) {
12589        if (right != mRight) {
12590            final boolean matrixIsIdentity = hasIdentityMatrix();
12591            if (matrixIsIdentity) {
12592                if (mAttachInfo != null) {
12593                    int maxRight;
12594                    if (right < mRight) {
12595                        maxRight = mRight;
12596                    } else {
12597                        maxRight = right;
12598                    }
12599                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12600                }
12601            } else {
12602                // Double-invalidation is necessary to capture view's old and new areas
12603                invalidate(true);
12604            }
12605
12606            int oldWidth = mRight - mLeft;
12607            int height = mBottom - mTop;
12608
12609            mRight = right;
12610            mRenderNode.setRight(mRight);
12611
12612            sizeChange(mRight - mLeft, height, oldWidth, height);
12613
12614            if (!matrixIsIdentity) {
12615                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12616                invalidate(true);
12617            }
12618            mBackgroundSizeChanged = true;
12619            if (mForegroundInfo != null) {
12620                mForegroundInfo.mBoundsChanged = true;
12621            }
12622            invalidateParentIfNeeded();
12623            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12624                // View was rejected last time it was drawn by its parent; this may have changed
12625                invalidateParentIfNeeded();
12626            }
12627        }
12628    }
12629
12630    /**
12631     * The visual x position of this view, in pixels. This is equivalent to the
12632     * {@link #setTranslationX(float) translationX} property plus the current
12633     * {@link #getLeft() left} property.
12634     *
12635     * @return The visual x position of this view, in pixels.
12636     */
12637    @ViewDebug.ExportedProperty(category = "drawing")
12638    public float getX() {
12639        return mLeft + getTranslationX();
12640    }
12641
12642    /**
12643     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12644     * {@link #setTranslationX(float) translationX} property to be the difference between
12645     * the x value passed in and the current {@link #getLeft() left} property.
12646     *
12647     * @param x The visual x position of this view, in pixels.
12648     */
12649    public void setX(float x) {
12650        setTranslationX(x - mLeft);
12651    }
12652
12653    /**
12654     * The visual y position of this view, in pixels. This is equivalent to the
12655     * {@link #setTranslationY(float) translationY} property plus the current
12656     * {@link #getTop() top} property.
12657     *
12658     * @return The visual y position of this view, in pixels.
12659     */
12660    @ViewDebug.ExportedProperty(category = "drawing")
12661    public float getY() {
12662        return mTop + getTranslationY();
12663    }
12664
12665    /**
12666     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12667     * {@link #setTranslationY(float) translationY} property to be the difference between
12668     * the y value passed in and the current {@link #getTop() top} property.
12669     *
12670     * @param y The visual y position of this view, in pixels.
12671     */
12672    public void setY(float y) {
12673        setTranslationY(y - mTop);
12674    }
12675
12676    /**
12677     * The visual z position of this view, in pixels. This is equivalent to the
12678     * {@link #setTranslationZ(float) translationZ} property plus the current
12679     * {@link #getElevation() elevation} property.
12680     *
12681     * @return The visual z position of this view, in pixels.
12682     */
12683    @ViewDebug.ExportedProperty(category = "drawing")
12684    public float getZ() {
12685        return getElevation() + getTranslationZ();
12686    }
12687
12688    /**
12689     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12690     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12691     * the x value passed in and the current {@link #getElevation() elevation} property.
12692     *
12693     * @param z The visual z position of this view, in pixels.
12694     */
12695    public void setZ(float z) {
12696        setTranslationZ(z - getElevation());
12697    }
12698
12699    /**
12700     * The base elevation of this view relative to its parent, in pixels.
12701     *
12702     * @return The base depth position of the view, in pixels.
12703     */
12704    @ViewDebug.ExportedProperty(category = "drawing")
12705    public float getElevation() {
12706        return mRenderNode.getElevation();
12707    }
12708
12709    /**
12710     * Sets the base elevation of this view, in pixels.
12711     *
12712     * @attr ref android.R.styleable#View_elevation
12713     */
12714    public void setElevation(float elevation) {
12715        if (elevation != getElevation()) {
12716            invalidateViewProperty(true, false);
12717            mRenderNode.setElevation(elevation);
12718            invalidateViewProperty(false, true);
12719
12720            invalidateParentIfNeededAndWasQuickRejected();
12721        }
12722    }
12723
12724    /**
12725     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12726     * This position is post-layout, in addition to wherever the object's
12727     * layout placed it.
12728     *
12729     * @return The horizontal position of this view relative to its left position, in pixels.
12730     */
12731    @ViewDebug.ExportedProperty(category = "drawing")
12732    public float getTranslationX() {
12733        return mRenderNode.getTranslationX();
12734    }
12735
12736    /**
12737     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12738     * This effectively positions the object post-layout, in addition to wherever the object's
12739     * layout placed it.
12740     *
12741     * @param translationX The horizontal position of this view relative to its left position,
12742     * in pixels.
12743     *
12744     * @attr ref android.R.styleable#View_translationX
12745     */
12746    public void setTranslationX(float translationX) {
12747        if (translationX != getTranslationX()) {
12748            invalidateViewProperty(true, false);
12749            mRenderNode.setTranslationX(translationX);
12750            invalidateViewProperty(false, true);
12751
12752            invalidateParentIfNeededAndWasQuickRejected();
12753            notifySubtreeAccessibilityStateChangedIfNeeded();
12754        }
12755    }
12756
12757    /**
12758     * The vertical location of this view relative to its {@link #getTop() top} position.
12759     * This position is post-layout, in addition to wherever the object's
12760     * layout placed it.
12761     *
12762     * @return The vertical position of this view relative to its top position,
12763     * in pixels.
12764     */
12765    @ViewDebug.ExportedProperty(category = "drawing")
12766    public float getTranslationY() {
12767        return mRenderNode.getTranslationY();
12768    }
12769
12770    /**
12771     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12772     * This effectively positions the object post-layout, in addition to wherever the object's
12773     * layout placed it.
12774     *
12775     * @param translationY The vertical position of this view relative to its top position,
12776     * in pixels.
12777     *
12778     * @attr ref android.R.styleable#View_translationY
12779     */
12780    public void setTranslationY(float translationY) {
12781        if (translationY != getTranslationY()) {
12782            invalidateViewProperty(true, false);
12783            mRenderNode.setTranslationY(translationY);
12784            invalidateViewProperty(false, true);
12785
12786            invalidateParentIfNeededAndWasQuickRejected();
12787            notifySubtreeAccessibilityStateChangedIfNeeded();
12788        }
12789    }
12790
12791    /**
12792     * The depth location of this view relative to its {@link #getElevation() elevation}.
12793     *
12794     * @return The depth of this view relative to its elevation.
12795     */
12796    @ViewDebug.ExportedProperty(category = "drawing")
12797    public float getTranslationZ() {
12798        return mRenderNode.getTranslationZ();
12799    }
12800
12801    /**
12802     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12803     *
12804     * @attr ref android.R.styleable#View_translationZ
12805     */
12806    public void setTranslationZ(float translationZ) {
12807        if (translationZ != getTranslationZ()) {
12808            invalidateViewProperty(true, false);
12809            mRenderNode.setTranslationZ(translationZ);
12810            invalidateViewProperty(false, true);
12811
12812            invalidateParentIfNeededAndWasQuickRejected();
12813        }
12814    }
12815
12816    /** @hide */
12817    public void setAnimationMatrix(Matrix matrix) {
12818        invalidateViewProperty(true, false);
12819        mRenderNode.setAnimationMatrix(matrix);
12820        invalidateViewProperty(false, true);
12821
12822        invalidateParentIfNeededAndWasQuickRejected();
12823    }
12824
12825    /**
12826     * Returns the current StateListAnimator if exists.
12827     *
12828     * @return StateListAnimator or null if it does not exists
12829     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12830     */
12831    public StateListAnimator getStateListAnimator() {
12832        return mStateListAnimator;
12833    }
12834
12835    /**
12836     * Attaches the provided StateListAnimator to this View.
12837     * <p>
12838     * Any previously attached StateListAnimator will be detached.
12839     *
12840     * @param stateListAnimator The StateListAnimator to update the view
12841     * @see {@link android.animation.StateListAnimator}
12842     */
12843    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12844        if (mStateListAnimator == stateListAnimator) {
12845            return;
12846        }
12847        if (mStateListAnimator != null) {
12848            mStateListAnimator.setTarget(null);
12849        }
12850        mStateListAnimator = stateListAnimator;
12851        if (stateListAnimator != null) {
12852            stateListAnimator.setTarget(this);
12853            if (isAttachedToWindow()) {
12854                stateListAnimator.setState(getDrawableState());
12855            }
12856        }
12857    }
12858
12859    /**
12860     * Returns whether the Outline should be used to clip the contents of the View.
12861     * <p>
12862     * Note that this flag will only be respected if the View's Outline returns true from
12863     * {@link Outline#canClip()}.
12864     *
12865     * @see #setOutlineProvider(ViewOutlineProvider)
12866     * @see #setClipToOutline(boolean)
12867     */
12868    public final boolean getClipToOutline() {
12869        return mRenderNode.getClipToOutline();
12870    }
12871
12872    /**
12873     * Sets whether the View's Outline should be used to clip the contents of the View.
12874     * <p>
12875     * Only a single non-rectangular clip can be applied on a View at any time.
12876     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12877     * circular reveal} animation take priority over Outline clipping, and
12878     * child Outline clipping takes priority over Outline clipping done by a
12879     * parent.
12880     * <p>
12881     * Note that this flag will only be respected if the View's Outline returns true from
12882     * {@link Outline#canClip()}.
12883     *
12884     * @see #setOutlineProvider(ViewOutlineProvider)
12885     * @see #getClipToOutline()
12886     */
12887    public void setClipToOutline(boolean clipToOutline) {
12888        damageInParent();
12889        if (getClipToOutline() != clipToOutline) {
12890            mRenderNode.setClipToOutline(clipToOutline);
12891        }
12892    }
12893
12894    // correspond to the enum values of View_outlineProvider
12895    private static final int PROVIDER_BACKGROUND = 0;
12896    private static final int PROVIDER_NONE = 1;
12897    private static final int PROVIDER_BOUNDS = 2;
12898    private static final int PROVIDER_PADDED_BOUNDS = 3;
12899    private void setOutlineProviderFromAttribute(int providerInt) {
12900        switch (providerInt) {
12901            case PROVIDER_BACKGROUND:
12902                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12903                break;
12904            case PROVIDER_NONE:
12905                setOutlineProvider(null);
12906                break;
12907            case PROVIDER_BOUNDS:
12908                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12909                break;
12910            case PROVIDER_PADDED_BOUNDS:
12911                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12912                break;
12913        }
12914    }
12915
12916    /**
12917     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12918     * the shape of the shadow it casts, and enables outline clipping.
12919     * <p>
12920     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12921     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12922     * outline provider with this method allows this behavior to be overridden.
12923     * <p>
12924     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12925     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12926     * <p>
12927     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12928     *
12929     * @see #setClipToOutline(boolean)
12930     * @see #getClipToOutline()
12931     * @see #getOutlineProvider()
12932     */
12933    public void setOutlineProvider(ViewOutlineProvider provider) {
12934        mOutlineProvider = provider;
12935        invalidateOutline();
12936    }
12937
12938    /**
12939     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12940     * that defines the shape of the shadow it casts, and enables outline clipping.
12941     *
12942     * @see #setOutlineProvider(ViewOutlineProvider)
12943     */
12944    public ViewOutlineProvider getOutlineProvider() {
12945        return mOutlineProvider;
12946    }
12947
12948    /**
12949     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12950     *
12951     * @see #setOutlineProvider(ViewOutlineProvider)
12952     */
12953    public void invalidateOutline() {
12954        rebuildOutline();
12955
12956        notifySubtreeAccessibilityStateChangedIfNeeded();
12957        invalidateViewProperty(false, false);
12958    }
12959
12960    /**
12961     * Internal version of {@link #invalidateOutline()} which invalidates the
12962     * outline without invalidating the view itself. This is intended to be called from
12963     * within methods in the View class itself which are the result of the view being
12964     * invalidated already. For example, when we are drawing the background of a View,
12965     * we invalidate the outline in case it changed in the meantime, but we do not
12966     * need to invalidate the view because we're already drawing the background as part
12967     * of drawing the view in response to an earlier invalidation of the view.
12968     */
12969    private void rebuildOutline() {
12970        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12971        if (mAttachInfo == null) return;
12972
12973        if (mOutlineProvider == null) {
12974            // no provider, remove outline
12975            mRenderNode.setOutline(null);
12976        } else {
12977            final Outline outline = mAttachInfo.mTmpOutline;
12978            outline.setEmpty();
12979            outline.setAlpha(1.0f);
12980
12981            mOutlineProvider.getOutline(this, outline);
12982            mRenderNode.setOutline(outline);
12983        }
12984    }
12985
12986    /**
12987     * HierarchyViewer only
12988     *
12989     * @hide
12990     */
12991    @ViewDebug.ExportedProperty(category = "drawing")
12992    public boolean hasShadow() {
12993        return mRenderNode.hasShadow();
12994    }
12995
12996
12997    /** @hide */
12998    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
12999        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13000        invalidateViewProperty(false, false);
13001    }
13002
13003    /**
13004     * Hit rectangle in parent's coordinates
13005     *
13006     * @param outRect The hit rectangle of the view.
13007     */
13008    public void getHitRect(Rect outRect) {
13009        if (hasIdentityMatrix() || mAttachInfo == null) {
13010            outRect.set(mLeft, mTop, mRight, mBottom);
13011        } else {
13012            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13013            tmpRect.set(0, 0, getWidth(), getHeight());
13014            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13015            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13016                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13017        }
13018    }
13019
13020    /**
13021     * Determines whether the given point, in local coordinates is inside the view.
13022     */
13023    /*package*/ final boolean pointInView(float localX, float localY) {
13024        return pointInView(localX, localY, 0);
13025    }
13026
13027    /**
13028     * Utility method to determine whether the given point, in local coordinates,
13029     * is inside the view, where the area of the view is expanded by the slop factor.
13030     * This method is called while processing touch-move events to determine if the event
13031     * is still within the view.
13032     *
13033     * @hide
13034     */
13035    public boolean pointInView(float localX, float localY, float slop) {
13036        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13037                localY < ((mBottom - mTop) + slop);
13038    }
13039
13040    /**
13041     * When a view has focus and the user navigates away from it, the next view is searched for
13042     * starting from the rectangle filled in by this method.
13043     *
13044     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13045     * of the view.  However, if your view maintains some idea of internal selection,
13046     * such as a cursor, or a selected row or column, you should override this method and
13047     * fill in a more specific rectangle.
13048     *
13049     * @param r The rectangle to fill in, in this view's coordinates.
13050     */
13051    public void getFocusedRect(Rect r) {
13052        getDrawingRect(r);
13053    }
13054
13055    /**
13056     * If some part of this view is not clipped by any of its parents, then
13057     * return that area in r in global (root) coordinates. To convert r to local
13058     * coordinates (without taking possible View rotations into account), offset
13059     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13060     * If the view is completely clipped or translated out, return false.
13061     *
13062     * @param r If true is returned, r holds the global coordinates of the
13063     *        visible portion of this view.
13064     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13065     *        between this view and its root. globalOffet may be null.
13066     * @return true if r is non-empty (i.e. part of the view is visible at the
13067     *         root level.
13068     */
13069    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13070        int width = mRight - mLeft;
13071        int height = mBottom - mTop;
13072        if (width > 0 && height > 0) {
13073            r.set(0, 0, width, height);
13074            if (globalOffset != null) {
13075                globalOffset.set(-mScrollX, -mScrollY);
13076            }
13077            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13078        }
13079        return false;
13080    }
13081
13082    public final boolean getGlobalVisibleRect(Rect r) {
13083        return getGlobalVisibleRect(r, null);
13084    }
13085
13086    public final boolean getLocalVisibleRect(Rect r) {
13087        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13088        if (getGlobalVisibleRect(r, offset)) {
13089            r.offset(-offset.x, -offset.y); // make r local
13090            return true;
13091        }
13092        return false;
13093    }
13094
13095    /**
13096     * Offset this view's vertical location by the specified number of pixels.
13097     *
13098     * @param offset the number of pixels to offset the view by
13099     */
13100    public void offsetTopAndBottom(int offset) {
13101        if (offset != 0) {
13102            final boolean matrixIsIdentity = hasIdentityMatrix();
13103            if (matrixIsIdentity) {
13104                if (isHardwareAccelerated()) {
13105                    invalidateViewProperty(false, false);
13106                } else {
13107                    final ViewParent p = mParent;
13108                    if (p != null && mAttachInfo != null) {
13109                        final Rect r = mAttachInfo.mTmpInvalRect;
13110                        int minTop;
13111                        int maxBottom;
13112                        int yLoc;
13113                        if (offset < 0) {
13114                            minTop = mTop + offset;
13115                            maxBottom = mBottom;
13116                            yLoc = offset;
13117                        } else {
13118                            minTop = mTop;
13119                            maxBottom = mBottom + offset;
13120                            yLoc = 0;
13121                        }
13122                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13123                        p.invalidateChild(this, r);
13124                    }
13125                }
13126            } else {
13127                invalidateViewProperty(false, false);
13128            }
13129
13130            mTop += offset;
13131            mBottom += offset;
13132            mRenderNode.offsetTopAndBottom(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     * Offset this view's horizontal location by the specified amount of pixels.
13148     *
13149     * @param offset the number of pixels to offset the view by
13150     */
13151    public void offsetLeftAndRight(int offset) {
13152        if (offset != 0) {
13153            final boolean matrixIsIdentity = hasIdentityMatrix();
13154            if (matrixIsIdentity) {
13155                if (isHardwareAccelerated()) {
13156                    invalidateViewProperty(false, false);
13157                } else {
13158                    final ViewParent p = mParent;
13159                    if (p != null && mAttachInfo != null) {
13160                        final Rect r = mAttachInfo.mTmpInvalRect;
13161                        int minLeft;
13162                        int maxRight;
13163                        if (offset < 0) {
13164                            minLeft = mLeft + offset;
13165                            maxRight = mRight;
13166                        } else {
13167                            minLeft = mLeft;
13168                            maxRight = mRight + offset;
13169                        }
13170                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13171                        p.invalidateChild(this, r);
13172                    }
13173                }
13174            } else {
13175                invalidateViewProperty(false, false);
13176            }
13177
13178            mLeft += offset;
13179            mRight += offset;
13180            mRenderNode.offsetLeftAndRight(offset);
13181            if (isHardwareAccelerated()) {
13182                invalidateViewProperty(false, false);
13183                invalidateParentIfNeededAndWasQuickRejected();
13184            } else {
13185                if (!matrixIsIdentity) {
13186                    invalidateViewProperty(false, true);
13187                }
13188                invalidateParentIfNeeded();
13189            }
13190            notifySubtreeAccessibilityStateChangedIfNeeded();
13191        }
13192    }
13193
13194    /**
13195     * Get the LayoutParams associated with this view. All views should have
13196     * layout parameters. These supply parameters to the <i>parent</i> of this
13197     * view specifying how it should be arranged. There are many subclasses of
13198     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13199     * of ViewGroup that are responsible for arranging their children.
13200     *
13201     * This method may return null if this View is not attached to a parent
13202     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13203     * was not invoked successfully. When a View is attached to a parent
13204     * ViewGroup, this method must not return null.
13205     *
13206     * @return The LayoutParams associated with this view, or null if no
13207     *         parameters have been set yet
13208     */
13209    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13210    public ViewGroup.LayoutParams getLayoutParams() {
13211        return mLayoutParams;
13212    }
13213
13214    /**
13215     * Set the layout parameters associated with this view. These supply
13216     * parameters to the <i>parent</i> of this view specifying how it should be
13217     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13218     * correspond to the different subclasses of ViewGroup that are responsible
13219     * for arranging their children.
13220     *
13221     * @param params The layout parameters for this view, cannot be null
13222     */
13223    public void setLayoutParams(ViewGroup.LayoutParams params) {
13224        if (params == null) {
13225            throw new NullPointerException("Layout parameters cannot be null");
13226        }
13227        mLayoutParams = params;
13228        resolveLayoutParams();
13229        if (mParent instanceof ViewGroup) {
13230            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13231        }
13232        requestLayout();
13233    }
13234
13235    /**
13236     * Resolve the layout parameters depending on the resolved layout direction
13237     *
13238     * @hide
13239     */
13240    public void resolveLayoutParams() {
13241        if (mLayoutParams != null) {
13242            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13243        }
13244    }
13245
13246    /**
13247     * Set the scrolled position of your view. This will cause a call to
13248     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13249     * invalidated.
13250     * @param x the x position to scroll to
13251     * @param y the y position to scroll to
13252     */
13253    public void scrollTo(int x, int y) {
13254        if (mScrollX != x || mScrollY != y) {
13255            int oldX = mScrollX;
13256            int oldY = mScrollY;
13257            mScrollX = x;
13258            mScrollY = y;
13259            invalidateParentCaches();
13260            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13261            if (!awakenScrollBars()) {
13262                postInvalidateOnAnimation();
13263            }
13264        }
13265    }
13266
13267    /**
13268     * Move the scrolled position of your view. This will cause a call to
13269     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13270     * invalidated.
13271     * @param x the amount of pixels to scroll by horizontally
13272     * @param y the amount of pixels to scroll by vertically
13273     */
13274    public void scrollBy(int x, int y) {
13275        scrollTo(mScrollX + x, mScrollY + y);
13276    }
13277
13278    /**
13279     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13280     * animation to fade the scrollbars out after a default delay. If a subclass
13281     * provides animated scrolling, the start delay should equal the duration
13282     * of the scrolling animation.</p>
13283     *
13284     * <p>The animation starts only if at least one of the scrollbars is
13285     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13286     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13287     * this method returns true, and false otherwise. If the animation is
13288     * started, this method calls {@link #invalidate()}; in that case the
13289     * caller should not call {@link #invalidate()}.</p>
13290     *
13291     * <p>This method should be invoked every time a subclass directly updates
13292     * the scroll parameters.</p>
13293     *
13294     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13295     * and {@link #scrollTo(int, int)}.</p>
13296     *
13297     * @return true if the animation is played, false otherwise
13298     *
13299     * @see #awakenScrollBars(int)
13300     * @see #scrollBy(int, int)
13301     * @see #scrollTo(int, int)
13302     * @see #isHorizontalScrollBarEnabled()
13303     * @see #isVerticalScrollBarEnabled()
13304     * @see #setHorizontalScrollBarEnabled(boolean)
13305     * @see #setVerticalScrollBarEnabled(boolean)
13306     */
13307    protected boolean awakenScrollBars() {
13308        return mScrollCache != null &&
13309                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13310    }
13311
13312    /**
13313     * Trigger the scrollbars to draw.
13314     * This method differs from awakenScrollBars() only in its default duration.
13315     * initialAwakenScrollBars() will show the scroll bars for longer than
13316     * usual to give the user more of a chance to notice them.
13317     *
13318     * @return true if the animation is played, false otherwise.
13319     */
13320    private boolean initialAwakenScrollBars() {
13321        return mScrollCache != null &&
13322                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13323    }
13324
13325    /**
13326     * <p>
13327     * Trigger the scrollbars to draw. When invoked this method starts an
13328     * animation to fade the scrollbars out after a fixed delay. If a subclass
13329     * provides animated scrolling, the start delay should equal the duration of
13330     * the scrolling animation.
13331     * </p>
13332     *
13333     * <p>
13334     * The animation starts only if at least one of the scrollbars is enabled,
13335     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13336     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13337     * this method returns true, and false otherwise. If the animation is
13338     * started, this method calls {@link #invalidate()}; in that case the caller
13339     * should not call {@link #invalidate()}.
13340     * </p>
13341     *
13342     * <p>
13343     * This method should be invoked every time a subclass directly updates the
13344     * scroll parameters.
13345     * </p>
13346     *
13347     * @param startDelay the delay, in milliseconds, after which the animation
13348     *        should start; when the delay is 0, the animation starts
13349     *        immediately
13350     * @return true if the animation is played, false otherwise
13351     *
13352     * @see #scrollBy(int, int)
13353     * @see #scrollTo(int, int)
13354     * @see #isHorizontalScrollBarEnabled()
13355     * @see #isVerticalScrollBarEnabled()
13356     * @see #setHorizontalScrollBarEnabled(boolean)
13357     * @see #setVerticalScrollBarEnabled(boolean)
13358     */
13359    protected boolean awakenScrollBars(int startDelay) {
13360        return awakenScrollBars(startDelay, true);
13361    }
13362
13363    /**
13364     * <p>
13365     * Trigger the scrollbars to draw. When invoked this method starts an
13366     * animation to fade the scrollbars out after a fixed delay. If a subclass
13367     * provides animated scrolling, the start delay should equal the duration of
13368     * the scrolling animation.
13369     * </p>
13370     *
13371     * <p>
13372     * The animation starts only if at least one of the scrollbars is enabled,
13373     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13374     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13375     * this method returns true, and false otherwise. If the animation is
13376     * started, this method calls {@link #invalidate()} if the invalidate parameter
13377     * is set to true; in that case the caller
13378     * should not call {@link #invalidate()}.
13379     * </p>
13380     *
13381     * <p>
13382     * This method should be invoked every time a subclass directly updates the
13383     * scroll parameters.
13384     * </p>
13385     *
13386     * @param startDelay the delay, in milliseconds, after which the animation
13387     *        should start; when the delay is 0, the animation starts
13388     *        immediately
13389     *
13390     * @param invalidate Whether this method should call invalidate
13391     *
13392     * @return true if the animation is played, false otherwise
13393     *
13394     * @see #scrollBy(int, int)
13395     * @see #scrollTo(int, int)
13396     * @see #isHorizontalScrollBarEnabled()
13397     * @see #isVerticalScrollBarEnabled()
13398     * @see #setHorizontalScrollBarEnabled(boolean)
13399     * @see #setVerticalScrollBarEnabled(boolean)
13400     */
13401    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13402        final ScrollabilityCache scrollCache = mScrollCache;
13403
13404        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13405            return false;
13406        }
13407
13408        if (scrollCache.scrollBar == null) {
13409            scrollCache.scrollBar = new ScrollBarDrawable();
13410            scrollCache.scrollBar.setState(getDrawableState());
13411            scrollCache.scrollBar.setCallback(this);
13412        }
13413
13414        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13415
13416            if (invalidate) {
13417                // Invalidate to show the scrollbars
13418                postInvalidateOnAnimation();
13419            }
13420
13421            if (scrollCache.state == ScrollabilityCache.OFF) {
13422                // FIXME: this is copied from WindowManagerService.
13423                // We should get this value from the system when it
13424                // is possible to do so.
13425                final int KEY_REPEAT_FIRST_DELAY = 750;
13426                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13427            }
13428
13429            // Tell mScrollCache when we should start fading. This may
13430            // extend the fade start time if one was already scheduled
13431            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13432            scrollCache.fadeStartTime = fadeStartTime;
13433            scrollCache.state = ScrollabilityCache.ON;
13434
13435            // Schedule our fader to run, unscheduling any old ones first
13436            if (mAttachInfo != null) {
13437                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13438                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13439            }
13440
13441            return true;
13442        }
13443
13444        return false;
13445    }
13446
13447    /**
13448     * Do not invalidate views which are not visible and which are not running an animation. They
13449     * will not get drawn and they should not set dirty flags as if they will be drawn
13450     */
13451    private boolean skipInvalidate() {
13452        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13453                (!(mParent instanceof ViewGroup) ||
13454                        !((ViewGroup) mParent).isViewTransitioning(this));
13455    }
13456
13457    /**
13458     * Mark the area defined by dirty as needing to be drawn. If the view is
13459     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13460     * point in the future.
13461     * <p>
13462     * This must be called from a UI thread. To call from a non-UI thread, call
13463     * {@link #postInvalidate()}.
13464     * <p>
13465     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13466     * {@code dirty}.
13467     *
13468     * @param dirty the rectangle representing the bounds of the dirty region
13469     */
13470    public void invalidate(Rect dirty) {
13471        final int scrollX = mScrollX;
13472        final int scrollY = mScrollY;
13473        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13474                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13475    }
13476
13477    /**
13478     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13479     * coordinates of the dirty rect are relative to the view. If the view is
13480     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13481     * point in the future.
13482     * <p>
13483     * This must be called from a UI thread. To call from a non-UI thread, call
13484     * {@link #postInvalidate()}.
13485     *
13486     * @param l the left position of the dirty region
13487     * @param t the top position of the dirty region
13488     * @param r the right position of the dirty region
13489     * @param b the bottom position of the dirty region
13490     */
13491    public void invalidate(int l, int t, int r, int b) {
13492        final int scrollX = mScrollX;
13493        final int scrollY = mScrollY;
13494        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13495    }
13496
13497    /**
13498     * Invalidate the whole view. If the view is visible,
13499     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13500     * the future.
13501     * <p>
13502     * This must be called from a UI thread. To call from a non-UI thread, call
13503     * {@link #postInvalidate()}.
13504     */
13505    public void invalidate() {
13506        invalidate(true);
13507    }
13508
13509    /**
13510     * This is where the invalidate() work actually happens. A full invalidate()
13511     * causes the drawing cache to be invalidated, but this function can be
13512     * called with invalidateCache set to false to skip that invalidation step
13513     * for cases that do not need it (for example, a component that remains at
13514     * the same dimensions with the same content).
13515     *
13516     * @param invalidateCache Whether the drawing cache for this view should be
13517     *            invalidated as well. This is usually true for a full
13518     *            invalidate, but may be set to false if the View's contents or
13519     *            dimensions have not changed.
13520     */
13521    void invalidate(boolean invalidateCache) {
13522        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13523    }
13524
13525    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13526            boolean fullInvalidate) {
13527        if (mGhostView != null) {
13528            mGhostView.invalidate(true);
13529            return;
13530        }
13531
13532        if (skipInvalidate()) {
13533            return;
13534        }
13535
13536        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13537                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13538                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13539                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13540            if (fullInvalidate) {
13541                mLastIsOpaque = isOpaque();
13542                mPrivateFlags &= ~PFLAG_DRAWN;
13543            }
13544
13545            mPrivateFlags |= PFLAG_DIRTY;
13546
13547            if (invalidateCache) {
13548                mPrivateFlags |= PFLAG_INVALIDATED;
13549                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13550            }
13551
13552            // Propagate the damage rectangle to the parent view.
13553            final AttachInfo ai = mAttachInfo;
13554            final ViewParent p = mParent;
13555            if (p != null && ai != null && l < r && t < b) {
13556                final Rect damage = ai.mTmpInvalRect;
13557                damage.set(l, t, r, b);
13558                p.invalidateChild(this, damage);
13559            }
13560
13561            // Damage the entire projection receiver, if necessary.
13562            if (mBackground != null && mBackground.isProjected()) {
13563                final View receiver = getProjectionReceiver();
13564                if (receiver != null) {
13565                    receiver.damageInParent();
13566                }
13567            }
13568
13569            // Damage the entire IsolatedZVolume receiving this view's shadow.
13570            if (isHardwareAccelerated() && getZ() != 0) {
13571                damageShadowReceiver();
13572            }
13573        }
13574    }
13575
13576    /**
13577     * @return this view's projection receiver, or {@code null} if none exists
13578     */
13579    private View getProjectionReceiver() {
13580        ViewParent p = getParent();
13581        while (p != null && p instanceof View) {
13582            final View v = (View) p;
13583            if (v.isProjectionReceiver()) {
13584                return v;
13585            }
13586            p = p.getParent();
13587        }
13588
13589        return null;
13590    }
13591
13592    /**
13593     * @return whether the view is a projection receiver
13594     */
13595    private boolean isProjectionReceiver() {
13596        return mBackground != null;
13597    }
13598
13599    /**
13600     * Damage area of the screen that can be covered by this View's shadow.
13601     *
13602     * This method will guarantee that any changes to shadows cast by a View
13603     * are damaged on the screen for future redraw.
13604     */
13605    private void damageShadowReceiver() {
13606        final AttachInfo ai = mAttachInfo;
13607        if (ai != null) {
13608            ViewParent p = getParent();
13609            if (p != null && p instanceof ViewGroup) {
13610                final ViewGroup vg = (ViewGroup) p;
13611                vg.damageInParent();
13612            }
13613        }
13614    }
13615
13616    /**
13617     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13618     * set any flags or handle all of the cases handled by the default invalidation methods.
13619     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13620     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13621     * walk up the hierarchy, transforming the dirty rect as necessary.
13622     *
13623     * The method also handles normal invalidation logic if display list properties are not
13624     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13625     * backup approach, to handle these cases used in the various property-setting methods.
13626     *
13627     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13628     * are not being used in this view
13629     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13630     * list properties are not being used in this view
13631     */
13632    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13633        if (!isHardwareAccelerated()
13634                || !mRenderNode.isValid()
13635                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13636            if (invalidateParent) {
13637                invalidateParentCaches();
13638            }
13639            if (forceRedraw) {
13640                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13641            }
13642            invalidate(false);
13643        } else {
13644            damageInParent();
13645        }
13646        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13647            damageShadowReceiver();
13648        }
13649    }
13650
13651    /**
13652     * Tells the parent view to damage this view's bounds.
13653     *
13654     * @hide
13655     */
13656    protected void damageInParent() {
13657        final AttachInfo ai = mAttachInfo;
13658        final ViewParent p = mParent;
13659        if (p != null && ai != null) {
13660            final Rect r = ai.mTmpInvalRect;
13661            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13662            if (mParent instanceof ViewGroup) {
13663                ((ViewGroup) mParent).damageChild(this, r);
13664            } else {
13665                mParent.invalidateChild(this, r);
13666            }
13667        }
13668    }
13669
13670    /**
13671     * Utility method to transform a given Rect by the current matrix of this view.
13672     */
13673    void transformRect(final Rect rect) {
13674        if (!getMatrix().isIdentity()) {
13675            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13676            boundingRect.set(rect);
13677            getMatrix().mapRect(boundingRect);
13678            rect.set((int) Math.floor(boundingRect.left),
13679                    (int) Math.floor(boundingRect.top),
13680                    (int) Math.ceil(boundingRect.right),
13681                    (int) Math.ceil(boundingRect.bottom));
13682        }
13683    }
13684
13685    /**
13686     * Used to indicate that the parent of this view should clear its caches. This functionality
13687     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13688     * which is necessary when various parent-managed properties of the view change, such as
13689     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13690     * clears the parent caches and does not causes an invalidate event.
13691     *
13692     * @hide
13693     */
13694    protected void invalidateParentCaches() {
13695        if (mParent instanceof View) {
13696            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13697        }
13698    }
13699
13700    /**
13701     * Used to indicate that the parent of this view should be invalidated. This functionality
13702     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13703     * which is necessary when various parent-managed properties of the view change, such as
13704     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13705     * an invalidation event to the parent.
13706     *
13707     * @hide
13708     */
13709    protected void invalidateParentIfNeeded() {
13710        if (isHardwareAccelerated() && mParent instanceof View) {
13711            ((View) mParent).invalidate(true);
13712        }
13713    }
13714
13715    /**
13716     * @hide
13717     */
13718    protected void invalidateParentIfNeededAndWasQuickRejected() {
13719        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13720            // View was rejected last time it was drawn by its parent; this may have changed
13721            invalidateParentIfNeeded();
13722        }
13723    }
13724
13725    /**
13726     * Indicates whether this View is opaque. An opaque View guarantees that it will
13727     * draw all the pixels overlapping its bounds using a fully opaque color.
13728     *
13729     * Subclasses of View should override this method whenever possible to indicate
13730     * whether an instance is opaque. Opaque Views are treated in a special way by
13731     * the View hierarchy, possibly allowing it to perform optimizations during
13732     * invalidate/draw passes.
13733     *
13734     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13735     */
13736    @ViewDebug.ExportedProperty(category = "drawing")
13737    public boolean isOpaque() {
13738        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13739                getFinalAlpha() >= 1.0f;
13740    }
13741
13742    /**
13743     * @hide
13744     */
13745    protected void computeOpaqueFlags() {
13746        // Opaque if:
13747        //   - Has a background
13748        //   - Background is opaque
13749        //   - Doesn't have scrollbars or scrollbars overlay
13750
13751        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13752            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13753        } else {
13754            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13755        }
13756
13757        final int flags = mViewFlags;
13758        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13759                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13760                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13761            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13762        } else {
13763            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13764        }
13765    }
13766
13767    /**
13768     * @hide
13769     */
13770    protected boolean hasOpaqueScrollbars() {
13771        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13772    }
13773
13774    /**
13775     * @return A handler associated with the thread running the View. This
13776     * handler can be used to pump events in the UI events queue.
13777     */
13778    public Handler getHandler() {
13779        final AttachInfo attachInfo = mAttachInfo;
13780        if (attachInfo != null) {
13781            return attachInfo.mHandler;
13782        }
13783        return null;
13784    }
13785
13786    /**
13787     * Returns the queue of runnable for this view.
13788     *
13789     * @return the queue of runnables for this view
13790     */
13791    private HandlerActionQueue getRunQueue() {
13792        if (mRunQueue == null) {
13793            mRunQueue = new HandlerActionQueue();
13794        }
13795        return mRunQueue;
13796    }
13797
13798    /**
13799     * Gets the view root associated with the View.
13800     * @return The view root, or null if none.
13801     * @hide
13802     */
13803    public ViewRootImpl getViewRootImpl() {
13804        if (mAttachInfo != null) {
13805            return mAttachInfo.mViewRootImpl;
13806        }
13807        return null;
13808    }
13809
13810    /**
13811     * @hide
13812     */
13813    public ThreadedRenderer getHardwareRenderer() {
13814        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
13815    }
13816
13817    /**
13818     * <p>Causes the Runnable to be added to the message queue.
13819     * The runnable will be run on the user interface thread.</p>
13820     *
13821     * @param action The Runnable that will be executed.
13822     *
13823     * @return Returns true if the Runnable was successfully placed in to the
13824     *         message queue.  Returns false on failure, usually because the
13825     *         looper processing the message queue is exiting.
13826     *
13827     * @see #postDelayed
13828     * @see #removeCallbacks
13829     */
13830    public boolean post(Runnable action) {
13831        final AttachInfo attachInfo = mAttachInfo;
13832        if (attachInfo != null) {
13833            return attachInfo.mHandler.post(action);
13834        }
13835
13836        // Postpone the runnable until we know on which thread it needs to run.
13837        // Assume that the runnable will be successfully placed after attach.
13838        getRunQueue().post(action);
13839        return true;
13840    }
13841
13842    /**
13843     * <p>Causes the Runnable to be added to the message queue, to be run
13844     * after the specified amount of time elapses.
13845     * The runnable will be run on the user interface thread.</p>
13846     *
13847     * @param action The Runnable that will be executed.
13848     * @param delayMillis The delay (in milliseconds) until the Runnable
13849     *        will be executed.
13850     *
13851     * @return true if the Runnable was successfully placed in to the
13852     *         message queue.  Returns false on failure, usually because the
13853     *         looper processing the message queue is exiting.  Note that a
13854     *         result of true does not mean the Runnable will be processed --
13855     *         if the looper is quit before the delivery time of the message
13856     *         occurs then the message will be dropped.
13857     *
13858     * @see #post
13859     * @see #removeCallbacks
13860     */
13861    public boolean postDelayed(Runnable action, long delayMillis) {
13862        final AttachInfo attachInfo = mAttachInfo;
13863        if (attachInfo != null) {
13864            return attachInfo.mHandler.postDelayed(action, delayMillis);
13865        }
13866
13867        // Postpone the runnable until we know on which thread it needs to run.
13868        // Assume that the runnable will be successfully placed after attach.
13869        getRunQueue().postDelayed(action, delayMillis);
13870        return true;
13871    }
13872
13873    /**
13874     * <p>Causes the Runnable to execute on the next animation time step.
13875     * The runnable will be run on the user interface thread.</p>
13876     *
13877     * @param action The Runnable that will be executed.
13878     *
13879     * @see #postOnAnimationDelayed
13880     * @see #removeCallbacks
13881     */
13882    public void postOnAnimation(Runnable action) {
13883        final AttachInfo attachInfo = mAttachInfo;
13884        if (attachInfo != null) {
13885            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13886                    Choreographer.CALLBACK_ANIMATION, action, null);
13887        } else {
13888            // Postpone the runnable until we know
13889            // on which thread it needs to run.
13890            getRunQueue().post(action);
13891        }
13892    }
13893
13894    /**
13895     * <p>Causes the Runnable to execute on the next animation time step,
13896     * after the specified amount of time elapses.
13897     * The runnable will be run on the user interface thread.</p>
13898     *
13899     * @param action The Runnable that will be executed.
13900     * @param delayMillis The delay (in milliseconds) until the Runnable
13901     *        will be executed.
13902     *
13903     * @see #postOnAnimation
13904     * @see #removeCallbacks
13905     */
13906    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13907        final AttachInfo attachInfo = mAttachInfo;
13908        if (attachInfo != null) {
13909            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13910                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13911        } else {
13912            // Postpone the runnable until we know
13913            // on which thread it needs to run.
13914            getRunQueue().postDelayed(action, delayMillis);
13915        }
13916    }
13917
13918    /**
13919     * <p>Removes the specified Runnable from the message queue.</p>
13920     *
13921     * @param action The Runnable to remove from the message handling queue
13922     *
13923     * @return true if this view could ask the Handler to remove the Runnable,
13924     *         false otherwise. When the returned value is true, the Runnable
13925     *         may or may not have been actually removed from the message queue
13926     *         (for instance, if the Runnable was not in the queue already.)
13927     *
13928     * @see #post
13929     * @see #postDelayed
13930     * @see #postOnAnimation
13931     * @see #postOnAnimationDelayed
13932     */
13933    public boolean removeCallbacks(Runnable action) {
13934        if (action != null) {
13935            final AttachInfo attachInfo = mAttachInfo;
13936            if (attachInfo != null) {
13937                attachInfo.mHandler.removeCallbacks(action);
13938                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13939                        Choreographer.CALLBACK_ANIMATION, action, null);
13940            }
13941            getRunQueue().removeCallbacks(action);
13942        }
13943        return true;
13944    }
13945
13946    /**
13947     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13948     * Use this to invalidate the View from a non-UI thread.</p>
13949     *
13950     * <p>This method can be invoked from outside of the UI thread
13951     * only when this View is attached to a window.</p>
13952     *
13953     * @see #invalidate()
13954     * @see #postInvalidateDelayed(long)
13955     */
13956    public void postInvalidate() {
13957        postInvalidateDelayed(0);
13958    }
13959
13960    /**
13961     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13962     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13963     *
13964     * <p>This method can be invoked from outside of the UI thread
13965     * only when this View is attached to a window.</p>
13966     *
13967     * @param left The left coordinate of the rectangle to invalidate.
13968     * @param top The top coordinate of the rectangle to invalidate.
13969     * @param right The right coordinate of the rectangle to invalidate.
13970     * @param bottom The bottom coordinate of the rectangle to invalidate.
13971     *
13972     * @see #invalidate(int, int, int, int)
13973     * @see #invalidate(Rect)
13974     * @see #postInvalidateDelayed(long, int, int, int, int)
13975     */
13976    public void postInvalidate(int left, int top, int right, int bottom) {
13977        postInvalidateDelayed(0, left, top, right, bottom);
13978    }
13979
13980    /**
13981     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13982     * loop. Waits for the specified amount of time.</p>
13983     *
13984     * <p>This method can be invoked from outside of the UI thread
13985     * only when this View is attached to a window.</p>
13986     *
13987     * @param delayMilliseconds the duration in milliseconds to delay the
13988     *         invalidation by
13989     *
13990     * @see #invalidate()
13991     * @see #postInvalidate()
13992     */
13993    public void postInvalidateDelayed(long delayMilliseconds) {
13994        // We try only with the AttachInfo because there's no point in invalidating
13995        // if we are not attached to our window
13996        final AttachInfo attachInfo = mAttachInfo;
13997        if (attachInfo != null) {
13998            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
13999        }
14000    }
14001
14002    /**
14003     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14004     * through the event loop. Waits for the specified amount of time.</p>
14005     *
14006     * <p>This method can be invoked from outside of the UI thread
14007     * only when this View is attached to a window.</p>
14008     *
14009     * @param delayMilliseconds the duration in milliseconds to delay the
14010     *         invalidation by
14011     * @param left The left coordinate of the rectangle to invalidate.
14012     * @param top The top coordinate of the rectangle to invalidate.
14013     * @param right The right coordinate of the rectangle to invalidate.
14014     * @param bottom The bottom coordinate of the rectangle to invalidate.
14015     *
14016     * @see #invalidate(int, int, int, int)
14017     * @see #invalidate(Rect)
14018     * @see #postInvalidate(int, int, int, int)
14019     */
14020    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14021            int right, int bottom) {
14022
14023        // We try only with the AttachInfo because there's no point in invalidating
14024        // if we are not attached to our window
14025        final AttachInfo attachInfo = mAttachInfo;
14026        if (attachInfo != null) {
14027            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14028            info.target = this;
14029            info.left = left;
14030            info.top = top;
14031            info.right = right;
14032            info.bottom = bottom;
14033
14034            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14035        }
14036    }
14037
14038    /**
14039     * <p>Cause an invalidate to happen on the next animation time step, typically the
14040     * next display frame.</p>
14041     *
14042     * <p>This method can be invoked from outside of the UI thread
14043     * only when this View is attached to a window.</p>
14044     *
14045     * @see #invalidate()
14046     */
14047    public void postInvalidateOnAnimation() {
14048        // We try only with the AttachInfo because there's no point in invalidating
14049        // if we are not attached to our window
14050        final AttachInfo attachInfo = mAttachInfo;
14051        if (attachInfo != null) {
14052            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14053        }
14054    }
14055
14056    /**
14057     * <p>Cause an invalidate of the specified area to happen on the next animation
14058     * time step, typically the next display frame.</p>
14059     *
14060     * <p>This method can be invoked from outside of the UI thread
14061     * only when this View is attached to a window.</p>
14062     *
14063     * @param left The left coordinate of the rectangle to invalidate.
14064     * @param top The top coordinate of the rectangle to invalidate.
14065     * @param right The right coordinate of the rectangle to invalidate.
14066     * @param bottom The bottom coordinate of the rectangle to invalidate.
14067     *
14068     * @see #invalidate(int, int, int, int)
14069     * @see #invalidate(Rect)
14070     */
14071    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14072        // We try only with the AttachInfo because there's no point in invalidating
14073        // if we are not attached to our window
14074        final AttachInfo attachInfo = mAttachInfo;
14075        if (attachInfo != null) {
14076            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14077            info.target = this;
14078            info.left = left;
14079            info.top = top;
14080            info.right = right;
14081            info.bottom = bottom;
14082
14083            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14084        }
14085    }
14086
14087    /**
14088     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14089     * This event is sent at most once every
14090     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14091     */
14092    private void postSendViewScrolledAccessibilityEventCallback() {
14093        if (mSendViewScrolledAccessibilityEvent == null) {
14094            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14095        }
14096        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14097            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14098            postDelayed(mSendViewScrolledAccessibilityEvent,
14099                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14100        }
14101    }
14102
14103    /**
14104     * Called by a parent to request that a child update its values for mScrollX
14105     * and mScrollY if necessary. This will typically be done if the child is
14106     * animating a scroll using a {@link android.widget.Scroller Scroller}
14107     * object.
14108     */
14109    public void computeScroll() {
14110    }
14111
14112    /**
14113     * <p>Indicate whether the horizontal edges are faded when the view is
14114     * scrolled horizontally.</p>
14115     *
14116     * @return true if the horizontal edges should are faded on scroll, false
14117     *         otherwise
14118     *
14119     * @see #setHorizontalFadingEdgeEnabled(boolean)
14120     *
14121     * @attr ref android.R.styleable#View_requiresFadingEdge
14122     */
14123    public boolean isHorizontalFadingEdgeEnabled() {
14124        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14125    }
14126
14127    /**
14128     * <p>Define whether the horizontal edges should be faded when this view
14129     * is scrolled horizontally.</p>
14130     *
14131     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14132     *                                    be faded when the view is scrolled
14133     *                                    horizontally
14134     *
14135     * @see #isHorizontalFadingEdgeEnabled()
14136     *
14137     * @attr ref android.R.styleable#View_requiresFadingEdge
14138     */
14139    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14140        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14141            if (horizontalFadingEdgeEnabled) {
14142                initScrollCache();
14143            }
14144
14145            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14146        }
14147    }
14148
14149    /**
14150     * <p>Indicate whether the vertical edges are faded when the view is
14151     * scrolled horizontally.</p>
14152     *
14153     * @return true if the vertical edges should are faded on scroll, false
14154     *         otherwise
14155     *
14156     * @see #setVerticalFadingEdgeEnabled(boolean)
14157     *
14158     * @attr ref android.R.styleable#View_requiresFadingEdge
14159     */
14160    public boolean isVerticalFadingEdgeEnabled() {
14161        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14162    }
14163
14164    /**
14165     * <p>Define whether the vertical edges should be faded when this view
14166     * is scrolled vertically.</p>
14167     *
14168     * @param verticalFadingEdgeEnabled true if the vertical edges should
14169     *                                  be faded when the view is scrolled
14170     *                                  vertically
14171     *
14172     * @see #isVerticalFadingEdgeEnabled()
14173     *
14174     * @attr ref android.R.styleable#View_requiresFadingEdge
14175     */
14176    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14177        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14178            if (verticalFadingEdgeEnabled) {
14179                initScrollCache();
14180            }
14181
14182            mViewFlags ^= FADING_EDGE_VERTICAL;
14183        }
14184    }
14185
14186    /**
14187     * Returns the strength, or intensity, of the top faded edge. The strength is
14188     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14189     * returns 0.0 or 1.0 but no value in between.
14190     *
14191     * Subclasses should override this method to provide a smoother fade transition
14192     * when scrolling occurs.
14193     *
14194     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14195     */
14196    protected float getTopFadingEdgeStrength() {
14197        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14198    }
14199
14200    /**
14201     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14202     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14203     * returns 0.0 or 1.0 but no value in between.
14204     *
14205     * Subclasses should override this method to provide a smoother fade transition
14206     * when scrolling occurs.
14207     *
14208     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14209     */
14210    protected float getBottomFadingEdgeStrength() {
14211        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14212                computeVerticalScrollRange() ? 1.0f : 0.0f;
14213    }
14214
14215    /**
14216     * Returns the strength, or intensity, of the left faded edge. The strength is
14217     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14218     * returns 0.0 or 1.0 but no value in between.
14219     *
14220     * Subclasses should override this method to provide a smoother fade transition
14221     * when scrolling occurs.
14222     *
14223     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14224     */
14225    protected float getLeftFadingEdgeStrength() {
14226        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14227    }
14228
14229    /**
14230     * Returns the strength, or intensity, of the right faded edge. The strength is
14231     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14232     * returns 0.0 or 1.0 but no value in between.
14233     *
14234     * Subclasses should override this method to provide a smoother fade transition
14235     * when scrolling occurs.
14236     *
14237     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14238     */
14239    protected float getRightFadingEdgeStrength() {
14240        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14241                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14242    }
14243
14244    /**
14245     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14246     * scrollbar is not drawn by default.</p>
14247     *
14248     * @return true if the horizontal scrollbar should be painted, false
14249     *         otherwise
14250     *
14251     * @see #setHorizontalScrollBarEnabled(boolean)
14252     */
14253    public boolean isHorizontalScrollBarEnabled() {
14254        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14255    }
14256
14257    /**
14258     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14259     * scrollbar is not drawn by default.</p>
14260     *
14261     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14262     *                                   be painted
14263     *
14264     * @see #isHorizontalScrollBarEnabled()
14265     */
14266    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14267        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14268            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14269            computeOpaqueFlags();
14270            resolvePadding();
14271        }
14272    }
14273
14274    /**
14275     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14276     * scrollbar is not drawn by default.</p>
14277     *
14278     * @return true if the vertical scrollbar should be painted, false
14279     *         otherwise
14280     *
14281     * @see #setVerticalScrollBarEnabled(boolean)
14282     */
14283    public boolean isVerticalScrollBarEnabled() {
14284        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14285    }
14286
14287    /**
14288     * <p>Define whether the vertical scrollbar should be drawn or not. The
14289     * scrollbar is not drawn by default.</p>
14290     *
14291     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14292     *                                 be painted
14293     *
14294     * @see #isVerticalScrollBarEnabled()
14295     */
14296    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14297        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14298            mViewFlags ^= SCROLLBARS_VERTICAL;
14299            computeOpaqueFlags();
14300            resolvePadding();
14301        }
14302    }
14303
14304    /**
14305     * @hide
14306     */
14307    protected void recomputePadding() {
14308        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14309    }
14310
14311    /**
14312     * Define whether scrollbars will fade when the view is not scrolling.
14313     *
14314     * @param fadeScrollbars whether to enable fading
14315     *
14316     * @attr ref android.R.styleable#View_fadeScrollbars
14317     */
14318    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14319        initScrollCache();
14320        final ScrollabilityCache scrollabilityCache = mScrollCache;
14321        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14322        if (fadeScrollbars) {
14323            scrollabilityCache.state = ScrollabilityCache.OFF;
14324        } else {
14325            scrollabilityCache.state = ScrollabilityCache.ON;
14326        }
14327    }
14328
14329    /**
14330     *
14331     * Returns true if scrollbars will fade when this view is not scrolling
14332     *
14333     * @return true if scrollbar fading is enabled
14334     *
14335     * @attr ref android.R.styleable#View_fadeScrollbars
14336     */
14337    public boolean isScrollbarFadingEnabled() {
14338        return mScrollCache != null && mScrollCache.fadeScrollBars;
14339    }
14340
14341    /**
14342     *
14343     * Returns the delay before scrollbars fade.
14344     *
14345     * @return the delay before scrollbars fade
14346     *
14347     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14348     */
14349    public int getScrollBarDefaultDelayBeforeFade() {
14350        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14351                mScrollCache.scrollBarDefaultDelayBeforeFade;
14352    }
14353
14354    /**
14355     * Define the delay before scrollbars fade.
14356     *
14357     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14358     *
14359     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14360     */
14361    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14362        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14363    }
14364
14365    /**
14366     *
14367     * Returns the scrollbar fade duration.
14368     *
14369     * @return the scrollbar fade duration
14370     *
14371     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14372     */
14373    public int getScrollBarFadeDuration() {
14374        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14375                mScrollCache.scrollBarFadeDuration;
14376    }
14377
14378    /**
14379     * Define the scrollbar fade duration.
14380     *
14381     * @param scrollBarFadeDuration - the scrollbar fade duration
14382     *
14383     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14384     */
14385    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14386        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14387    }
14388
14389    /**
14390     *
14391     * Returns the scrollbar size.
14392     *
14393     * @return the scrollbar size
14394     *
14395     * @attr ref android.R.styleable#View_scrollbarSize
14396     */
14397    public int getScrollBarSize() {
14398        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14399                mScrollCache.scrollBarSize;
14400    }
14401
14402    /**
14403     * Define the scrollbar size.
14404     *
14405     * @param scrollBarSize - the scrollbar size
14406     *
14407     * @attr ref android.R.styleable#View_scrollbarSize
14408     */
14409    public void setScrollBarSize(int scrollBarSize) {
14410        getScrollCache().scrollBarSize = scrollBarSize;
14411    }
14412
14413    /**
14414     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14415     * inset. When inset, they add to the padding of the view. And the scrollbars
14416     * can be drawn inside the padding area or on the edge of the view. For example,
14417     * if a view has a background drawable and you want to draw the scrollbars
14418     * inside the padding specified by the drawable, you can use
14419     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14420     * appear at the edge of the view, ignoring the padding, then you can use
14421     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14422     * @param style the style of the scrollbars. Should be one of
14423     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14424     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14425     * @see #SCROLLBARS_INSIDE_OVERLAY
14426     * @see #SCROLLBARS_INSIDE_INSET
14427     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14428     * @see #SCROLLBARS_OUTSIDE_INSET
14429     *
14430     * @attr ref android.R.styleable#View_scrollbarStyle
14431     */
14432    public void setScrollBarStyle(@ScrollBarStyle int style) {
14433        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14434            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14435            computeOpaqueFlags();
14436            resolvePadding();
14437        }
14438    }
14439
14440    /**
14441     * <p>Returns the current scrollbar style.</p>
14442     * @return the current scrollbar style
14443     * @see #SCROLLBARS_INSIDE_OVERLAY
14444     * @see #SCROLLBARS_INSIDE_INSET
14445     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14446     * @see #SCROLLBARS_OUTSIDE_INSET
14447     *
14448     * @attr ref android.R.styleable#View_scrollbarStyle
14449     */
14450    @ViewDebug.ExportedProperty(mapping = {
14451            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14452            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14453            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14454            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14455    })
14456    @ScrollBarStyle
14457    public int getScrollBarStyle() {
14458        return mViewFlags & SCROLLBARS_STYLE_MASK;
14459    }
14460
14461    /**
14462     * <p>Compute the horizontal range that the horizontal scrollbar
14463     * represents.</p>
14464     *
14465     * <p>The range is expressed in arbitrary units that must be the same as the
14466     * units used by {@link #computeHorizontalScrollExtent()} and
14467     * {@link #computeHorizontalScrollOffset()}.</p>
14468     *
14469     * <p>The default range is the drawing width of this view.</p>
14470     *
14471     * @return the total horizontal range represented by the horizontal
14472     *         scrollbar
14473     *
14474     * @see #computeHorizontalScrollExtent()
14475     * @see #computeHorizontalScrollOffset()
14476     * @see android.widget.ScrollBarDrawable
14477     */
14478    protected int computeHorizontalScrollRange() {
14479        return getWidth();
14480    }
14481
14482    /**
14483     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14484     * within the horizontal range. This value is used to compute the position
14485     * of the thumb within the scrollbar's track.</p>
14486     *
14487     * <p>The range is expressed in arbitrary units that must be the same as the
14488     * units used by {@link #computeHorizontalScrollRange()} and
14489     * {@link #computeHorizontalScrollExtent()}.</p>
14490     *
14491     * <p>The default offset is the scroll offset of this view.</p>
14492     *
14493     * @return the horizontal offset of the scrollbar's thumb
14494     *
14495     * @see #computeHorizontalScrollRange()
14496     * @see #computeHorizontalScrollExtent()
14497     * @see android.widget.ScrollBarDrawable
14498     */
14499    protected int computeHorizontalScrollOffset() {
14500        return mScrollX;
14501    }
14502
14503    /**
14504     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14505     * within the horizontal range. This value is used to compute the length
14506     * of the thumb within the scrollbar's track.</p>
14507     *
14508     * <p>The range is expressed in arbitrary units that must be the same as the
14509     * units used by {@link #computeHorizontalScrollRange()} and
14510     * {@link #computeHorizontalScrollOffset()}.</p>
14511     *
14512     * <p>The default extent is the drawing width of this view.</p>
14513     *
14514     * @return the horizontal extent of the scrollbar's thumb
14515     *
14516     * @see #computeHorizontalScrollRange()
14517     * @see #computeHorizontalScrollOffset()
14518     * @see android.widget.ScrollBarDrawable
14519     */
14520    protected int computeHorizontalScrollExtent() {
14521        return getWidth();
14522    }
14523
14524    /**
14525     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14526     *
14527     * <p>The range is expressed in arbitrary units that must be the same as the
14528     * units used by {@link #computeVerticalScrollExtent()} and
14529     * {@link #computeVerticalScrollOffset()}.</p>
14530     *
14531     * @return the total vertical range represented by the vertical scrollbar
14532     *
14533     * <p>The default range is the drawing height of this view.</p>
14534     *
14535     * @see #computeVerticalScrollExtent()
14536     * @see #computeVerticalScrollOffset()
14537     * @see android.widget.ScrollBarDrawable
14538     */
14539    protected int computeVerticalScrollRange() {
14540        return getHeight();
14541    }
14542
14543    /**
14544     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14545     * within the horizontal range. This value is used to compute the position
14546     * of the thumb within the scrollbar's track.</p>
14547     *
14548     * <p>The range is expressed in arbitrary units that must be the same as the
14549     * units used by {@link #computeVerticalScrollRange()} and
14550     * {@link #computeVerticalScrollExtent()}.</p>
14551     *
14552     * <p>The default offset is the scroll offset of this view.</p>
14553     *
14554     * @return the vertical offset of the scrollbar's thumb
14555     *
14556     * @see #computeVerticalScrollRange()
14557     * @see #computeVerticalScrollExtent()
14558     * @see android.widget.ScrollBarDrawable
14559     */
14560    protected int computeVerticalScrollOffset() {
14561        return mScrollY;
14562    }
14563
14564    /**
14565     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14566     * within the vertical range. This value is used to compute the length
14567     * of the thumb within the scrollbar's track.</p>
14568     *
14569     * <p>The range is expressed in arbitrary units that must be the same as the
14570     * units used by {@link #computeVerticalScrollRange()} and
14571     * {@link #computeVerticalScrollOffset()}.</p>
14572     *
14573     * <p>The default extent is the drawing height of this view.</p>
14574     *
14575     * @return the vertical extent of the scrollbar's thumb
14576     *
14577     * @see #computeVerticalScrollRange()
14578     * @see #computeVerticalScrollOffset()
14579     * @see android.widget.ScrollBarDrawable
14580     */
14581    protected int computeVerticalScrollExtent() {
14582        return getHeight();
14583    }
14584
14585    /**
14586     * Check if this view can be scrolled horizontally in a certain direction.
14587     *
14588     * @param direction Negative to check scrolling left, positive to check scrolling right.
14589     * @return true if this view can be scrolled in the specified direction, false otherwise.
14590     */
14591    public boolean canScrollHorizontally(int direction) {
14592        final int offset = computeHorizontalScrollOffset();
14593        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14594        if (range == 0) return false;
14595        if (direction < 0) {
14596            return offset > 0;
14597        } else {
14598            return offset < range - 1;
14599        }
14600    }
14601
14602    /**
14603     * Check if this view can be scrolled vertically in a certain direction.
14604     *
14605     * @param direction Negative to check scrolling up, positive to check scrolling down.
14606     * @return true if this view can be scrolled in the specified direction, false otherwise.
14607     */
14608    public boolean canScrollVertically(int direction) {
14609        final int offset = computeVerticalScrollOffset();
14610        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14611        if (range == 0) return false;
14612        if (direction < 0) {
14613            return offset > 0;
14614        } else {
14615            return offset < range - 1;
14616        }
14617    }
14618
14619    void getScrollIndicatorBounds(@NonNull Rect out) {
14620        out.left = mScrollX;
14621        out.right = mScrollX + mRight - mLeft;
14622        out.top = mScrollY;
14623        out.bottom = mScrollY + mBottom - mTop;
14624    }
14625
14626    private void onDrawScrollIndicators(Canvas c) {
14627        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14628            // No scroll indicators enabled.
14629            return;
14630        }
14631
14632        final Drawable dr = mScrollIndicatorDrawable;
14633        if (dr == null) {
14634            // Scroll indicators aren't supported here.
14635            return;
14636        }
14637
14638        final int h = dr.getIntrinsicHeight();
14639        final int w = dr.getIntrinsicWidth();
14640        final Rect rect = mAttachInfo.mTmpInvalRect;
14641        getScrollIndicatorBounds(rect);
14642
14643        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14644            final boolean canScrollUp = canScrollVertically(-1);
14645            if (canScrollUp) {
14646                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14647                dr.draw(c);
14648            }
14649        }
14650
14651        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14652            final boolean canScrollDown = canScrollVertically(1);
14653            if (canScrollDown) {
14654                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14655                dr.draw(c);
14656            }
14657        }
14658
14659        final int leftRtl;
14660        final int rightRtl;
14661        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14662            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14663            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14664        } else {
14665            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14666            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14667        }
14668
14669        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14670        if ((mPrivateFlags3 & leftMask) != 0) {
14671            final boolean canScrollLeft = canScrollHorizontally(-1);
14672            if (canScrollLeft) {
14673                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14674                dr.draw(c);
14675            }
14676        }
14677
14678        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14679        if ((mPrivateFlags3 & rightMask) != 0) {
14680            final boolean canScrollRight = canScrollHorizontally(1);
14681            if (canScrollRight) {
14682                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14683                dr.draw(c);
14684            }
14685        }
14686    }
14687
14688    private void getHorizontalScrollBarBounds(Rect bounds) {
14689        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14690        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14691                && !isVerticalScrollBarHidden();
14692        final int size = getHorizontalScrollbarHeight();
14693        final int verticalScrollBarGap = drawVerticalScrollBar ?
14694                getVerticalScrollbarWidth() : 0;
14695        final int width = mRight - mLeft;
14696        final int height = mBottom - mTop;
14697        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14698        bounds.left = mScrollX + (mPaddingLeft & inside);
14699        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14700        bounds.bottom = bounds.top + size;
14701    }
14702
14703    private void getVerticalScrollBarBounds(Rect bounds) {
14704        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14705        final int size = getVerticalScrollbarWidth();
14706        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14707        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14708            verticalScrollbarPosition = isLayoutRtl() ?
14709                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14710        }
14711        final int width = mRight - mLeft;
14712        final int height = mBottom - mTop;
14713        switch (verticalScrollbarPosition) {
14714            default:
14715            case SCROLLBAR_POSITION_RIGHT:
14716                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14717                break;
14718            case SCROLLBAR_POSITION_LEFT:
14719                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14720                break;
14721        }
14722        bounds.top = mScrollY + (mPaddingTop & inside);
14723        bounds.right = bounds.left + size;
14724        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14725    }
14726
14727    /**
14728     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14729     * scrollbars are painted only if they have been awakened first.</p>
14730     *
14731     * @param canvas the canvas on which to draw the scrollbars
14732     *
14733     * @see #awakenScrollBars(int)
14734     */
14735    protected final void onDrawScrollBars(Canvas canvas) {
14736        // scrollbars are drawn only when the animation is running
14737        final ScrollabilityCache cache = mScrollCache;
14738        if (cache != null) {
14739
14740            int state = cache.state;
14741
14742            if (state == ScrollabilityCache.OFF) {
14743                return;
14744            }
14745
14746            boolean invalidate = false;
14747
14748            if (state == ScrollabilityCache.FADING) {
14749                // We're fading -- get our fade interpolation
14750                if (cache.interpolatorValues == null) {
14751                    cache.interpolatorValues = new float[1];
14752                }
14753
14754                float[] values = cache.interpolatorValues;
14755
14756                // Stops the animation if we're done
14757                if (cache.scrollBarInterpolator.timeToValues(values) ==
14758                        Interpolator.Result.FREEZE_END) {
14759                    cache.state = ScrollabilityCache.OFF;
14760                } else {
14761                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14762                }
14763
14764                // This will make the scroll bars inval themselves after
14765                // drawing. We only want this when we're fading so that
14766                // we prevent excessive redraws
14767                invalidate = true;
14768            } else {
14769                // We're just on -- but we may have been fading before so
14770                // reset alpha
14771                cache.scrollBar.mutate().setAlpha(255);
14772            }
14773
14774            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14775            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14776                    && !isVerticalScrollBarHidden();
14777
14778            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14779                final ScrollBarDrawable scrollBar = cache.scrollBar;
14780
14781                if (drawHorizontalScrollBar) {
14782                    scrollBar.setParameters(computeHorizontalScrollRange(),
14783                                            computeHorizontalScrollOffset(),
14784                                            computeHorizontalScrollExtent(), false);
14785                    final Rect bounds = cache.mScrollBarBounds;
14786                    getHorizontalScrollBarBounds(bounds);
14787                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14788                            bounds.right, bounds.bottom);
14789                    if (invalidate) {
14790                        invalidate(bounds);
14791                    }
14792                }
14793
14794                if (drawVerticalScrollBar) {
14795                    scrollBar.setParameters(computeVerticalScrollRange(),
14796                                            computeVerticalScrollOffset(),
14797                                            computeVerticalScrollExtent(), true);
14798                    final Rect bounds = cache.mScrollBarBounds;
14799                    getVerticalScrollBarBounds(bounds);
14800                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14801                            bounds.right, bounds.bottom);
14802                    if (invalidate) {
14803                        invalidate(bounds);
14804                    }
14805                }
14806            }
14807        }
14808    }
14809
14810    /**
14811     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14812     * FastScroller is visible.
14813     * @return whether to temporarily hide the vertical scrollbar
14814     * @hide
14815     */
14816    protected boolean isVerticalScrollBarHidden() {
14817        return false;
14818    }
14819
14820    /**
14821     * <p>Draw the horizontal scrollbar if
14822     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14823     *
14824     * @param canvas the canvas on which to draw the scrollbar
14825     * @param scrollBar the scrollbar's drawable
14826     *
14827     * @see #isHorizontalScrollBarEnabled()
14828     * @see #computeHorizontalScrollRange()
14829     * @see #computeHorizontalScrollExtent()
14830     * @see #computeHorizontalScrollOffset()
14831     * @see android.widget.ScrollBarDrawable
14832     * @hide
14833     */
14834    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14835            int l, int t, int r, int b) {
14836        scrollBar.setBounds(l, t, r, b);
14837        scrollBar.draw(canvas);
14838    }
14839
14840    /**
14841     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14842     * returns true.</p>
14843     *
14844     * @param canvas the canvas on which to draw the scrollbar
14845     * @param scrollBar the scrollbar's drawable
14846     *
14847     * @see #isVerticalScrollBarEnabled()
14848     * @see #computeVerticalScrollRange()
14849     * @see #computeVerticalScrollExtent()
14850     * @see #computeVerticalScrollOffset()
14851     * @see android.widget.ScrollBarDrawable
14852     * @hide
14853     */
14854    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14855            int l, int t, int r, int b) {
14856        scrollBar.setBounds(l, t, r, b);
14857        scrollBar.draw(canvas);
14858    }
14859
14860    /**
14861     * Implement this to do your drawing.
14862     *
14863     * @param canvas the canvas on which the background will be drawn
14864     */
14865    protected void onDraw(Canvas canvas) {
14866    }
14867
14868    /*
14869     * Caller is responsible for calling requestLayout if necessary.
14870     * (This allows addViewInLayout to not request a new layout.)
14871     */
14872    void assignParent(ViewParent parent) {
14873        if (mParent == null) {
14874            mParent = parent;
14875        } else if (parent == null) {
14876            mParent = null;
14877        } else {
14878            throw new RuntimeException("view " + this + " being added, but"
14879                    + " it already has a parent");
14880        }
14881    }
14882
14883    /**
14884     * This is called when the view is attached to a window.  At this point it
14885     * has a Surface and will start drawing.  Note that this function is
14886     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14887     * however it may be called any time before the first onDraw -- including
14888     * before or after {@link #onMeasure(int, int)}.
14889     *
14890     * @see #onDetachedFromWindow()
14891     */
14892    @CallSuper
14893    protected void onAttachedToWindow() {
14894        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14895            mParent.requestTransparentRegion(this);
14896        }
14897
14898        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14899
14900        jumpDrawablesToCurrentState();
14901
14902        resetSubtreeAccessibilityStateChanged();
14903
14904        // rebuild, since Outline not maintained while View is detached
14905        rebuildOutline();
14906
14907        if (isFocused()) {
14908            InputMethodManager imm = InputMethodManager.peekInstance();
14909            if (imm != null) {
14910                imm.focusIn(this);
14911            }
14912        }
14913    }
14914
14915    /**
14916     * Resolve all RTL related properties.
14917     *
14918     * @return true if resolution of RTL properties has been done
14919     *
14920     * @hide
14921     */
14922    public boolean resolveRtlPropertiesIfNeeded() {
14923        if (!needRtlPropertiesResolution()) return false;
14924
14925        // Order is important here: LayoutDirection MUST be resolved first
14926        if (!isLayoutDirectionResolved()) {
14927            resolveLayoutDirection();
14928            resolveLayoutParams();
14929        }
14930        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14931        if (!isTextDirectionResolved()) {
14932            resolveTextDirection();
14933        }
14934        if (!isTextAlignmentResolved()) {
14935            resolveTextAlignment();
14936        }
14937        // Should resolve Drawables before Padding because we need the layout direction of the
14938        // Drawable to correctly resolve Padding.
14939        if (!areDrawablesResolved()) {
14940            resolveDrawables();
14941        }
14942        if (!isPaddingResolved()) {
14943            resolvePadding();
14944        }
14945        onRtlPropertiesChanged(getLayoutDirection());
14946        return true;
14947    }
14948
14949    /**
14950     * Reset resolution of all RTL related properties.
14951     *
14952     * @hide
14953     */
14954    public void resetRtlProperties() {
14955        resetResolvedLayoutDirection();
14956        resetResolvedTextDirection();
14957        resetResolvedTextAlignment();
14958        resetResolvedPadding();
14959        resetResolvedDrawables();
14960    }
14961
14962    /**
14963     * @see #onScreenStateChanged(int)
14964     */
14965    void dispatchScreenStateChanged(int screenState) {
14966        onScreenStateChanged(screenState);
14967    }
14968
14969    /**
14970     * This method is called whenever the state of the screen this view is
14971     * attached to changes. A state change will usually occurs when the screen
14972     * turns on or off (whether it happens automatically or the user does it
14973     * manually.)
14974     *
14975     * @param screenState The new state of the screen. Can be either
14976     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14977     */
14978    public void onScreenStateChanged(int screenState) {
14979    }
14980
14981    /**
14982     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
14983     */
14984    private boolean hasRtlSupport() {
14985        return mContext.getApplicationInfo().hasRtlSupport();
14986    }
14987
14988    /**
14989     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
14990     * RTL not supported)
14991     */
14992    private boolean isRtlCompatibilityMode() {
14993        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
14994        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
14995    }
14996
14997    /**
14998     * @return true if RTL properties need resolution.
14999     *
15000     */
15001    private boolean needRtlPropertiesResolution() {
15002        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15003    }
15004
15005    /**
15006     * Called when any RTL property (layout direction or text direction or text alignment) has
15007     * been changed.
15008     *
15009     * Subclasses need to override this method to take care of cached information that depends on the
15010     * resolved layout direction, or to inform child views that inherit their layout direction.
15011     *
15012     * The default implementation does nothing.
15013     *
15014     * @param layoutDirection the direction of the layout
15015     *
15016     * @see #LAYOUT_DIRECTION_LTR
15017     * @see #LAYOUT_DIRECTION_RTL
15018     */
15019    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15020    }
15021
15022    /**
15023     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15024     * that the parent directionality can and will be resolved before its children.
15025     *
15026     * @return true if resolution has been done, false otherwise.
15027     *
15028     * @hide
15029     */
15030    public boolean resolveLayoutDirection() {
15031        // Clear any previous layout direction resolution
15032        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15033
15034        if (hasRtlSupport()) {
15035            // Set resolved depending on layout direction
15036            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15037                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15038                case LAYOUT_DIRECTION_INHERIT:
15039                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15040                    // later to get the correct resolved value
15041                    if (!canResolveLayoutDirection()) return false;
15042
15043                    // Parent has not yet resolved, LTR is still the default
15044                    try {
15045                        if (!mParent.isLayoutDirectionResolved()) return false;
15046
15047                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15048                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15049                        }
15050                    } catch (AbstractMethodError e) {
15051                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15052                                " does not fully implement ViewParent", e);
15053                    }
15054                    break;
15055                case LAYOUT_DIRECTION_RTL:
15056                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15057                    break;
15058                case LAYOUT_DIRECTION_LOCALE:
15059                    if((LAYOUT_DIRECTION_RTL ==
15060                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15061                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15062                    }
15063                    break;
15064                default:
15065                    // Nothing to do, LTR by default
15066            }
15067        }
15068
15069        // Set to resolved
15070        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15071        return true;
15072    }
15073
15074    /**
15075     * Check if layout direction resolution can be done.
15076     *
15077     * @return true if layout direction resolution can be done otherwise return false.
15078     */
15079    public boolean canResolveLayoutDirection() {
15080        switch (getRawLayoutDirection()) {
15081            case LAYOUT_DIRECTION_INHERIT:
15082                if (mParent != null) {
15083                    try {
15084                        return mParent.canResolveLayoutDirection();
15085                    } catch (AbstractMethodError e) {
15086                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15087                                " does not fully implement ViewParent", e);
15088                    }
15089                }
15090                return false;
15091
15092            default:
15093                return true;
15094        }
15095    }
15096
15097    /**
15098     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15099     * {@link #onMeasure(int, int)}.
15100     *
15101     * @hide
15102     */
15103    public void resetResolvedLayoutDirection() {
15104        // Reset the current resolved bits
15105        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15106    }
15107
15108    /**
15109     * @return true if the layout direction is inherited.
15110     *
15111     * @hide
15112     */
15113    public boolean isLayoutDirectionInherited() {
15114        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15115    }
15116
15117    /**
15118     * @return true if layout direction has been resolved.
15119     */
15120    public boolean isLayoutDirectionResolved() {
15121        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15122    }
15123
15124    /**
15125     * Return if padding has been resolved
15126     *
15127     * @hide
15128     */
15129    boolean isPaddingResolved() {
15130        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15131    }
15132
15133    /**
15134     * Resolves padding depending on layout direction, if applicable, and
15135     * recomputes internal padding values to adjust for scroll bars.
15136     *
15137     * @hide
15138     */
15139    public void resolvePadding() {
15140        final int resolvedLayoutDirection = getLayoutDirection();
15141
15142        if (!isRtlCompatibilityMode()) {
15143            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15144            // If start / end padding are defined, they will be resolved (hence overriding) to
15145            // left / right or right / left depending on the resolved layout direction.
15146            // If start / end padding are not defined, use the left / right ones.
15147            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15148                Rect padding = sThreadLocal.get();
15149                if (padding == null) {
15150                    padding = new Rect();
15151                    sThreadLocal.set(padding);
15152                }
15153                mBackground.getPadding(padding);
15154                if (!mLeftPaddingDefined) {
15155                    mUserPaddingLeftInitial = padding.left;
15156                }
15157                if (!mRightPaddingDefined) {
15158                    mUserPaddingRightInitial = padding.right;
15159                }
15160            }
15161            switch (resolvedLayoutDirection) {
15162                case LAYOUT_DIRECTION_RTL:
15163                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15164                        mUserPaddingRight = mUserPaddingStart;
15165                    } else {
15166                        mUserPaddingRight = mUserPaddingRightInitial;
15167                    }
15168                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15169                        mUserPaddingLeft = mUserPaddingEnd;
15170                    } else {
15171                        mUserPaddingLeft = mUserPaddingLeftInitial;
15172                    }
15173                    break;
15174                case LAYOUT_DIRECTION_LTR:
15175                default:
15176                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15177                        mUserPaddingLeft = mUserPaddingStart;
15178                    } else {
15179                        mUserPaddingLeft = mUserPaddingLeftInitial;
15180                    }
15181                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15182                        mUserPaddingRight = mUserPaddingEnd;
15183                    } else {
15184                        mUserPaddingRight = mUserPaddingRightInitial;
15185                    }
15186            }
15187
15188            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15189        }
15190
15191        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15192        onRtlPropertiesChanged(resolvedLayoutDirection);
15193
15194        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15195    }
15196
15197    /**
15198     * Reset the resolved layout direction.
15199     *
15200     * @hide
15201     */
15202    public void resetResolvedPadding() {
15203        resetResolvedPaddingInternal();
15204    }
15205
15206    /**
15207     * Used when we only want to reset *this* view's padding and not trigger overrides
15208     * in ViewGroup that reset children too.
15209     */
15210    void resetResolvedPaddingInternal() {
15211        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15212    }
15213
15214    /**
15215     * This is called when the view is detached from a window.  At this point it
15216     * no longer has a surface for drawing.
15217     *
15218     * @see #onAttachedToWindow()
15219     */
15220    @CallSuper
15221    protected void onDetachedFromWindow() {
15222    }
15223
15224    /**
15225     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15226     * after onDetachedFromWindow().
15227     *
15228     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15229     * The super method should be called at the end of the overridden method to ensure
15230     * subclasses are destroyed first
15231     *
15232     * @hide
15233     */
15234    @CallSuper
15235    protected void onDetachedFromWindowInternal() {
15236        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15237        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15238        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15239
15240        removeUnsetPressCallback();
15241        removeLongPressCallback();
15242        removePerformClickCallback();
15243        removeSendViewScrolledAccessibilityEventCallback();
15244        stopNestedScroll();
15245
15246        // Anything that started animating right before detach should already
15247        // be in its final state when re-attached.
15248        jumpDrawablesToCurrentState();
15249
15250        destroyDrawingCache();
15251
15252        cleanupDraw();
15253        releasePointerCapture();
15254        mCurrentAnimation = null;
15255    }
15256
15257    private void cleanupDraw() {
15258        resetDisplayList();
15259        if (mAttachInfo != null) {
15260            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15261        }
15262    }
15263
15264    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15265    }
15266
15267    /**
15268     * @return The number of times this view has been attached to a window
15269     */
15270    protected int getWindowAttachCount() {
15271        return mWindowAttachCount;
15272    }
15273
15274    /**
15275     * Retrieve a unique token identifying the window this view is attached to.
15276     * @return Return the window's token for use in
15277     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15278     */
15279    public IBinder getWindowToken() {
15280        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15281    }
15282
15283    /**
15284     * Retrieve the {@link WindowId} for the window this view is
15285     * currently attached to.
15286     */
15287    public WindowId getWindowId() {
15288        if (mAttachInfo == null) {
15289            return null;
15290        }
15291        if (mAttachInfo.mWindowId == null) {
15292            try {
15293                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15294                        mAttachInfo.mWindowToken);
15295                mAttachInfo.mWindowId = new WindowId(
15296                        mAttachInfo.mIWindowId);
15297            } catch (RemoteException e) {
15298            }
15299        }
15300        return mAttachInfo.mWindowId;
15301    }
15302
15303    /**
15304     * Retrieve a unique token identifying the top-level "real" window of
15305     * the window that this view is attached to.  That is, this is like
15306     * {@link #getWindowToken}, except if the window this view in is a panel
15307     * window (attached to another containing window), then the token of
15308     * the containing window is returned instead.
15309     *
15310     * @return Returns the associated window token, either
15311     * {@link #getWindowToken()} or the containing window's token.
15312     */
15313    public IBinder getApplicationWindowToken() {
15314        AttachInfo ai = mAttachInfo;
15315        if (ai != null) {
15316            IBinder appWindowToken = ai.mPanelParentWindowToken;
15317            if (appWindowToken == null) {
15318                appWindowToken = ai.mWindowToken;
15319            }
15320            return appWindowToken;
15321        }
15322        return null;
15323    }
15324
15325    /**
15326     * Gets the logical display to which the view's window has been attached.
15327     *
15328     * @return The logical display, or null if the view is not currently attached to a window.
15329     */
15330    public Display getDisplay() {
15331        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15332    }
15333
15334    /**
15335     * Retrieve private session object this view hierarchy is using to
15336     * communicate with the window manager.
15337     * @return the session object to communicate with the window manager
15338     */
15339    /*package*/ IWindowSession getWindowSession() {
15340        return mAttachInfo != null ? mAttachInfo.mSession : null;
15341    }
15342
15343    /**
15344     * Return the visibility value of the least visible component passed.
15345     */
15346    int combineVisibility(int vis1, int vis2) {
15347        // This works because VISIBLE < INVISIBLE < GONE.
15348        return Math.max(vis1, vis2);
15349    }
15350
15351    /**
15352     * @param info the {@link android.view.View.AttachInfo} to associated with
15353     *        this view
15354     */
15355    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15356        mAttachInfo = info;
15357        if (mOverlay != null) {
15358            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15359        }
15360        mWindowAttachCount++;
15361        // We will need to evaluate the drawable state at least once.
15362        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15363        if (mFloatingTreeObserver != null) {
15364            info.mTreeObserver.merge(mFloatingTreeObserver);
15365            mFloatingTreeObserver = null;
15366        }
15367
15368        registerPendingFrameMetricsObservers();
15369
15370        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15371            mAttachInfo.mScrollContainers.add(this);
15372            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15373        }
15374        // Transfer all pending runnables.
15375        if (mRunQueue != null) {
15376            mRunQueue.executeActions(info.mHandler);
15377            mRunQueue = null;
15378        }
15379        performCollectViewAttributes(mAttachInfo, visibility);
15380        onAttachedToWindow();
15381
15382        ListenerInfo li = mListenerInfo;
15383        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15384                li != null ? li.mOnAttachStateChangeListeners : null;
15385        if (listeners != null && listeners.size() > 0) {
15386            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15387            // perform the dispatching. The iterator is a safe guard against listeners that
15388            // could mutate the list by calling the various add/remove methods. This prevents
15389            // the array from being modified while we iterate it.
15390            for (OnAttachStateChangeListener listener : listeners) {
15391                listener.onViewAttachedToWindow(this);
15392            }
15393        }
15394
15395        int vis = info.mWindowVisibility;
15396        if (vis != GONE) {
15397            onWindowVisibilityChanged(vis);
15398            if (isShown()) {
15399                // Calling onVisibilityChanged directly here since the subtree will also
15400                // receive dispatchAttachedToWindow and this same call
15401                onVisibilityAggregated(vis == VISIBLE);
15402            }
15403        }
15404
15405        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15406        // As all views in the subtree will already receive dispatchAttachedToWindow
15407        // traversing the subtree again here is not desired.
15408        onVisibilityChanged(this, visibility);
15409
15410        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15411            // If nobody has evaluated the drawable state yet, then do it now.
15412            refreshDrawableState();
15413        }
15414        needGlobalAttributesUpdate(false);
15415    }
15416
15417    void dispatchDetachedFromWindow() {
15418        AttachInfo info = mAttachInfo;
15419        if (info != null) {
15420            int vis = info.mWindowVisibility;
15421            if (vis != GONE) {
15422                onWindowVisibilityChanged(GONE);
15423                if (isShown()) {
15424                    // Invoking onVisibilityAggregated directly here since the subtree
15425                    // will also receive detached from window
15426                    onVisibilityAggregated(false);
15427                }
15428            }
15429        }
15430
15431        onDetachedFromWindow();
15432        onDetachedFromWindowInternal();
15433
15434        InputMethodManager imm = InputMethodManager.peekInstance();
15435        if (imm != null) {
15436            imm.onViewDetachedFromWindow(this);
15437        }
15438
15439        ListenerInfo li = mListenerInfo;
15440        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15441                li != null ? li.mOnAttachStateChangeListeners : null;
15442        if (listeners != null && listeners.size() > 0) {
15443            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15444            // perform the dispatching. The iterator is a safe guard against listeners that
15445            // could mutate the list by calling the various add/remove methods. This prevents
15446            // the array from being modified while we iterate it.
15447            for (OnAttachStateChangeListener listener : listeners) {
15448                listener.onViewDetachedFromWindow(this);
15449            }
15450        }
15451
15452        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15453            mAttachInfo.mScrollContainers.remove(this);
15454            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15455        }
15456
15457        mAttachInfo = null;
15458        if (mOverlay != null) {
15459            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15460        }
15461    }
15462
15463    /**
15464     * Cancel any deferred high-level input events that were previously posted to the event queue.
15465     *
15466     * <p>Many views post high-level events such as click handlers to the event queue
15467     * to run deferred in order to preserve a desired user experience - clearing visible
15468     * pressed states before executing, etc. This method will abort any events of this nature
15469     * that are currently in flight.</p>
15470     *
15471     * <p>Custom views that generate their own high-level deferred input events should override
15472     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15473     *
15474     * <p>This will also cancel pending input events for any child views.</p>
15475     *
15476     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15477     * This will not impact newer events posted after this call that may occur as a result of
15478     * lower-level input events still waiting in the queue. If you are trying to prevent
15479     * double-submitted  events for the duration of some sort of asynchronous transaction
15480     * you should also take other steps to protect against unexpected double inputs e.g. calling
15481     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15482     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15483     */
15484    public final void cancelPendingInputEvents() {
15485        dispatchCancelPendingInputEvents();
15486    }
15487
15488    /**
15489     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15490     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15491     */
15492    void dispatchCancelPendingInputEvents() {
15493        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15494        onCancelPendingInputEvents();
15495        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15496            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15497                    " did not call through to super.onCancelPendingInputEvents()");
15498        }
15499    }
15500
15501    /**
15502     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15503     * a parent view.
15504     *
15505     * <p>This method is responsible for removing any pending high-level input events that were
15506     * posted to the event queue to run later. Custom view classes that post their own deferred
15507     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15508     * {@link android.os.Handler} should override this method, call
15509     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15510     * </p>
15511     */
15512    public void onCancelPendingInputEvents() {
15513        removePerformClickCallback();
15514        cancelLongPress();
15515        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15516    }
15517
15518    /**
15519     * Store this view hierarchy's frozen state into the given container.
15520     *
15521     * @param container The SparseArray in which to save the view's state.
15522     *
15523     * @see #restoreHierarchyState(android.util.SparseArray)
15524     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15525     * @see #onSaveInstanceState()
15526     */
15527    public void saveHierarchyState(SparseArray<Parcelable> container) {
15528        dispatchSaveInstanceState(container);
15529    }
15530
15531    /**
15532     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15533     * this view and its children. May be overridden to modify how freezing happens to a
15534     * view's children; for example, some views may want to not store state for their children.
15535     *
15536     * @param container The SparseArray in which to save the view's state.
15537     *
15538     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15539     * @see #saveHierarchyState(android.util.SparseArray)
15540     * @see #onSaveInstanceState()
15541     */
15542    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15543        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15544            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15545            Parcelable state = onSaveInstanceState();
15546            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15547                throw new IllegalStateException(
15548                        "Derived class did not call super.onSaveInstanceState()");
15549            }
15550            if (state != null) {
15551                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15552                // + ": " + state);
15553                container.put(mID, state);
15554            }
15555        }
15556    }
15557
15558    /**
15559     * Hook allowing a view to generate a representation of its internal state
15560     * that can later be used to create a new instance with that same state.
15561     * This state should only contain information that is not persistent or can
15562     * not be reconstructed later. For example, you will never store your
15563     * current position on screen because that will be computed again when a
15564     * new instance of the view is placed in its view hierarchy.
15565     * <p>
15566     * Some examples of things you may store here: the current cursor position
15567     * in a text view (but usually not the text itself since that is stored in a
15568     * content provider or other persistent storage), the currently selected
15569     * item in a list view.
15570     *
15571     * @return Returns a Parcelable object containing the view's current dynamic
15572     *         state, or null if there is nothing interesting to save. The
15573     *         default implementation returns null.
15574     * @see #onRestoreInstanceState(android.os.Parcelable)
15575     * @see #saveHierarchyState(android.util.SparseArray)
15576     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15577     * @see #setSaveEnabled(boolean)
15578     */
15579    @CallSuper
15580    protected Parcelable onSaveInstanceState() {
15581        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15582        if (mStartActivityRequestWho != null) {
15583            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15584            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15585            return state;
15586        }
15587        return BaseSavedState.EMPTY_STATE;
15588    }
15589
15590    /**
15591     * Restore this view hierarchy's frozen state from the given container.
15592     *
15593     * @param container The SparseArray which holds previously frozen states.
15594     *
15595     * @see #saveHierarchyState(android.util.SparseArray)
15596     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15597     * @see #onRestoreInstanceState(android.os.Parcelable)
15598     */
15599    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15600        dispatchRestoreInstanceState(container);
15601    }
15602
15603    /**
15604     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15605     * state for this view and its children. May be overridden to modify how restoring
15606     * happens to a view's children; for example, some views may want to not store state
15607     * for their children.
15608     *
15609     * @param container The SparseArray which holds previously saved state.
15610     *
15611     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15612     * @see #restoreHierarchyState(android.util.SparseArray)
15613     * @see #onRestoreInstanceState(android.os.Parcelable)
15614     */
15615    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15616        if (mID != NO_ID) {
15617            Parcelable state = container.get(mID);
15618            if (state != null) {
15619                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15620                // + ": " + state);
15621                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15622                onRestoreInstanceState(state);
15623                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15624                    throw new IllegalStateException(
15625                            "Derived class did not call super.onRestoreInstanceState()");
15626                }
15627            }
15628        }
15629    }
15630
15631    /**
15632     * Hook allowing a view to re-apply a representation of its internal state that had previously
15633     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15634     * null state.
15635     *
15636     * @param state The frozen state that had previously been returned by
15637     *        {@link #onSaveInstanceState}.
15638     *
15639     * @see #onSaveInstanceState()
15640     * @see #restoreHierarchyState(android.util.SparseArray)
15641     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15642     */
15643    @CallSuper
15644    protected void onRestoreInstanceState(Parcelable state) {
15645        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15646        if (state != null && !(state instanceof AbsSavedState)) {
15647            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15648                    + "received " + state.getClass().toString() + " instead. This usually happens "
15649                    + "when two views of different type have the same id in the same hierarchy. "
15650                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15651                    + "other views do not use the same id.");
15652        }
15653        if (state != null && state instanceof BaseSavedState) {
15654            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15655        }
15656    }
15657
15658    /**
15659     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15660     *
15661     * @return the drawing start time in milliseconds
15662     */
15663    public long getDrawingTime() {
15664        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15665    }
15666
15667    /**
15668     * <p>Enables or disables the duplication of the parent's state into this view. When
15669     * duplication is enabled, this view gets its drawable state from its parent rather
15670     * than from its own internal properties.</p>
15671     *
15672     * <p>Note: in the current implementation, setting this property to true after the
15673     * view was added to a ViewGroup might have no effect at all. This property should
15674     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15675     *
15676     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15677     * property is enabled, an exception will be thrown.</p>
15678     *
15679     * <p>Note: if the child view uses and updates additional states which are unknown to the
15680     * parent, these states should not be affected by this method.</p>
15681     *
15682     * @param enabled True to enable duplication of the parent's drawable state, false
15683     *                to disable it.
15684     *
15685     * @see #getDrawableState()
15686     * @see #isDuplicateParentStateEnabled()
15687     */
15688    public void setDuplicateParentStateEnabled(boolean enabled) {
15689        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15690    }
15691
15692    /**
15693     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15694     *
15695     * @return True if this view's drawable state is duplicated from the parent,
15696     *         false otherwise
15697     *
15698     * @see #getDrawableState()
15699     * @see #setDuplicateParentStateEnabled(boolean)
15700     */
15701    public boolean isDuplicateParentStateEnabled() {
15702        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15703    }
15704
15705    /**
15706     * <p>Specifies the type of layer backing this view. The layer can be
15707     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15708     * {@link #LAYER_TYPE_HARDWARE}.</p>
15709     *
15710     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15711     * instance that controls how the layer is composed on screen. The following
15712     * properties of the paint are taken into account when composing the layer:</p>
15713     * <ul>
15714     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15715     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15716     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15717     * </ul>
15718     *
15719     * <p>If this view has an alpha value set to < 1.0 by calling
15720     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15721     * by this view's alpha value.</p>
15722     *
15723     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15724     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15725     * for more information on when and how to use layers.</p>
15726     *
15727     * @param layerType The type of layer to use with this view, must be one of
15728     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15729     *        {@link #LAYER_TYPE_HARDWARE}
15730     * @param paint The paint used to compose the layer. This argument is optional
15731     *        and can be null. It is ignored when the layer type is
15732     *        {@link #LAYER_TYPE_NONE}
15733     *
15734     * @see #getLayerType()
15735     * @see #LAYER_TYPE_NONE
15736     * @see #LAYER_TYPE_SOFTWARE
15737     * @see #LAYER_TYPE_HARDWARE
15738     * @see #setAlpha(float)
15739     *
15740     * @attr ref android.R.styleable#View_layerType
15741     */
15742    public void setLayerType(int layerType, @Nullable Paint paint) {
15743        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15744            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15745                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15746        }
15747
15748        boolean typeChanged = mRenderNode.setLayerType(layerType);
15749
15750        if (!typeChanged) {
15751            setLayerPaint(paint);
15752            return;
15753        }
15754
15755        if (layerType != LAYER_TYPE_SOFTWARE) {
15756            // Destroy any previous software drawing cache if present
15757            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15758            // drawing cache created in View#draw when drawing to a SW canvas.
15759            destroyDrawingCache();
15760        }
15761
15762        mLayerType = layerType;
15763        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15764        mRenderNode.setLayerPaint(mLayerPaint);
15765
15766        // draw() behaves differently if we are on a layer, so we need to
15767        // invalidate() here
15768        invalidateParentCaches();
15769        invalidate(true);
15770    }
15771
15772    /**
15773     * Updates the {@link Paint} object used with the current layer (used only if the current
15774     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15775     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15776     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15777     * ensure that the view gets redrawn immediately.
15778     *
15779     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15780     * instance that controls how the layer is composed on screen. The following
15781     * properties of the paint are taken into account when composing the layer:</p>
15782     * <ul>
15783     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15784     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15785     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15786     * </ul>
15787     *
15788     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15789     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15790     *
15791     * @param paint The paint used to compose the layer. This argument is optional
15792     *        and can be null. It is ignored when the layer type is
15793     *        {@link #LAYER_TYPE_NONE}
15794     *
15795     * @see #setLayerType(int, android.graphics.Paint)
15796     */
15797    public void setLayerPaint(@Nullable Paint paint) {
15798        int layerType = getLayerType();
15799        if (layerType != LAYER_TYPE_NONE) {
15800            mLayerPaint = paint;
15801            if (layerType == LAYER_TYPE_HARDWARE) {
15802                if (mRenderNode.setLayerPaint(paint)) {
15803                    invalidateViewProperty(false, false);
15804                }
15805            } else {
15806                invalidate();
15807            }
15808        }
15809    }
15810
15811    /**
15812     * Indicates what type of layer is currently associated with this view. By default
15813     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15814     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15815     * for more information on the different types of layers.
15816     *
15817     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15818     *         {@link #LAYER_TYPE_HARDWARE}
15819     *
15820     * @see #setLayerType(int, android.graphics.Paint)
15821     * @see #buildLayer()
15822     * @see #LAYER_TYPE_NONE
15823     * @see #LAYER_TYPE_SOFTWARE
15824     * @see #LAYER_TYPE_HARDWARE
15825     */
15826    public int getLayerType() {
15827        return mLayerType;
15828    }
15829
15830    /**
15831     * Forces this view's layer to be created and this view to be rendered
15832     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15833     * invoking this method will have no effect.
15834     *
15835     * This method can for instance be used to render a view into its layer before
15836     * starting an animation. If this view is complex, rendering into the layer
15837     * before starting the animation will avoid skipping frames.
15838     *
15839     * @throws IllegalStateException If this view is not attached to a window
15840     *
15841     * @see #setLayerType(int, android.graphics.Paint)
15842     */
15843    public void buildLayer() {
15844        if (mLayerType == LAYER_TYPE_NONE) return;
15845
15846        final AttachInfo attachInfo = mAttachInfo;
15847        if (attachInfo == null) {
15848            throw new IllegalStateException("This view must be attached to a window first");
15849        }
15850
15851        if (getWidth() == 0 || getHeight() == 0) {
15852            return;
15853        }
15854
15855        switch (mLayerType) {
15856            case LAYER_TYPE_HARDWARE:
15857                updateDisplayListIfDirty();
15858                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
15859                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
15860                }
15861                break;
15862            case LAYER_TYPE_SOFTWARE:
15863                buildDrawingCache(true);
15864                break;
15865        }
15866    }
15867
15868    /**
15869     * Destroys all hardware rendering resources. This method is invoked
15870     * when the system needs to reclaim resources. Upon execution of this
15871     * method, you should free any OpenGL resources created by the view.
15872     *
15873     * Note: you <strong>must</strong> call
15874     * <code>super.destroyHardwareResources()</code> when overriding
15875     * this method.
15876     *
15877     * @hide
15878     */
15879    @CallSuper
15880    protected void destroyHardwareResources() {
15881        // Although the Layer will be destroyed by RenderNode, we want to release
15882        // the staging display list, which is also a signal to RenderNode that it's
15883        // safe to free its copy of the display list as it knows that we will
15884        // push an updated DisplayList if we try to draw again
15885        resetDisplayList();
15886    }
15887
15888    /**
15889     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15890     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15891     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15892     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15893     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15894     * null.</p>
15895     *
15896     * <p>Enabling the drawing cache is similar to
15897     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15898     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15899     * drawing cache has no effect on rendering because the system uses a different mechanism
15900     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15901     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15902     * for information on how to enable software and hardware layers.</p>
15903     *
15904     * <p>This API can be used to manually generate
15905     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15906     * {@link #getDrawingCache()}.</p>
15907     *
15908     * @param enabled true to enable the drawing cache, false otherwise
15909     *
15910     * @see #isDrawingCacheEnabled()
15911     * @see #getDrawingCache()
15912     * @see #buildDrawingCache()
15913     * @see #setLayerType(int, android.graphics.Paint)
15914     */
15915    public void setDrawingCacheEnabled(boolean enabled) {
15916        mCachingFailed = false;
15917        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15918    }
15919
15920    /**
15921     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15922     *
15923     * @return true if the drawing cache is enabled
15924     *
15925     * @see #setDrawingCacheEnabled(boolean)
15926     * @see #getDrawingCache()
15927     */
15928    @ViewDebug.ExportedProperty(category = "drawing")
15929    public boolean isDrawingCacheEnabled() {
15930        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15931    }
15932
15933    /**
15934     * Debugging utility which recursively outputs the dirty state of a view and its
15935     * descendants.
15936     *
15937     * @hide
15938     */
15939    @SuppressWarnings({"UnusedDeclaration"})
15940    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15941        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15942                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15943                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15944                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15945        if (clear) {
15946            mPrivateFlags &= clearMask;
15947        }
15948        if (this instanceof ViewGroup) {
15949            ViewGroup parent = (ViewGroup) this;
15950            final int count = parent.getChildCount();
15951            for (int i = 0; i < count; i++) {
15952                final View child = parent.getChildAt(i);
15953                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15954            }
15955        }
15956    }
15957
15958    /**
15959     * This method is used by ViewGroup to cause its children to restore or recreate their
15960     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15961     * to recreate its own display list, which would happen if it went through the normal
15962     * draw/dispatchDraw mechanisms.
15963     *
15964     * @hide
15965     */
15966    protected void dispatchGetDisplayList() {}
15967
15968    /**
15969     * A view that is not attached or hardware accelerated cannot create a display list.
15970     * This method checks these conditions and returns the appropriate result.
15971     *
15972     * @return true if view has the ability to create a display list, false otherwise.
15973     *
15974     * @hide
15975     */
15976    public boolean canHaveDisplayList() {
15977        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
15978    }
15979
15980    /**
15981     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15982     * @hide
15983     */
15984    @NonNull
15985    public RenderNode updateDisplayListIfDirty() {
15986        final RenderNode renderNode = mRenderNode;
15987        if (!canHaveDisplayList()) {
15988            // can't populate RenderNode, don't try
15989            return renderNode;
15990        }
15991
15992        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
15993                || !renderNode.isValid()
15994                || (mRecreateDisplayList)) {
15995            // Don't need to recreate the display list, just need to tell our
15996            // children to restore/recreate theirs
15997            if (renderNode.isValid()
15998                    && !mRecreateDisplayList) {
15999                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16000                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16001                dispatchGetDisplayList();
16002
16003                return renderNode; // no work needed
16004            }
16005
16006            // If we got here, we're recreating it. Mark it as such to ensure that
16007            // we copy in child display lists into ours in drawChild()
16008            mRecreateDisplayList = true;
16009
16010            int width = mRight - mLeft;
16011            int height = mBottom - mTop;
16012            int layerType = getLayerType();
16013
16014            final DisplayListCanvas canvas = renderNode.start(width, height);
16015            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16016
16017            try {
16018                if (layerType == LAYER_TYPE_SOFTWARE) {
16019                    buildDrawingCache(true);
16020                    Bitmap cache = getDrawingCache(true);
16021                    if (cache != null) {
16022                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16023                    }
16024                } else {
16025                    computeScroll();
16026
16027                    canvas.translate(-mScrollX, -mScrollY);
16028                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16029                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16030
16031                    // Fast path for layouts with no backgrounds
16032                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16033                        dispatchDraw(canvas);
16034                        if (mOverlay != null && !mOverlay.isEmpty()) {
16035                            mOverlay.getOverlayView().draw(canvas);
16036                        }
16037                    } else {
16038                        draw(canvas);
16039                    }
16040                }
16041            } finally {
16042                renderNode.end(canvas);
16043                setDisplayListProperties(renderNode);
16044            }
16045        } else {
16046            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16047            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16048        }
16049        return renderNode;
16050    }
16051
16052    private void resetDisplayList() {
16053        if (mRenderNode.isValid()) {
16054            mRenderNode.discardDisplayList();
16055        }
16056
16057        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16058            mBackgroundRenderNode.discardDisplayList();
16059        }
16060    }
16061
16062    /**
16063     * Called when the passed RenderNode is removed from the draw tree
16064     * @hide
16065     */
16066    public void onRenderNodeDetached(RenderNode renderNode) {
16067    }
16068
16069    /**
16070     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16071     *
16072     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16073     *
16074     * @see #getDrawingCache(boolean)
16075     */
16076    public Bitmap getDrawingCache() {
16077        return getDrawingCache(false);
16078    }
16079
16080    /**
16081     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16082     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16083     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16084     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16085     * request the drawing cache by calling this method and draw it on screen if the
16086     * returned bitmap is not null.</p>
16087     *
16088     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16089     * this method will create a bitmap of the same size as this view. Because this bitmap
16090     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16091     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16092     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16093     * size than the view. This implies that your application must be able to handle this
16094     * size.</p>
16095     *
16096     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16097     *        the current density of the screen when the application is in compatibility
16098     *        mode.
16099     *
16100     * @return A bitmap representing this view or null if cache is disabled.
16101     *
16102     * @see #setDrawingCacheEnabled(boolean)
16103     * @see #isDrawingCacheEnabled()
16104     * @see #buildDrawingCache(boolean)
16105     * @see #destroyDrawingCache()
16106     */
16107    public Bitmap getDrawingCache(boolean autoScale) {
16108        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16109            return null;
16110        }
16111        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16112            buildDrawingCache(autoScale);
16113        }
16114        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16115    }
16116
16117    /**
16118     * <p>Frees the resources used by the drawing cache. If you call
16119     * {@link #buildDrawingCache()} manually without calling
16120     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16121     * should cleanup the cache with this method afterwards.</p>
16122     *
16123     * @see #setDrawingCacheEnabled(boolean)
16124     * @see #buildDrawingCache()
16125     * @see #getDrawingCache()
16126     */
16127    public void destroyDrawingCache() {
16128        if (mDrawingCache != null) {
16129            mDrawingCache.recycle();
16130            mDrawingCache = null;
16131        }
16132        if (mUnscaledDrawingCache != null) {
16133            mUnscaledDrawingCache.recycle();
16134            mUnscaledDrawingCache = null;
16135        }
16136    }
16137
16138    /**
16139     * Setting a solid background color for the drawing cache's bitmaps will improve
16140     * performance and memory usage. Note, though that this should only be used if this
16141     * view will always be drawn on top of a solid color.
16142     *
16143     * @param color The background color to use for the drawing cache's bitmap
16144     *
16145     * @see #setDrawingCacheEnabled(boolean)
16146     * @see #buildDrawingCache()
16147     * @see #getDrawingCache()
16148     */
16149    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16150        if (color != mDrawingCacheBackgroundColor) {
16151            mDrawingCacheBackgroundColor = color;
16152            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16153        }
16154    }
16155
16156    /**
16157     * @see #setDrawingCacheBackgroundColor(int)
16158     *
16159     * @return The background color to used for the drawing cache's bitmap
16160     */
16161    @ColorInt
16162    public int getDrawingCacheBackgroundColor() {
16163        return mDrawingCacheBackgroundColor;
16164    }
16165
16166    /**
16167     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16168     *
16169     * @see #buildDrawingCache(boolean)
16170     */
16171    public void buildDrawingCache() {
16172        buildDrawingCache(false);
16173    }
16174
16175    /**
16176     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16177     *
16178     * <p>If you call {@link #buildDrawingCache()} manually without calling
16179     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16180     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16181     *
16182     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16183     * this method will create a bitmap of the same size as this view. Because this bitmap
16184     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16185     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16186     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16187     * size than the view. This implies that your application must be able to handle this
16188     * size.</p>
16189     *
16190     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16191     * you do not need the drawing cache bitmap, calling this method will increase memory
16192     * usage and cause the view to be rendered in software once, thus negatively impacting
16193     * performance.</p>
16194     *
16195     * @see #getDrawingCache()
16196     * @see #destroyDrawingCache()
16197     */
16198    public void buildDrawingCache(boolean autoScale) {
16199        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16200                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16201            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16202                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16203                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16204            }
16205            try {
16206                buildDrawingCacheImpl(autoScale);
16207            } finally {
16208                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16209            }
16210        }
16211    }
16212
16213    /**
16214     * private, internal implementation of buildDrawingCache, used to enable tracing
16215     */
16216    private void buildDrawingCacheImpl(boolean autoScale) {
16217        mCachingFailed = false;
16218
16219        int width = mRight - mLeft;
16220        int height = mBottom - mTop;
16221
16222        final AttachInfo attachInfo = mAttachInfo;
16223        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16224
16225        if (autoScale && scalingRequired) {
16226            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16227            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16228        }
16229
16230        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16231        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16232        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16233
16234        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16235        final long drawingCacheSize =
16236                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16237        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16238            if (width > 0 && height > 0) {
16239                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16240                        + " too large to fit into a software layer (or drawing cache), needs "
16241                        + projectedBitmapSize + " bytes, only "
16242                        + drawingCacheSize + " available");
16243            }
16244            destroyDrawingCache();
16245            mCachingFailed = true;
16246            return;
16247        }
16248
16249        boolean clear = true;
16250        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16251
16252        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16253            Bitmap.Config quality;
16254            if (!opaque) {
16255                // Never pick ARGB_4444 because it looks awful
16256                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16257                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16258                    case DRAWING_CACHE_QUALITY_AUTO:
16259                    case DRAWING_CACHE_QUALITY_LOW:
16260                    case DRAWING_CACHE_QUALITY_HIGH:
16261                    default:
16262                        quality = Bitmap.Config.ARGB_8888;
16263                        break;
16264                }
16265            } else {
16266                // Optimization for translucent windows
16267                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16268                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16269            }
16270
16271            // Try to cleanup memory
16272            if (bitmap != null) bitmap.recycle();
16273
16274            try {
16275                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16276                        width, height, quality);
16277                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16278                if (autoScale) {
16279                    mDrawingCache = bitmap;
16280                } else {
16281                    mUnscaledDrawingCache = bitmap;
16282                }
16283                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16284            } catch (OutOfMemoryError e) {
16285                // If there is not enough memory to create the bitmap cache, just
16286                // ignore the issue as bitmap caches are not required to draw the
16287                // view hierarchy
16288                if (autoScale) {
16289                    mDrawingCache = null;
16290                } else {
16291                    mUnscaledDrawingCache = null;
16292                }
16293                mCachingFailed = true;
16294                return;
16295            }
16296
16297            clear = drawingCacheBackgroundColor != 0;
16298        }
16299
16300        Canvas canvas;
16301        if (attachInfo != null) {
16302            canvas = attachInfo.mCanvas;
16303            if (canvas == null) {
16304                canvas = new Canvas();
16305            }
16306            canvas.setBitmap(bitmap);
16307            // Temporarily clobber the cached Canvas in case one of our children
16308            // is also using a drawing cache. Without this, the children would
16309            // steal the canvas by attaching their own bitmap to it and bad, bad
16310            // thing would happen (invisible views, corrupted drawings, etc.)
16311            attachInfo.mCanvas = null;
16312        } else {
16313            // This case should hopefully never or seldom happen
16314            canvas = new Canvas(bitmap);
16315        }
16316
16317        if (clear) {
16318            bitmap.eraseColor(drawingCacheBackgroundColor);
16319        }
16320
16321        computeScroll();
16322        final int restoreCount = canvas.save();
16323
16324        if (autoScale && scalingRequired) {
16325            final float scale = attachInfo.mApplicationScale;
16326            canvas.scale(scale, scale);
16327        }
16328
16329        canvas.translate(-mScrollX, -mScrollY);
16330
16331        mPrivateFlags |= PFLAG_DRAWN;
16332        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16333                mLayerType != LAYER_TYPE_NONE) {
16334            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16335        }
16336
16337        // Fast path for layouts with no backgrounds
16338        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16339            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16340            dispatchDraw(canvas);
16341            if (mOverlay != null && !mOverlay.isEmpty()) {
16342                mOverlay.getOverlayView().draw(canvas);
16343            }
16344        } else {
16345            draw(canvas);
16346        }
16347
16348        canvas.restoreToCount(restoreCount);
16349        canvas.setBitmap(null);
16350
16351        if (attachInfo != null) {
16352            // Restore the cached Canvas for our siblings
16353            attachInfo.mCanvas = canvas;
16354        }
16355    }
16356
16357    /**
16358     * Create a snapshot of the view into a bitmap.  We should probably make
16359     * some form of this public, but should think about the API.
16360     *
16361     * @hide
16362     */
16363    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16364        int width = mRight - mLeft;
16365        int height = mBottom - mTop;
16366
16367        final AttachInfo attachInfo = mAttachInfo;
16368        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16369        width = (int) ((width * scale) + 0.5f);
16370        height = (int) ((height * scale) + 0.5f);
16371
16372        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16373                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16374        if (bitmap == null) {
16375            throw new OutOfMemoryError();
16376        }
16377
16378        Resources resources = getResources();
16379        if (resources != null) {
16380            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16381        }
16382
16383        Canvas canvas;
16384        if (attachInfo != null) {
16385            canvas = attachInfo.mCanvas;
16386            if (canvas == null) {
16387                canvas = new Canvas();
16388            }
16389            canvas.setBitmap(bitmap);
16390            // Temporarily clobber the cached Canvas in case one of our children
16391            // is also using a drawing cache. Without this, the children would
16392            // steal the canvas by attaching their own bitmap to it and bad, bad
16393            // things would happen (invisible views, corrupted drawings, etc.)
16394            attachInfo.mCanvas = null;
16395        } else {
16396            // This case should hopefully never or seldom happen
16397            canvas = new Canvas(bitmap);
16398        }
16399
16400        if ((backgroundColor & 0xff000000) != 0) {
16401            bitmap.eraseColor(backgroundColor);
16402        }
16403
16404        computeScroll();
16405        final int restoreCount = canvas.save();
16406        canvas.scale(scale, scale);
16407        canvas.translate(-mScrollX, -mScrollY);
16408
16409        // Temporarily remove the dirty mask
16410        int flags = mPrivateFlags;
16411        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16412
16413        // Fast path for layouts with no backgrounds
16414        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16415            dispatchDraw(canvas);
16416            if (mOverlay != null && !mOverlay.isEmpty()) {
16417                mOverlay.getOverlayView().draw(canvas);
16418            }
16419        } else {
16420            draw(canvas);
16421        }
16422
16423        mPrivateFlags = flags;
16424
16425        canvas.restoreToCount(restoreCount);
16426        canvas.setBitmap(null);
16427
16428        if (attachInfo != null) {
16429            // Restore the cached Canvas for our siblings
16430            attachInfo.mCanvas = canvas;
16431        }
16432
16433        return bitmap;
16434    }
16435
16436    /**
16437     * Indicates whether this View is currently in edit mode. A View is usually
16438     * in edit mode when displayed within a developer tool. For instance, if
16439     * this View is being drawn by a visual user interface builder, this method
16440     * should return true.
16441     *
16442     * Subclasses should check the return value of this method to provide
16443     * different behaviors if their normal behavior might interfere with the
16444     * host environment. For instance: the class spawns a thread in its
16445     * constructor, the drawing code relies on device-specific features, etc.
16446     *
16447     * This method is usually checked in the drawing code of custom widgets.
16448     *
16449     * @return True if this View is in edit mode, false otherwise.
16450     */
16451    public boolean isInEditMode() {
16452        return false;
16453    }
16454
16455    /**
16456     * If the View draws content inside its padding and enables fading edges,
16457     * it needs to support padding offsets. Padding offsets are added to the
16458     * fading edges to extend the length of the fade so that it covers pixels
16459     * drawn inside the padding.
16460     *
16461     * Subclasses of this class should override this method if they need
16462     * to draw content inside the padding.
16463     *
16464     * @return True if padding offset must be applied, false otherwise.
16465     *
16466     * @see #getLeftPaddingOffset()
16467     * @see #getRightPaddingOffset()
16468     * @see #getTopPaddingOffset()
16469     * @see #getBottomPaddingOffset()
16470     *
16471     * @since CURRENT
16472     */
16473    protected boolean isPaddingOffsetRequired() {
16474        return false;
16475    }
16476
16477    /**
16478     * Amount by which to extend the left fading region. Called only when
16479     * {@link #isPaddingOffsetRequired()} returns true.
16480     *
16481     * @return The left padding offset in pixels.
16482     *
16483     * @see #isPaddingOffsetRequired()
16484     *
16485     * @since CURRENT
16486     */
16487    protected int getLeftPaddingOffset() {
16488        return 0;
16489    }
16490
16491    /**
16492     * Amount by which to extend the right fading region. Called only when
16493     * {@link #isPaddingOffsetRequired()} returns true.
16494     *
16495     * @return The right padding offset in pixels.
16496     *
16497     * @see #isPaddingOffsetRequired()
16498     *
16499     * @since CURRENT
16500     */
16501    protected int getRightPaddingOffset() {
16502        return 0;
16503    }
16504
16505    /**
16506     * Amount by which to extend the top fading region. Called only when
16507     * {@link #isPaddingOffsetRequired()} returns true.
16508     *
16509     * @return The top padding offset in pixels.
16510     *
16511     * @see #isPaddingOffsetRequired()
16512     *
16513     * @since CURRENT
16514     */
16515    protected int getTopPaddingOffset() {
16516        return 0;
16517    }
16518
16519    /**
16520     * Amount by which to extend the bottom fading region. Called only when
16521     * {@link #isPaddingOffsetRequired()} returns true.
16522     *
16523     * @return The bottom padding offset in pixels.
16524     *
16525     * @see #isPaddingOffsetRequired()
16526     *
16527     * @since CURRENT
16528     */
16529    protected int getBottomPaddingOffset() {
16530        return 0;
16531    }
16532
16533    /**
16534     * @hide
16535     * @param offsetRequired
16536     */
16537    protected int getFadeTop(boolean offsetRequired) {
16538        int top = mPaddingTop;
16539        if (offsetRequired) top += getTopPaddingOffset();
16540        return top;
16541    }
16542
16543    /**
16544     * @hide
16545     * @param offsetRequired
16546     */
16547    protected int getFadeHeight(boolean offsetRequired) {
16548        int padding = mPaddingTop;
16549        if (offsetRequired) padding += getTopPaddingOffset();
16550        return mBottom - mTop - mPaddingBottom - padding;
16551    }
16552
16553    /**
16554     * <p>Indicates whether this view is attached to a hardware accelerated
16555     * window or not.</p>
16556     *
16557     * <p>Even if this method returns true, it does not mean that every call
16558     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16559     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16560     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16561     * window is hardware accelerated,
16562     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16563     * return false, and this method will return true.</p>
16564     *
16565     * @return True if the view is attached to a window and the window is
16566     *         hardware accelerated; false in any other case.
16567     */
16568    @ViewDebug.ExportedProperty(category = "drawing")
16569    public boolean isHardwareAccelerated() {
16570        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16571    }
16572
16573    /**
16574     * Sets a rectangular area on this view to which the view will be clipped
16575     * when it is drawn. Setting the value to null will remove the clip bounds
16576     * and the view will draw normally, using its full bounds.
16577     *
16578     * @param clipBounds The rectangular area, in the local coordinates of
16579     * this view, to which future drawing operations will be clipped.
16580     */
16581    public void setClipBounds(Rect clipBounds) {
16582        if (clipBounds == mClipBounds
16583                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16584            return;
16585        }
16586        if (clipBounds != null) {
16587            if (mClipBounds == null) {
16588                mClipBounds = new Rect(clipBounds);
16589            } else {
16590                mClipBounds.set(clipBounds);
16591            }
16592        } else {
16593            mClipBounds = null;
16594        }
16595        mRenderNode.setClipBounds(mClipBounds);
16596        invalidateViewProperty(false, false);
16597    }
16598
16599    /**
16600     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16601     *
16602     * @return A copy of the current clip bounds if clip bounds are set,
16603     * otherwise null.
16604     */
16605    public Rect getClipBounds() {
16606        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16607    }
16608
16609
16610    /**
16611     * Populates an output rectangle with the clip bounds of the view,
16612     * returning {@code true} if successful or {@code false} if the view's
16613     * clip bounds are {@code null}.
16614     *
16615     * @param outRect rectangle in which to place the clip bounds of the view
16616     * @return {@code true} if successful or {@code false} if the view's
16617     *         clip bounds are {@code null}
16618     */
16619    public boolean getClipBounds(Rect outRect) {
16620        if (mClipBounds != null) {
16621            outRect.set(mClipBounds);
16622            return true;
16623        }
16624        return false;
16625    }
16626
16627    /**
16628     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16629     * case of an active Animation being run on the view.
16630     */
16631    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16632            Animation a, boolean scalingRequired) {
16633        Transformation invalidationTransform;
16634        final int flags = parent.mGroupFlags;
16635        final boolean initialized = a.isInitialized();
16636        if (!initialized) {
16637            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16638            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16639            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16640            onAnimationStart();
16641        }
16642
16643        final Transformation t = parent.getChildTransformation();
16644        boolean more = a.getTransformation(drawingTime, t, 1f);
16645        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16646            if (parent.mInvalidationTransformation == null) {
16647                parent.mInvalidationTransformation = new Transformation();
16648            }
16649            invalidationTransform = parent.mInvalidationTransformation;
16650            a.getTransformation(drawingTime, invalidationTransform, 1f);
16651        } else {
16652            invalidationTransform = t;
16653        }
16654
16655        if (more) {
16656            if (!a.willChangeBounds()) {
16657                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16658                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16659                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16660                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16661                    // The child need to draw an animation, potentially offscreen, so
16662                    // make sure we do not cancel invalidate requests
16663                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16664                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16665                }
16666            } else {
16667                if (parent.mInvalidateRegion == null) {
16668                    parent.mInvalidateRegion = new RectF();
16669                }
16670                final RectF region = parent.mInvalidateRegion;
16671                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16672                        invalidationTransform);
16673
16674                // The child need to draw an animation, potentially offscreen, so
16675                // make sure we do not cancel invalidate requests
16676                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16677
16678                final int left = mLeft + (int) region.left;
16679                final int top = mTop + (int) region.top;
16680                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16681                        top + (int) (region.height() + .5f));
16682            }
16683        }
16684        return more;
16685    }
16686
16687    /**
16688     * This method is called by getDisplayList() when a display list is recorded for a View.
16689     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16690     */
16691    void setDisplayListProperties(RenderNode renderNode) {
16692        if (renderNode != null) {
16693            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16694            renderNode.setClipToBounds(mParent instanceof ViewGroup
16695                    && ((ViewGroup) mParent).getClipChildren());
16696
16697            float alpha = 1;
16698            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16699                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16700                ViewGroup parentVG = (ViewGroup) mParent;
16701                final Transformation t = parentVG.getChildTransformation();
16702                if (parentVG.getChildStaticTransformation(this, t)) {
16703                    final int transformType = t.getTransformationType();
16704                    if (transformType != Transformation.TYPE_IDENTITY) {
16705                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16706                            alpha = t.getAlpha();
16707                        }
16708                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16709                            renderNode.setStaticMatrix(t.getMatrix());
16710                        }
16711                    }
16712                }
16713            }
16714            if (mTransformationInfo != null) {
16715                alpha *= getFinalAlpha();
16716                if (alpha < 1) {
16717                    final int multipliedAlpha = (int) (255 * alpha);
16718                    if (onSetAlpha(multipliedAlpha)) {
16719                        alpha = 1;
16720                    }
16721                }
16722                renderNode.setAlpha(alpha);
16723            } else if (alpha < 1) {
16724                renderNode.setAlpha(alpha);
16725            }
16726        }
16727    }
16728
16729    /**
16730     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16731     *
16732     * This is where the View specializes rendering behavior based on layer type,
16733     * and hardware acceleration.
16734     */
16735    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16736        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16737        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16738         *
16739         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16740         * HW accelerated, it can't handle drawing RenderNodes.
16741         */
16742        boolean drawingWithRenderNode = mAttachInfo != null
16743                && mAttachInfo.mHardwareAccelerated
16744                && hardwareAcceleratedCanvas;
16745
16746        boolean more = false;
16747        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16748        final int parentFlags = parent.mGroupFlags;
16749
16750        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16751            parent.getChildTransformation().clear();
16752            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16753        }
16754
16755        Transformation transformToApply = null;
16756        boolean concatMatrix = false;
16757        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16758        final Animation a = getAnimation();
16759        if (a != null) {
16760            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16761            concatMatrix = a.willChangeTransformationMatrix();
16762            if (concatMatrix) {
16763                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16764            }
16765            transformToApply = parent.getChildTransformation();
16766        } else {
16767            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16768                // No longer animating: clear out old animation matrix
16769                mRenderNode.setAnimationMatrix(null);
16770                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16771            }
16772            if (!drawingWithRenderNode
16773                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16774                final Transformation t = parent.getChildTransformation();
16775                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16776                if (hasTransform) {
16777                    final int transformType = t.getTransformationType();
16778                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16779                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16780                }
16781            }
16782        }
16783
16784        concatMatrix |= !childHasIdentityMatrix;
16785
16786        // Sets the flag as early as possible to allow draw() implementations
16787        // to call invalidate() successfully when doing animations
16788        mPrivateFlags |= PFLAG_DRAWN;
16789
16790        if (!concatMatrix &&
16791                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16792                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16793                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16794                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16795            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16796            return more;
16797        }
16798        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16799
16800        if (hardwareAcceleratedCanvas) {
16801            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16802            // retain the flag's value temporarily in the mRecreateDisplayList flag
16803            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16804            mPrivateFlags &= ~PFLAG_INVALIDATED;
16805        }
16806
16807        RenderNode renderNode = null;
16808        Bitmap cache = null;
16809        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16810        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16811             if (layerType != LAYER_TYPE_NONE) {
16812                 // If not drawing with RenderNode, treat HW layers as SW
16813                 layerType = LAYER_TYPE_SOFTWARE;
16814                 buildDrawingCache(true);
16815            }
16816            cache = getDrawingCache(true);
16817        }
16818
16819        if (drawingWithRenderNode) {
16820            // Delay getting the display list until animation-driven alpha values are
16821            // set up and possibly passed on to the view
16822            renderNode = updateDisplayListIfDirty();
16823            if (!renderNode.isValid()) {
16824                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16825                // to getDisplayList(), the display list will be marked invalid and we should not
16826                // try to use it again.
16827                renderNode = null;
16828                drawingWithRenderNode = false;
16829            }
16830        }
16831
16832        int sx = 0;
16833        int sy = 0;
16834        if (!drawingWithRenderNode) {
16835            computeScroll();
16836            sx = mScrollX;
16837            sy = mScrollY;
16838        }
16839
16840        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16841        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16842
16843        int restoreTo = -1;
16844        if (!drawingWithRenderNode || transformToApply != null) {
16845            restoreTo = canvas.save();
16846        }
16847        if (offsetForScroll) {
16848            canvas.translate(mLeft - sx, mTop - sy);
16849        } else {
16850            if (!drawingWithRenderNode) {
16851                canvas.translate(mLeft, mTop);
16852            }
16853            if (scalingRequired) {
16854                if (drawingWithRenderNode) {
16855                    // TODO: Might not need this if we put everything inside the DL
16856                    restoreTo = canvas.save();
16857                }
16858                // mAttachInfo cannot be null, otherwise scalingRequired == false
16859                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16860                canvas.scale(scale, scale);
16861            }
16862        }
16863
16864        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16865        if (transformToApply != null
16866                || alpha < 1
16867                || !hasIdentityMatrix()
16868                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16869            if (transformToApply != null || !childHasIdentityMatrix) {
16870                int transX = 0;
16871                int transY = 0;
16872
16873                if (offsetForScroll) {
16874                    transX = -sx;
16875                    transY = -sy;
16876                }
16877
16878                if (transformToApply != null) {
16879                    if (concatMatrix) {
16880                        if (drawingWithRenderNode) {
16881                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16882                        } else {
16883                            // Undo the scroll translation, apply the transformation matrix,
16884                            // then redo the scroll translate to get the correct result.
16885                            canvas.translate(-transX, -transY);
16886                            canvas.concat(transformToApply.getMatrix());
16887                            canvas.translate(transX, transY);
16888                        }
16889                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16890                    }
16891
16892                    float transformAlpha = transformToApply.getAlpha();
16893                    if (transformAlpha < 1) {
16894                        alpha *= transformAlpha;
16895                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16896                    }
16897                }
16898
16899                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16900                    canvas.translate(-transX, -transY);
16901                    canvas.concat(getMatrix());
16902                    canvas.translate(transX, transY);
16903                }
16904            }
16905
16906            // Deal with alpha if it is or used to be <1
16907            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16908                if (alpha < 1) {
16909                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16910                } else {
16911                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16912                }
16913                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16914                if (!drawingWithDrawingCache) {
16915                    final int multipliedAlpha = (int) (255 * alpha);
16916                    if (!onSetAlpha(multipliedAlpha)) {
16917                        if (drawingWithRenderNode) {
16918                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16919                        } else if (layerType == LAYER_TYPE_NONE) {
16920                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16921                                    multipliedAlpha);
16922                        }
16923                    } else {
16924                        // Alpha is handled by the child directly, clobber the layer's alpha
16925                        mPrivateFlags |= PFLAG_ALPHA_SET;
16926                    }
16927                }
16928            }
16929        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16930            onSetAlpha(255);
16931            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16932        }
16933
16934        if (!drawingWithRenderNode) {
16935            // apply clips directly, since RenderNode won't do it for this draw
16936            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16937                if (offsetForScroll) {
16938                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16939                } else {
16940                    if (!scalingRequired || cache == null) {
16941                        canvas.clipRect(0, 0, getWidth(), getHeight());
16942                    } else {
16943                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16944                    }
16945                }
16946            }
16947
16948            if (mClipBounds != null) {
16949                // clip bounds ignore scroll
16950                canvas.clipRect(mClipBounds);
16951            }
16952        }
16953
16954        if (!drawingWithDrawingCache) {
16955            if (drawingWithRenderNode) {
16956                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16957                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16958            } else {
16959                // Fast path for layouts with no backgrounds
16960                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16961                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16962                    dispatchDraw(canvas);
16963                } else {
16964                    draw(canvas);
16965                }
16966            }
16967        } else if (cache != null) {
16968            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16969            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
16970                // no layer paint, use temporary paint to draw bitmap
16971                Paint cachePaint = parent.mCachePaint;
16972                if (cachePaint == null) {
16973                    cachePaint = new Paint();
16974                    cachePaint.setDither(false);
16975                    parent.mCachePaint = cachePaint;
16976                }
16977                cachePaint.setAlpha((int) (alpha * 255));
16978                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16979            } else {
16980                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16981                int layerPaintAlpha = mLayerPaint.getAlpha();
16982                if (alpha < 1) {
16983                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16984                }
16985                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
16986                if (alpha < 1) {
16987                    mLayerPaint.setAlpha(layerPaintAlpha);
16988                }
16989            }
16990        }
16991
16992        if (restoreTo >= 0) {
16993            canvas.restoreToCount(restoreTo);
16994        }
16995
16996        if (a != null && !more) {
16997            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
16998                onSetAlpha(255);
16999            }
17000            parent.finishAnimatingView(this, a);
17001        }
17002
17003        if (more && hardwareAcceleratedCanvas) {
17004            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17005                // alpha animations should cause the child to recreate its display list
17006                invalidate(true);
17007            }
17008        }
17009
17010        mRecreateDisplayList = false;
17011
17012        return more;
17013    }
17014
17015    /**
17016     * Manually render this view (and all of its children) to the given Canvas.
17017     * The view must have already done a full layout before this function is
17018     * called.  When implementing a view, implement
17019     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17020     * If you do need to override this method, call the superclass version.
17021     *
17022     * @param canvas The Canvas to which the View is rendered.
17023     */
17024    @CallSuper
17025    public void draw(Canvas canvas) {
17026        final int privateFlags = mPrivateFlags;
17027        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17028                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17029        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17030
17031        /*
17032         * Draw traversal performs several drawing steps which must be executed
17033         * in the appropriate order:
17034         *
17035         *      1. Draw the background
17036         *      2. If necessary, save the canvas' layers to prepare for fading
17037         *      3. Draw view's content
17038         *      4. Draw children
17039         *      5. If necessary, draw the fading edges and restore layers
17040         *      6. Draw decorations (scrollbars for instance)
17041         */
17042
17043        // Step 1, draw the background, if needed
17044        int saveCount;
17045
17046        if (!dirtyOpaque) {
17047            drawBackground(canvas);
17048        }
17049
17050        // skip step 2 & 5 if possible (common case)
17051        final int viewFlags = mViewFlags;
17052        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17053        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17054        if (!verticalEdges && !horizontalEdges) {
17055            // Step 3, draw the content
17056            if (!dirtyOpaque) onDraw(canvas);
17057
17058            // Step 4, draw the children
17059            dispatchDraw(canvas);
17060
17061            // Overlay is part of the content and draws beneath Foreground
17062            if (mOverlay != null && !mOverlay.isEmpty()) {
17063                mOverlay.getOverlayView().dispatchDraw(canvas);
17064            }
17065
17066            // Step 6, draw decorations (foreground, scrollbars)
17067            onDrawForeground(canvas);
17068
17069            // we're done...
17070            return;
17071        }
17072
17073        /*
17074         * Here we do the full fledged routine...
17075         * (this is an uncommon case where speed matters less,
17076         * this is why we repeat some of the tests that have been
17077         * done above)
17078         */
17079
17080        boolean drawTop = false;
17081        boolean drawBottom = false;
17082        boolean drawLeft = false;
17083        boolean drawRight = false;
17084
17085        float topFadeStrength = 0.0f;
17086        float bottomFadeStrength = 0.0f;
17087        float leftFadeStrength = 0.0f;
17088        float rightFadeStrength = 0.0f;
17089
17090        // Step 2, save the canvas' layers
17091        int paddingLeft = mPaddingLeft;
17092
17093        final boolean offsetRequired = isPaddingOffsetRequired();
17094        if (offsetRequired) {
17095            paddingLeft += getLeftPaddingOffset();
17096        }
17097
17098        int left = mScrollX + paddingLeft;
17099        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17100        int top = mScrollY + getFadeTop(offsetRequired);
17101        int bottom = top + getFadeHeight(offsetRequired);
17102
17103        if (offsetRequired) {
17104            right += getRightPaddingOffset();
17105            bottom += getBottomPaddingOffset();
17106        }
17107
17108        final ScrollabilityCache scrollabilityCache = mScrollCache;
17109        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17110        int length = (int) fadeHeight;
17111
17112        // clip the fade length if top and bottom fades overlap
17113        // overlapping fades produce odd-looking artifacts
17114        if (verticalEdges && (top + length > bottom - length)) {
17115            length = (bottom - top) / 2;
17116        }
17117
17118        // also clip horizontal fades if necessary
17119        if (horizontalEdges && (left + length > right - length)) {
17120            length = (right - left) / 2;
17121        }
17122
17123        if (verticalEdges) {
17124            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17125            drawTop = topFadeStrength * fadeHeight > 1.0f;
17126            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17127            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17128        }
17129
17130        if (horizontalEdges) {
17131            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17132            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17133            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17134            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17135        }
17136
17137        saveCount = canvas.getSaveCount();
17138
17139        int solidColor = getSolidColor();
17140        if (solidColor == 0) {
17141            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17142
17143            if (drawTop) {
17144                canvas.saveLayer(left, top, right, top + length, null, flags);
17145            }
17146
17147            if (drawBottom) {
17148                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17149            }
17150
17151            if (drawLeft) {
17152                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17153            }
17154
17155            if (drawRight) {
17156                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17157            }
17158        } else {
17159            scrollabilityCache.setFadeColor(solidColor);
17160        }
17161
17162        // Step 3, draw the content
17163        if (!dirtyOpaque) onDraw(canvas);
17164
17165        // Step 4, draw the children
17166        dispatchDraw(canvas);
17167
17168        // Step 5, draw the fade effect and restore layers
17169        final Paint p = scrollabilityCache.paint;
17170        final Matrix matrix = scrollabilityCache.matrix;
17171        final Shader fade = scrollabilityCache.shader;
17172
17173        if (drawTop) {
17174            matrix.setScale(1, fadeHeight * topFadeStrength);
17175            matrix.postTranslate(left, top);
17176            fade.setLocalMatrix(matrix);
17177            p.setShader(fade);
17178            canvas.drawRect(left, top, right, top + length, p);
17179        }
17180
17181        if (drawBottom) {
17182            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17183            matrix.postRotate(180);
17184            matrix.postTranslate(left, bottom);
17185            fade.setLocalMatrix(matrix);
17186            p.setShader(fade);
17187            canvas.drawRect(left, bottom - length, right, bottom, p);
17188        }
17189
17190        if (drawLeft) {
17191            matrix.setScale(1, fadeHeight * leftFadeStrength);
17192            matrix.postRotate(-90);
17193            matrix.postTranslate(left, top);
17194            fade.setLocalMatrix(matrix);
17195            p.setShader(fade);
17196            canvas.drawRect(left, top, left + length, bottom, p);
17197        }
17198
17199        if (drawRight) {
17200            matrix.setScale(1, fadeHeight * rightFadeStrength);
17201            matrix.postRotate(90);
17202            matrix.postTranslate(right, top);
17203            fade.setLocalMatrix(matrix);
17204            p.setShader(fade);
17205            canvas.drawRect(right - length, top, right, bottom, p);
17206        }
17207
17208        canvas.restoreToCount(saveCount);
17209
17210        // Overlay is part of the content and draws beneath Foreground
17211        if (mOverlay != null && !mOverlay.isEmpty()) {
17212            mOverlay.getOverlayView().dispatchDraw(canvas);
17213        }
17214
17215        // Step 6, draw decorations (foreground, scrollbars)
17216        onDrawForeground(canvas);
17217    }
17218
17219    /**
17220     * Draws the background onto the specified canvas.
17221     *
17222     * @param canvas Canvas on which to draw the background
17223     */
17224    private void drawBackground(Canvas canvas) {
17225        final Drawable background = mBackground;
17226        if (background == null) {
17227            return;
17228        }
17229
17230        setBackgroundBounds();
17231
17232        // Attempt to use a display list if requested.
17233        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17234                && mAttachInfo.mHardwareRenderer != null) {
17235            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17236
17237            final RenderNode renderNode = mBackgroundRenderNode;
17238            if (renderNode != null && renderNode.isValid()) {
17239                setBackgroundRenderNodeProperties(renderNode);
17240                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17241                return;
17242            }
17243        }
17244
17245        final int scrollX = mScrollX;
17246        final int scrollY = mScrollY;
17247        if ((scrollX | scrollY) == 0) {
17248            background.draw(canvas);
17249        } else {
17250            canvas.translate(scrollX, scrollY);
17251            background.draw(canvas);
17252            canvas.translate(-scrollX, -scrollY);
17253        }
17254    }
17255
17256    /**
17257     * Sets the correct background bounds and rebuilds the outline, if needed.
17258     * <p/>
17259     * This is called by LayoutLib.
17260     */
17261    void setBackgroundBounds() {
17262        if (mBackgroundSizeChanged && mBackground != null) {
17263            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17264            mBackgroundSizeChanged = false;
17265            rebuildOutline();
17266        }
17267    }
17268
17269    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17270        renderNode.setTranslationX(mScrollX);
17271        renderNode.setTranslationY(mScrollY);
17272    }
17273
17274    /**
17275     * Creates a new display list or updates the existing display list for the
17276     * specified Drawable.
17277     *
17278     * @param drawable Drawable for which to create a display list
17279     * @param renderNode Existing RenderNode, or {@code null}
17280     * @return A valid display list for the specified drawable
17281     */
17282    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17283        if (renderNode == null) {
17284            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17285        }
17286
17287        final Rect bounds = drawable.getBounds();
17288        final int width = bounds.width();
17289        final int height = bounds.height();
17290        final DisplayListCanvas canvas = renderNode.start(width, height);
17291
17292        // Reverse left/top translation done by drawable canvas, which will
17293        // instead be applied by rendernode's LTRB bounds below. This way, the
17294        // drawable's bounds match with its rendernode bounds and its content
17295        // will lie within those bounds in the rendernode tree.
17296        canvas.translate(-bounds.left, -bounds.top);
17297
17298        try {
17299            drawable.draw(canvas);
17300        } finally {
17301            renderNode.end(canvas);
17302        }
17303
17304        // Set up drawable properties that are view-independent.
17305        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17306        renderNode.setProjectBackwards(drawable.isProjected());
17307        renderNode.setProjectionReceiver(true);
17308        renderNode.setClipToBounds(false);
17309        return renderNode;
17310    }
17311
17312    /**
17313     * Returns the overlay for this view, creating it if it does not yet exist.
17314     * Adding drawables to the overlay will cause them to be displayed whenever
17315     * the view itself is redrawn. Objects in the overlay should be actively
17316     * managed: remove them when they should not be displayed anymore. The
17317     * overlay will always have the same size as its host view.
17318     *
17319     * <p>Note: Overlays do not currently work correctly with {@link
17320     * SurfaceView} or {@link TextureView}; contents in overlays for these
17321     * types of views may not display correctly.</p>
17322     *
17323     * @return The ViewOverlay object for this view.
17324     * @see ViewOverlay
17325     */
17326    public ViewOverlay getOverlay() {
17327        if (mOverlay == null) {
17328            mOverlay = new ViewOverlay(mContext, this);
17329        }
17330        return mOverlay;
17331    }
17332
17333    /**
17334     * Override this if your view is known to always be drawn on top of a solid color background,
17335     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17336     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17337     * should be set to 0xFF.
17338     *
17339     * @see #setVerticalFadingEdgeEnabled(boolean)
17340     * @see #setHorizontalFadingEdgeEnabled(boolean)
17341     *
17342     * @return The known solid color background for this view, or 0 if the color may vary
17343     */
17344    @ViewDebug.ExportedProperty(category = "drawing")
17345    @ColorInt
17346    public int getSolidColor() {
17347        return 0;
17348    }
17349
17350    /**
17351     * Build a human readable string representation of the specified view flags.
17352     *
17353     * @param flags the view flags to convert to a string
17354     * @return a String representing the supplied flags
17355     */
17356    private static String printFlags(int flags) {
17357        String output = "";
17358        int numFlags = 0;
17359        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17360            output += "TAKES_FOCUS";
17361            numFlags++;
17362        }
17363
17364        switch (flags & VISIBILITY_MASK) {
17365        case INVISIBLE:
17366            if (numFlags > 0) {
17367                output += " ";
17368            }
17369            output += "INVISIBLE";
17370            // USELESS HERE numFlags++;
17371            break;
17372        case GONE:
17373            if (numFlags > 0) {
17374                output += " ";
17375            }
17376            output += "GONE";
17377            // USELESS HERE numFlags++;
17378            break;
17379        default:
17380            break;
17381        }
17382        return output;
17383    }
17384
17385    /**
17386     * Build a human readable string representation of the specified private
17387     * view flags.
17388     *
17389     * @param privateFlags the private view flags to convert to a string
17390     * @return a String representing the supplied flags
17391     */
17392    private static String printPrivateFlags(int privateFlags) {
17393        String output = "";
17394        int numFlags = 0;
17395
17396        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17397            output += "WANTS_FOCUS";
17398            numFlags++;
17399        }
17400
17401        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17402            if (numFlags > 0) {
17403                output += " ";
17404            }
17405            output += "FOCUSED";
17406            numFlags++;
17407        }
17408
17409        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17410            if (numFlags > 0) {
17411                output += " ";
17412            }
17413            output += "SELECTED";
17414            numFlags++;
17415        }
17416
17417        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17418            if (numFlags > 0) {
17419                output += " ";
17420            }
17421            output += "IS_ROOT_NAMESPACE";
17422            numFlags++;
17423        }
17424
17425        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17426            if (numFlags > 0) {
17427                output += " ";
17428            }
17429            output += "HAS_BOUNDS";
17430            numFlags++;
17431        }
17432
17433        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17434            if (numFlags > 0) {
17435                output += " ";
17436            }
17437            output += "DRAWN";
17438            // USELESS HERE numFlags++;
17439        }
17440        return output;
17441    }
17442
17443    /**
17444     * <p>Indicates whether or not this view's layout will be requested during
17445     * the next hierarchy layout pass.</p>
17446     *
17447     * @return true if the layout will be forced during next layout pass
17448     */
17449    public boolean isLayoutRequested() {
17450        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17451    }
17452
17453    /**
17454     * Return true if o is a ViewGroup that is laying out using optical bounds.
17455     * @hide
17456     */
17457    public static boolean isLayoutModeOptical(Object o) {
17458        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17459    }
17460
17461    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17462        Insets parentInsets = mParent instanceof View ?
17463                ((View) mParent).getOpticalInsets() : Insets.NONE;
17464        Insets childInsets = getOpticalInsets();
17465        return setFrame(
17466                left   + parentInsets.left - childInsets.left,
17467                top    + parentInsets.top  - childInsets.top,
17468                right  + parentInsets.left + childInsets.right,
17469                bottom + parentInsets.top  + childInsets.bottom);
17470    }
17471
17472    /**
17473     * Assign a size and position to a view and all of its
17474     * descendants
17475     *
17476     * <p>This is the second phase of the layout mechanism.
17477     * (The first is measuring). In this phase, each parent calls
17478     * layout on all of its children to position them.
17479     * This is typically done using the child measurements
17480     * that were stored in the measure pass().</p>
17481     *
17482     * <p>Derived classes should not override this method.
17483     * Derived classes with children should override
17484     * onLayout. In that method, they should
17485     * call layout on each of their children.</p>
17486     *
17487     * @param l Left position, relative to parent
17488     * @param t Top position, relative to parent
17489     * @param r Right position, relative to parent
17490     * @param b Bottom position, relative to parent
17491     */
17492    @SuppressWarnings({"unchecked"})
17493    public void layout(int l, int t, int r, int b) {
17494        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17495            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17496            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17497        }
17498
17499        int oldL = mLeft;
17500        int oldT = mTop;
17501        int oldB = mBottom;
17502        int oldR = mRight;
17503
17504        boolean changed = isLayoutModeOptical(mParent) ?
17505                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17506
17507        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17508            onLayout(changed, l, t, r, b);
17509            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17510
17511            ListenerInfo li = mListenerInfo;
17512            if (li != null && li.mOnLayoutChangeListeners != null) {
17513                ArrayList<OnLayoutChangeListener> listenersCopy =
17514                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17515                int numListeners = listenersCopy.size();
17516                for (int i = 0; i < numListeners; ++i) {
17517                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17518                }
17519            }
17520        }
17521
17522        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17523        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17524    }
17525
17526    /**
17527     * Called from layout when this view should
17528     * assign a size and position to each of its children.
17529     *
17530     * Derived classes with children should override
17531     * this method and call layout on each of
17532     * their children.
17533     * @param changed This is a new size or position for this view
17534     * @param left Left position, relative to parent
17535     * @param top Top position, relative to parent
17536     * @param right Right position, relative to parent
17537     * @param bottom Bottom position, relative to parent
17538     */
17539    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17540    }
17541
17542    /**
17543     * Assign a size and position to this view.
17544     *
17545     * This is called from layout.
17546     *
17547     * @param left Left position, relative to parent
17548     * @param top Top position, relative to parent
17549     * @param right Right position, relative to parent
17550     * @param bottom Bottom position, relative to parent
17551     * @return true if the new size and position are different than the
17552     *         previous ones
17553     * {@hide}
17554     */
17555    protected boolean setFrame(int left, int top, int right, int bottom) {
17556        boolean changed = false;
17557
17558        if (DBG) {
17559            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17560                    + right + "," + bottom + ")");
17561        }
17562
17563        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17564            changed = true;
17565
17566            // Remember our drawn bit
17567            int drawn = mPrivateFlags & PFLAG_DRAWN;
17568
17569            int oldWidth = mRight - mLeft;
17570            int oldHeight = mBottom - mTop;
17571            int newWidth = right - left;
17572            int newHeight = bottom - top;
17573            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17574
17575            // Invalidate our old position
17576            invalidate(sizeChanged);
17577
17578            mLeft = left;
17579            mTop = top;
17580            mRight = right;
17581            mBottom = bottom;
17582            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17583
17584            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17585
17586
17587            if (sizeChanged) {
17588                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17589            }
17590
17591            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17592                // If we are visible, force the DRAWN bit to on so that
17593                // this invalidate will go through (at least to our parent).
17594                // This is because someone may have invalidated this view
17595                // before this call to setFrame came in, thereby clearing
17596                // the DRAWN bit.
17597                mPrivateFlags |= PFLAG_DRAWN;
17598                invalidate(sizeChanged);
17599                // parent display list may need to be recreated based on a change in the bounds
17600                // of any child
17601                invalidateParentCaches();
17602            }
17603
17604            // Reset drawn bit to original value (invalidate turns it off)
17605            mPrivateFlags |= drawn;
17606
17607            mBackgroundSizeChanged = true;
17608            if (mForegroundInfo != null) {
17609                mForegroundInfo.mBoundsChanged = true;
17610            }
17611
17612            notifySubtreeAccessibilityStateChangedIfNeeded();
17613        }
17614        return changed;
17615    }
17616
17617    /**
17618     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17619     * @hide
17620     */
17621    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17622        setFrame(left, top, right, bottom);
17623    }
17624
17625    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17626        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17627        if (mOverlay != null) {
17628            mOverlay.getOverlayView().setRight(newWidth);
17629            mOverlay.getOverlayView().setBottom(newHeight);
17630        }
17631        rebuildOutline();
17632    }
17633
17634    /**
17635     * Finalize inflating a view from XML.  This is called as the last phase
17636     * of inflation, after all child views have been added.
17637     *
17638     * <p>Even if the subclass overrides onFinishInflate, they should always be
17639     * sure to call the super method, so that we get called.
17640     */
17641    @CallSuper
17642    protected void onFinishInflate() {
17643    }
17644
17645    /**
17646     * Returns the resources associated with this view.
17647     *
17648     * @return Resources object.
17649     */
17650    public Resources getResources() {
17651        return mResources;
17652    }
17653
17654    /**
17655     * Invalidates the specified Drawable.
17656     *
17657     * @param drawable the drawable to invalidate
17658     */
17659    @Override
17660    public void invalidateDrawable(@NonNull Drawable drawable) {
17661        if (verifyDrawable(drawable)) {
17662            final Rect dirty = drawable.getDirtyBounds();
17663            final int scrollX = mScrollX;
17664            final int scrollY = mScrollY;
17665
17666            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17667                    dirty.right + scrollX, dirty.bottom + scrollY);
17668            rebuildOutline();
17669        }
17670    }
17671
17672    /**
17673     * Schedules an action on a drawable to occur at a specified time.
17674     *
17675     * @param who the recipient of the action
17676     * @param what the action to run on the drawable
17677     * @param when the time at which the action must occur. Uses the
17678     *        {@link SystemClock#uptimeMillis} timebase.
17679     */
17680    @Override
17681    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17682        if (verifyDrawable(who) && what != null) {
17683            final long delay = when - SystemClock.uptimeMillis();
17684            if (mAttachInfo != null) {
17685                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17686                        Choreographer.CALLBACK_ANIMATION, what, who,
17687                        Choreographer.subtractFrameDelay(delay));
17688            } else {
17689                // Postpone the runnable until we know
17690                // on which thread it needs to run.
17691                getRunQueue().postDelayed(what, delay);
17692            }
17693        }
17694    }
17695
17696    /**
17697     * Cancels a scheduled action on a drawable.
17698     *
17699     * @param who the recipient of the action
17700     * @param what the action to cancel
17701     */
17702    @Override
17703    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17704        if (verifyDrawable(who) && what != null) {
17705            if (mAttachInfo != null) {
17706                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17707                        Choreographer.CALLBACK_ANIMATION, what, who);
17708            }
17709            getRunQueue().removeCallbacks(what);
17710        }
17711    }
17712
17713    /**
17714     * Unschedule any events associated with the given Drawable.  This can be
17715     * used when selecting a new Drawable into a view, so that the previous
17716     * one is completely unscheduled.
17717     *
17718     * @param who The Drawable to unschedule.
17719     *
17720     * @see #drawableStateChanged
17721     */
17722    public void unscheduleDrawable(Drawable who) {
17723        if (mAttachInfo != null && who != null) {
17724            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17725                    Choreographer.CALLBACK_ANIMATION, null, who);
17726        }
17727    }
17728
17729    /**
17730     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17731     * that the View directionality can and will be resolved before its Drawables.
17732     *
17733     * Will call {@link View#onResolveDrawables} when resolution is done.
17734     *
17735     * @hide
17736     */
17737    protected void resolveDrawables() {
17738        // Drawables resolution may need to happen before resolving the layout direction (which is
17739        // done only during the measure() call).
17740        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17741        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17742        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17743        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17744        // direction to be resolved as its resolved value will be the same as its raw value.
17745        if (!isLayoutDirectionResolved() &&
17746                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17747            return;
17748        }
17749
17750        final int layoutDirection = isLayoutDirectionResolved() ?
17751                getLayoutDirection() : getRawLayoutDirection();
17752
17753        if (mBackground != null) {
17754            mBackground.setLayoutDirection(layoutDirection);
17755        }
17756        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17757            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17758        }
17759        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17760        onResolveDrawables(layoutDirection);
17761    }
17762
17763    boolean areDrawablesResolved() {
17764        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17765    }
17766
17767    /**
17768     * Called when layout direction has been resolved.
17769     *
17770     * The default implementation does nothing.
17771     *
17772     * @param layoutDirection The resolved layout direction.
17773     *
17774     * @see #LAYOUT_DIRECTION_LTR
17775     * @see #LAYOUT_DIRECTION_RTL
17776     *
17777     * @hide
17778     */
17779    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17780    }
17781
17782    /**
17783     * @hide
17784     */
17785    protected void resetResolvedDrawables() {
17786        resetResolvedDrawablesInternal();
17787    }
17788
17789    void resetResolvedDrawablesInternal() {
17790        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17791    }
17792
17793    /**
17794     * If your view subclass is displaying its own Drawable objects, it should
17795     * override this function and return true for any Drawable it is
17796     * displaying.  This allows animations for those drawables to be
17797     * scheduled.
17798     *
17799     * <p>Be sure to call through to the super class when overriding this
17800     * function.
17801     *
17802     * @param who The Drawable to verify.  Return true if it is one you are
17803     *            displaying, else return the result of calling through to the
17804     *            super class.
17805     *
17806     * @return boolean If true than the Drawable is being displayed in the
17807     *         view; else false and it is not allowed to animate.
17808     *
17809     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17810     * @see #drawableStateChanged()
17811     */
17812    @CallSuper
17813    protected boolean verifyDrawable(@NonNull Drawable who) {
17814        // Avoid verifying the scroll bar drawable so that we don't end up in
17815        // an invalidation loop. This effectively prevents the scroll bar
17816        // drawable from triggering invalidations and scheduling runnables.
17817        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17818    }
17819
17820    /**
17821     * This function is called whenever the state of the view changes in such
17822     * a way that it impacts the state of drawables being shown.
17823     * <p>
17824     * If the View has a StateListAnimator, it will also be called to run necessary state
17825     * change animations.
17826     * <p>
17827     * Be sure to call through to the superclass when overriding this function.
17828     *
17829     * @see Drawable#setState(int[])
17830     */
17831    @CallSuper
17832    protected void drawableStateChanged() {
17833        final int[] state = getDrawableState();
17834        boolean changed = false;
17835
17836        final Drawable bg = mBackground;
17837        if (bg != null && bg.isStateful()) {
17838            changed |= bg.setState(state);
17839        }
17840
17841        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17842        if (fg != null && fg.isStateful()) {
17843            changed |= fg.setState(state);
17844        }
17845
17846        if (mScrollCache != null) {
17847            final Drawable scrollBar = mScrollCache.scrollBar;
17848            if (scrollBar != null && scrollBar.isStateful()) {
17849                changed |= scrollBar.setState(state)
17850                        && mScrollCache.state != ScrollabilityCache.OFF;
17851            }
17852        }
17853
17854        if (mStateListAnimator != null) {
17855            mStateListAnimator.setState(state);
17856        }
17857
17858        if (changed) {
17859            invalidate();
17860        }
17861    }
17862
17863    /**
17864     * This function is called whenever the view hotspot changes and needs to
17865     * be propagated to drawables or child views managed by the view.
17866     * <p>
17867     * Dispatching to child views is handled by
17868     * {@link #dispatchDrawableHotspotChanged(float, float)}.
17869     * <p>
17870     * Be sure to call through to the superclass when overriding this function.
17871     *
17872     * @param x hotspot x coordinate
17873     * @param y hotspot y coordinate
17874     */
17875    @CallSuper
17876    public void drawableHotspotChanged(float x, float y) {
17877        if (mBackground != null) {
17878            mBackground.setHotspot(x, y);
17879        }
17880        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17881            mForegroundInfo.mDrawable.setHotspot(x, y);
17882        }
17883
17884        dispatchDrawableHotspotChanged(x, y);
17885    }
17886
17887    /**
17888     * Dispatches drawableHotspotChanged to all of this View's children.
17889     *
17890     * @param x hotspot x coordinate
17891     * @param y hotspot y coordinate
17892     * @see #drawableHotspotChanged(float, float)
17893     */
17894    public void dispatchDrawableHotspotChanged(float x, float y) {
17895    }
17896
17897    /**
17898     * Call this to force a view to update its drawable state. This will cause
17899     * drawableStateChanged to be called on this view. Views that are interested
17900     * in the new state should call getDrawableState.
17901     *
17902     * @see #drawableStateChanged
17903     * @see #getDrawableState
17904     */
17905    public void refreshDrawableState() {
17906        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17907        drawableStateChanged();
17908
17909        ViewParent parent = mParent;
17910        if (parent != null) {
17911            parent.childDrawableStateChanged(this);
17912        }
17913    }
17914
17915    /**
17916     * Return an array of resource IDs of the drawable states representing the
17917     * current state of the view.
17918     *
17919     * @return The current drawable state
17920     *
17921     * @see Drawable#setState(int[])
17922     * @see #drawableStateChanged()
17923     * @see #onCreateDrawableState(int)
17924     */
17925    public final int[] getDrawableState() {
17926        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17927            return mDrawableState;
17928        } else {
17929            mDrawableState = onCreateDrawableState(0);
17930            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17931            return mDrawableState;
17932        }
17933    }
17934
17935    /**
17936     * Generate the new {@link android.graphics.drawable.Drawable} state for
17937     * this view. This is called by the view
17938     * system when the cached Drawable state is determined to be invalid.  To
17939     * retrieve the current state, you should use {@link #getDrawableState}.
17940     *
17941     * @param extraSpace if non-zero, this is the number of extra entries you
17942     * would like in the returned array in which you can place your own
17943     * states.
17944     *
17945     * @return Returns an array holding the current {@link Drawable} state of
17946     * the view.
17947     *
17948     * @see #mergeDrawableStates(int[], int[])
17949     */
17950    protected int[] onCreateDrawableState(int extraSpace) {
17951        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17952                mParent instanceof View) {
17953            return ((View) mParent).onCreateDrawableState(extraSpace);
17954        }
17955
17956        int[] drawableState;
17957
17958        int privateFlags = mPrivateFlags;
17959
17960        int viewStateIndex = 0;
17961        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17962        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17963        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17964        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17965        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17966        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17967        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17968                ThreadedRenderer.isAvailable()) {
17969            // This is set if HW acceleration is requested, even if the current
17970            // process doesn't allow it.  This is just to allow app preview
17971            // windows to better match their app.
17972            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17973        }
17974        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17975
17976        final int privateFlags2 = mPrivateFlags2;
17977        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17978            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17979        }
17980        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17981            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17982        }
17983
17984        drawableState = StateSet.get(viewStateIndex);
17985
17986        //noinspection ConstantIfStatement
17987        if (false) {
17988            Log.i("View", "drawableStateIndex=" + viewStateIndex);
17989            Log.i("View", toString()
17990                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
17991                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
17992                    + " fo=" + hasFocus()
17993                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
17994                    + " wf=" + hasWindowFocus()
17995                    + ": " + Arrays.toString(drawableState));
17996        }
17997
17998        if (extraSpace == 0) {
17999            return drawableState;
18000        }
18001
18002        final int[] fullState;
18003        if (drawableState != null) {
18004            fullState = new int[drawableState.length + extraSpace];
18005            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18006        } else {
18007            fullState = new int[extraSpace];
18008        }
18009
18010        return fullState;
18011    }
18012
18013    /**
18014     * Merge your own state values in <var>additionalState</var> into the base
18015     * state values <var>baseState</var> that were returned by
18016     * {@link #onCreateDrawableState(int)}.
18017     *
18018     * @param baseState The base state values returned by
18019     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18020     * own additional state values.
18021     *
18022     * @param additionalState The additional state values you would like
18023     * added to <var>baseState</var>; this array is not modified.
18024     *
18025     * @return As a convenience, the <var>baseState</var> array you originally
18026     * passed into the function is returned.
18027     *
18028     * @see #onCreateDrawableState(int)
18029     */
18030    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18031        final int N = baseState.length;
18032        int i = N - 1;
18033        while (i >= 0 && baseState[i] == 0) {
18034            i--;
18035        }
18036        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18037        return baseState;
18038    }
18039
18040    /**
18041     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18042     * on all Drawable objects associated with this view.
18043     * <p>
18044     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18045     * attached to this view.
18046     */
18047    @CallSuper
18048    public void jumpDrawablesToCurrentState() {
18049        if (mBackground != null) {
18050            mBackground.jumpToCurrentState();
18051        }
18052        if (mStateListAnimator != null) {
18053            mStateListAnimator.jumpToCurrentState();
18054        }
18055        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18056            mForegroundInfo.mDrawable.jumpToCurrentState();
18057        }
18058    }
18059
18060    /**
18061     * Sets the background color for this view.
18062     * @param color the color of the background
18063     */
18064    @RemotableViewMethod
18065    public void setBackgroundColor(@ColorInt int color) {
18066        if (mBackground instanceof ColorDrawable) {
18067            ((ColorDrawable) mBackground.mutate()).setColor(color);
18068            computeOpaqueFlags();
18069            mBackgroundResource = 0;
18070        } else {
18071            setBackground(new ColorDrawable(color));
18072        }
18073    }
18074
18075    /**
18076     * Set the background to a given resource. The resource should refer to
18077     * a Drawable object or 0 to remove the background.
18078     * @param resid The identifier of the resource.
18079     *
18080     * @attr ref android.R.styleable#View_background
18081     */
18082    @RemotableViewMethod
18083    public void setBackgroundResource(@DrawableRes int resid) {
18084        if (resid != 0 && resid == mBackgroundResource) {
18085            return;
18086        }
18087
18088        Drawable d = null;
18089        if (resid != 0) {
18090            d = mContext.getDrawable(resid);
18091        }
18092        setBackground(d);
18093
18094        mBackgroundResource = resid;
18095    }
18096
18097    /**
18098     * Set the background to a given Drawable, or remove the background. If the
18099     * background has padding, this View's padding is set to the background's
18100     * padding. However, when a background is removed, this View's padding isn't
18101     * touched. If setting the padding is desired, please use
18102     * {@link #setPadding(int, int, int, int)}.
18103     *
18104     * @param background The Drawable to use as the background, or null to remove the
18105     *        background
18106     */
18107    public void setBackground(Drawable background) {
18108        //noinspection deprecation
18109        setBackgroundDrawable(background);
18110    }
18111
18112    /**
18113     * @deprecated use {@link #setBackground(Drawable)} instead
18114     */
18115    @Deprecated
18116    public void setBackgroundDrawable(Drawable background) {
18117        computeOpaqueFlags();
18118
18119        if (background == mBackground) {
18120            return;
18121        }
18122
18123        boolean requestLayout = false;
18124
18125        mBackgroundResource = 0;
18126
18127        /*
18128         * Regardless of whether we're setting a new background or not, we want
18129         * to clear the previous drawable. setVisible first while we still have the callback set.
18130         */
18131        if (mBackground != null) {
18132            if (isAttachedToWindow()) {
18133                mBackground.setVisible(false, false);
18134            }
18135            mBackground.setCallback(null);
18136            unscheduleDrawable(mBackground);
18137        }
18138
18139        if (background != null) {
18140            Rect padding = sThreadLocal.get();
18141            if (padding == null) {
18142                padding = new Rect();
18143                sThreadLocal.set(padding);
18144            }
18145            resetResolvedDrawablesInternal();
18146            background.setLayoutDirection(getLayoutDirection());
18147            if (background.getPadding(padding)) {
18148                resetResolvedPaddingInternal();
18149                switch (background.getLayoutDirection()) {
18150                    case LAYOUT_DIRECTION_RTL:
18151                        mUserPaddingLeftInitial = padding.right;
18152                        mUserPaddingRightInitial = padding.left;
18153                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18154                        break;
18155                    case LAYOUT_DIRECTION_LTR:
18156                    default:
18157                        mUserPaddingLeftInitial = padding.left;
18158                        mUserPaddingRightInitial = padding.right;
18159                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18160                }
18161                mLeftPaddingDefined = false;
18162                mRightPaddingDefined = false;
18163            }
18164
18165            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18166            // if it has a different minimum size, we should layout again
18167            if (mBackground == null
18168                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18169                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18170                requestLayout = true;
18171            }
18172
18173            // Set mBackground before we set this as the callback and start making other
18174            // background drawable state change calls. In particular, the setVisible call below
18175            // can result in drawables attempting to start animations or otherwise invalidate,
18176            // which requires the view set as the callback (us) to recognize the drawable as
18177            // belonging to it as per verifyDrawable.
18178            mBackground = background;
18179            if (background.isStateful()) {
18180                background.setState(getDrawableState());
18181            }
18182            if (isAttachedToWindow()) {
18183                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18184            }
18185
18186            applyBackgroundTint();
18187
18188            // Set callback last, since the view may still be initializing.
18189            background.setCallback(this);
18190
18191            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18192                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18193                requestLayout = true;
18194            }
18195        } else {
18196            /* Remove the background */
18197            mBackground = null;
18198            if ((mViewFlags & WILL_NOT_DRAW) != 0
18199                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18200                mPrivateFlags |= PFLAG_SKIP_DRAW;
18201            }
18202
18203            /*
18204             * When the background is set, we try to apply its padding to this
18205             * View. When the background is removed, we don't touch this View's
18206             * padding. This is noted in the Javadocs. Hence, we don't need to
18207             * requestLayout(), the invalidate() below is sufficient.
18208             */
18209
18210            // The old background's minimum size could have affected this
18211            // View's layout, so let's requestLayout
18212            requestLayout = true;
18213        }
18214
18215        computeOpaqueFlags();
18216
18217        if (requestLayout) {
18218            requestLayout();
18219        }
18220
18221        mBackgroundSizeChanged = true;
18222        invalidate(true);
18223        invalidateOutline();
18224    }
18225
18226    /**
18227     * Gets the background drawable
18228     *
18229     * @return The drawable used as the background for this view, if any.
18230     *
18231     * @see #setBackground(Drawable)
18232     *
18233     * @attr ref android.R.styleable#View_background
18234     */
18235    public Drawable getBackground() {
18236        return mBackground;
18237    }
18238
18239    /**
18240     * Applies a tint to the background drawable. Does not modify the current tint
18241     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18242     * <p>
18243     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18244     * mutate the drawable and apply the specified tint and tint mode using
18245     * {@link Drawable#setTintList(ColorStateList)}.
18246     *
18247     * @param tint the tint to apply, may be {@code null} to clear tint
18248     *
18249     * @attr ref android.R.styleable#View_backgroundTint
18250     * @see #getBackgroundTintList()
18251     * @see Drawable#setTintList(ColorStateList)
18252     */
18253    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18254        if (mBackgroundTint == null) {
18255            mBackgroundTint = new TintInfo();
18256        }
18257        mBackgroundTint.mTintList = tint;
18258        mBackgroundTint.mHasTintList = true;
18259
18260        applyBackgroundTint();
18261    }
18262
18263    /**
18264     * Return the tint applied to the background drawable, if specified.
18265     *
18266     * @return the tint applied to the background drawable
18267     * @attr ref android.R.styleable#View_backgroundTint
18268     * @see #setBackgroundTintList(ColorStateList)
18269     */
18270    @Nullable
18271    public ColorStateList getBackgroundTintList() {
18272        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18273    }
18274
18275    /**
18276     * Specifies the blending mode used to apply the tint specified by
18277     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18278     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18279     *
18280     * @param tintMode the blending mode used to apply the tint, may be
18281     *                 {@code null} to clear tint
18282     * @attr ref android.R.styleable#View_backgroundTintMode
18283     * @see #getBackgroundTintMode()
18284     * @see Drawable#setTintMode(PorterDuff.Mode)
18285     */
18286    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18287        if (mBackgroundTint == null) {
18288            mBackgroundTint = new TintInfo();
18289        }
18290        mBackgroundTint.mTintMode = tintMode;
18291        mBackgroundTint.mHasTintMode = true;
18292
18293        applyBackgroundTint();
18294    }
18295
18296    /**
18297     * Return the blending mode used to apply the tint to the background
18298     * drawable, if specified.
18299     *
18300     * @return the blending mode used to apply the tint to the background
18301     *         drawable
18302     * @attr ref android.R.styleable#View_backgroundTintMode
18303     * @see #setBackgroundTintMode(PorterDuff.Mode)
18304     */
18305    @Nullable
18306    public PorterDuff.Mode getBackgroundTintMode() {
18307        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18308    }
18309
18310    private void applyBackgroundTint() {
18311        if (mBackground != null && mBackgroundTint != null) {
18312            final TintInfo tintInfo = mBackgroundTint;
18313            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18314                mBackground = mBackground.mutate();
18315
18316                if (tintInfo.mHasTintList) {
18317                    mBackground.setTintList(tintInfo.mTintList);
18318                }
18319
18320                if (tintInfo.mHasTintMode) {
18321                    mBackground.setTintMode(tintInfo.mTintMode);
18322                }
18323
18324                // The drawable (or one of its children) may not have been
18325                // stateful before applying the tint, so let's try again.
18326                if (mBackground.isStateful()) {
18327                    mBackground.setState(getDrawableState());
18328                }
18329            }
18330        }
18331    }
18332
18333    /**
18334     * Returns the drawable used as the foreground of this View. The
18335     * foreground drawable, if non-null, is always drawn on top of the view's content.
18336     *
18337     * @return a Drawable or null if no foreground was set
18338     *
18339     * @see #onDrawForeground(Canvas)
18340     */
18341    public Drawable getForeground() {
18342        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18343    }
18344
18345    /**
18346     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18347     *
18348     * @param foreground the Drawable to be drawn on top of the children
18349     *
18350     * @attr ref android.R.styleable#View_foreground
18351     */
18352    public void setForeground(Drawable foreground) {
18353        if (mForegroundInfo == null) {
18354            if (foreground == null) {
18355                // Nothing to do.
18356                return;
18357            }
18358            mForegroundInfo = new ForegroundInfo();
18359        }
18360
18361        if (foreground == mForegroundInfo.mDrawable) {
18362            // Nothing to do
18363            return;
18364        }
18365
18366        if (mForegroundInfo.mDrawable != null) {
18367            if (isAttachedToWindow()) {
18368                mForegroundInfo.mDrawable.setVisible(false, false);
18369            }
18370            mForegroundInfo.mDrawable.setCallback(null);
18371            unscheduleDrawable(mForegroundInfo.mDrawable);
18372        }
18373
18374        mForegroundInfo.mDrawable = foreground;
18375        mForegroundInfo.mBoundsChanged = true;
18376        if (foreground != null) {
18377            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18378                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18379            }
18380            foreground.setLayoutDirection(getLayoutDirection());
18381            if (foreground.isStateful()) {
18382                foreground.setState(getDrawableState());
18383            }
18384            applyForegroundTint();
18385            if (isAttachedToWindow()) {
18386                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18387            }
18388            // Set callback last, since the view may still be initializing.
18389            foreground.setCallback(this);
18390        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18391            mPrivateFlags |= PFLAG_SKIP_DRAW;
18392        }
18393        requestLayout();
18394        invalidate();
18395    }
18396
18397    /**
18398     * Magic bit used to support features of framework-internal window decor implementation details.
18399     * This used to live exclusively in FrameLayout.
18400     *
18401     * @return true if the foreground should draw inside the padding region or false
18402     *         if it should draw inset by the view's padding
18403     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18404     */
18405    public boolean isForegroundInsidePadding() {
18406        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18407    }
18408
18409    /**
18410     * Describes how the foreground is positioned.
18411     *
18412     * @return foreground gravity.
18413     *
18414     * @see #setForegroundGravity(int)
18415     *
18416     * @attr ref android.R.styleable#View_foregroundGravity
18417     */
18418    public int getForegroundGravity() {
18419        return mForegroundInfo != null ? mForegroundInfo.mGravity
18420                : Gravity.START | Gravity.TOP;
18421    }
18422
18423    /**
18424     * Describes how the foreground is positioned. Defaults to START and TOP.
18425     *
18426     * @param gravity see {@link android.view.Gravity}
18427     *
18428     * @see #getForegroundGravity()
18429     *
18430     * @attr ref android.R.styleable#View_foregroundGravity
18431     */
18432    public void setForegroundGravity(int gravity) {
18433        if (mForegroundInfo == null) {
18434            mForegroundInfo = new ForegroundInfo();
18435        }
18436
18437        if (mForegroundInfo.mGravity != gravity) {
18438            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18439                gravity |= Gravity.START;
18440            }
18441
18442            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18443                gravity |= Gravity.TOP;
18444            }
18445
18446            mForegroundInfo.mGravity = gravity;
18447            requestLayout();
18448        }
18449    }
18450
18451    /**
18452     * Applies a tint to the foreground drawable. Does not modify the current tint
18453     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18454     * <p>
18455     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18456     * mutate the drawable and apply the specified tint and tint mode using
18457     * {@link Drawable#setTintList(ColorStateList)}.
18458     *
18459     * @param tint the tint to apply, may be {@code null} to clear tint
18460     *
18461     * @attr ref android.R.styleable#View_foregroundTint
18462     * @see #getForegroundTintList()
18463     * @see Drawable#setTintList(ColorStateList)
18464     */
18465    public void setForegroundTintList(@Nullable ColorStateList tint) {
18466        if (mForegroundInfo == null) {
18467            mForegroundInfo = new ForegroundInfo();
18468        }
18469        if (mForegroundInfo.mTintInfo == null) {
18470            mForegroundInfo.mTintInfo = new TintInfo();
18471        }
18472        mForegroundInfo.mTintInfo.mTintList = tint;
18473        mForegroundInfo.mTintInfo.mHasTintList = true;
18474
18475        applyForegroundTint();
18476    }
18477
18478    /**
18479     * Return the tint applied to the foreground drawable, if specified.
18480     *
18481     * @return the tint applied to the foreground drawable
18482     * @attr ref android.R.styleable#View_foregroundTint
18483     * @see #setForegroundTintList(ColorStateList)
18484     */
18485    @Nullable
18486    public ColorStateList getForegroundTintList() {
18487        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18488                ? mForegroundInfo.mTintInfo.mTintList : null;
18489    }
18490
18491    /**
18492     * Specifies the blending mode used to apply the tint specified by
18493     * {@link #setForegroundTintList(ColorStateList)}} to the background
18494     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18495     *
18496     * @param tintMode the blending mode used to apply the tint, may be
18497     *                 {@code null} to clear tint
18498     * @attr ref android.R.styleable#View_foregroundTintMode
18499     * @see #getForegroundTintMode()
18500     * @see Drawable#setTintMode(PorterDuff.Mode)
18501     */
18502    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18503        if (mForegroundInfo == null) {
18504            mForegroundInfo = new ForegroundInfo();
18505        }
18506        if (mForegroundInfo.mTintInfo == null) {
18507            mForegroundInfo.mTintInfo = new TintInfo();
18508        }
18509        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18510        mForegroundInfo.mTintInfo.mHasTintMode = true;
18511
18512        applyForegroundTint();
18513    }
18514
18515    /**
18516     * Return the blending mode used to apply the tint to the foreground
18517     * drawable, if specified.
18518     *
18519     * @return the blending mode used to apply the tint to the foreground
18520     *         drawable
18521     * @attr ref android.R.styleable#View_foregroundTintMode
18522     * @see #setForegroundTintMode(PorterDuff.Mode)
18523     */
18524    @Nullable
18525    public PorterDuff.Mode getForegroundTintMode() {
18526        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18527                ? mForegroundInfo.mTintInfo.mTintMode : null;
18528    }
18529
18530    private void applyForegroundTint() {
18531        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18532                && mForegroundInfo.mTintInfo != null) {
18533            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18534            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18535                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18536
18537                if (tintInfo.mHasTintList) {
18538                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18539                }
18540
18541                if (tintInfo.mHasTintMode) {
18542                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18543                }
18544
18545                // The drawable (or one of its children) may not have been
18546                // stateful before applying the tint, so let's try again.
18547                if (mForegroundInfo.mDrawable.isStateful()) {
18548                    mForegroundInfo.mDrawable.setState(getDrawableState());
18549                }
18550            }
18551        }
18552    }
18553
18554    /**
18555     * Draw any foreground content for this view.
18556     *
18557     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18558     * drawable or other view-specific decorations. The foreground is drawn on top of the
18559     * primary view content.</p>
18560     *
18561     * @param canvas canvas to draw into
18562     */
18563    public void onDrawForeground(Canvas canvas) {
18564        onDrawScrollIndicators(canvas);
18565        onDrawScrollBars(canvas);
18566
18567        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18568        if (foreground != null) {
18569            if (mForegroundInfo.mBoundsChanged) {
18570                mForegroundInfo.mBoundsChanged = false;
18571                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18572                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18573
18574                if (mForegroundInfo.mInsidePadding) {
18575                    selfBounds.set(0, 0, getWidth(), getHeight());
18576                } else {
18577                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18578                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18579                }
18580
18581                final int ld = getLayoutDirection();
18582                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18583                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18584                foreground.setBounds(overlayBounds);
18585            }
18586
18587            foreground.draw(canvas);
18588        }
18589    }
18590
18591    /**
18592     * Sets the padding. The view may add on the space required to display
18593     * the scrollbars, depending on the style and visibility of the scrollbars.
18594     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18595     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18596     * from the values set in this call.
18597     *
18598     * @attr ref android.R.styleable#View_padding
18599     * @attr ref android.R.styleable#View_paddingBottom
18600     * @attr ref android.R.styleable#View_paddingLeft
18601     * @attr ref android.R.styleable#View_paddingRight
18602     * @attr ref android.R.styleable#View_paddingTop
18603     * @param left the left padding in pixels
18604     * @param top the top padding in pixels
18605     * @param right the right padding in pixels
18606     * @param bottom the bottom padding in pixels
18607     */
18608    public void setPadding(int left, int top, int right, int bottom) {
18609        resetResolvedPaddingInternal();
18610
18611        mUserPaddingStart = UNDEFINED_PADDING;
18612        mUserPaddingEnd = UNDEFINED_PADDING;
18613
18614        mUserPaddingLeftInitial = left;
18615        mUserPaddingRightInitial = right;
18616
18617        mLeftPaddingDefined = true;
18618        mRightPaddingDefined = true;
18619
18620        internalSetPadding(left, top, right, bottom);
18621    }
18622
18623    /**
18624     * @hide
18625     */
18626    protected void internalSetPadding(int left, int top, int right, int bottom) {
18627        mUserPaddingLeft = left;
18628        mUserPaddingRight = right;
18629        mUserPaddingBottom = bottom;
18630
18631        final int viewFlags = mViewFlags;
18632        boolean changed = false;
18633
18634        // Common case is there are no scroll bars.
18635        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18636            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18637                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18638                        ? 0 : getVerticalScrollbarWidth();
18639                switch (mVerticalScrollbarPosition) {
18640                    case SCROLLBAR_POSITION_DEFAULT:
18641                        if (isLayoutRtl()) {
18642                            left += offset;
18643                        } else {
18644                            right += offset;
18645                        }
18646                        break;
18647                    case SCROLLBAR_POSITION_RIGHT:
18648                        right += offset;
18649                        break;
18650                    case SCROLLBAR_POSITION_LEFT:
18651                        left += offset;
18652                        break;
18653                }
18654            }
18655            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18656                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18657                        ? 0 : getHorizontalScrollbarHeight();
18658            }
18659        }
18660
18661        if (mPaddingLeft != left) {
18662            changed = true;
18663            mPaddingLeft = left;
18664        }
18665        if (mPaddingTop != top) {
18666            changed = true;
18667            mPaddingTop = top;
18668        }
18669        if (mPaddingRight != right) {
18670            changed = true;
18671            mPaddingRight = right;
18672        }
18673        if (mPaddingBottom != bottom) {
18674            changed = true;
18675            mPaddingBottom = bottom;
18676        }
18677
18678        if (changed) {
18679            requestLayout();
18680            invalidateOutline();
18681        }
18682    }
18683
18684    /**
18685     * Sets the relative padding. The view may add on the space required to display
18686     * the scrollbars, depending on the style and visibility of the scrollbars.
18687     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18688     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18689     * from the values set in this call.
18690     *
18691     * @attr ref android.R.styleable#View_padding
18692     * @attr ref android.R.styleable#View_paddingBottom
18693     * @attr ref android.R.styleable#View_paddingStart
18694     * @attr ref android.R.styleable#View_paddingEnd
18695     * @attr ref android.R.styleable#View_paddingTop
18696     * @param start the start padding in pixels
18697     * @param top the top padding in pixels
18698     * @param end the end padding in pixels
18699     * @param bottom the bottom padding in pixels
18700     */
18701    public void setPaddingRelative(int start, int top, int end, int bottom) {
18702        resetResolvedPaddingInternal();
18703
18704        mUserPaddingStart = start;
18705        mUserPaddingEnd = end;
18706        mLeftPaddingDefined = true;
18707        mRightPaddingDefined = true;
18708
18709        switch(getLayoutDirection()) {
18710            case LAYOUT_DIRECTION_RTL:
18711                mUserPaddingLeftInitial = end;
18712                mUserPaddingRightInitial = start;
18713                internalSetPadding(end, top, start, bottom);
18714                break;
18715            case LAYOUT_DIRECTION_LTR:
18716            default:
18717                mUserPaddingLeftInitial = start;
18718                mUserPaddingRightInitial = end;
18719                internalSetPadding(start, top, end, bottom);
18720        }
18721    }
18722
18723    /**
18724     * Returns the top padding of this view.
18725     *
18726     * @return the top padding in pixels
18727     */
18728    public int getPaddingTop() {
18729        return mPaddingTop;
18730    }
18731
18732    /**
18733     * Returns the bottom padding of this view. If there are inset and enabled
18734     * scrollbars, this value may include the space required to display the
18735     * scrollbars as well.
18736     *
18737     * @return the bottom padding in pixels
18738     */
18739    public int getPaddingBottom() {
18740        return mPaddingBottom;
18741    }
18742
18743    /**
18744     * Returns the left padding of this view. If there are inset and enabled
18745     * scrollbars, this value may include the space required to display the
18746     * scrollbars as well.
18747     *
18748     * @return the left padding in pixels
18749     */
18750    public int getPaddingLeft() {
18751        if (!isPaddingResolved()) {
18752            resolvePadding();
18753        }
18754        return mPaddingLeft;
18755    }
18756
18757    /**
18758     * Returns the start padding of this view depending on its resolved layout direction.
18759     * If there are inset and enabled scrollbars, this value may include the space
18760     * required to display the scrollbars as well.
18761     *
18762     * @return the start padding in pixels
18763     */
18764    public int getPaddingStart() {
18765        if (!isPaddingResolved()) {
18766            resolvePadding();
18767        }
18768        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18769                mPaddingRight : mPaddingLeft;
18770    }
18771
18772    /**
18773     * Returns the right padding of this view. If there are inset and enabled
18774     * scrollbars, this value may include the space required to display the
18775     * scrollbars as well.
18776     *
18777     * @return the right padding in pixels
18778     */
18779    public int getPaddingRight() {
18780        if (!isPaddingResolved()) {
18781            resolvePadding();
18782        }
18783        return mPaddingRight;
18784    }
18785
18786    /**
18787     * Returns the end padding of this view depending on its resolved layout direction.
18788     * If there are inset and enabled scrollbars, this value may include the space
18789     * required to display the scrollbars as well.
18790     *
18791     * @return the end padding in pixels
18792     */
18793    public int getPaddingEnd() {
18794        if (!isPaddingResolved()) {
18795            resolvePadding();
18796        }
18797        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18798                mPaddingLeft : mPaddingRight;
18799    }
18800
18801    /**
18802     * Return if the padding has been set through relative values
18803     * {@link #setPaddingRelative(int, int, int, int)} or through
18804     * @attr ref android.R.styleable#View_paddingStart or
18805     * @attr ref android.R.styleable#View_paddingEnd
18806     *
18807     * @return true if the padding is relative or false if it is not.
18808     */
18809    public boolean isPaddingRelative() {
18810        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18811    }
18812
18813    Insets computeOpticalInsets() {
18814        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18815    }
18816
18817    /**
18818     * @hide
18819     */
18820    public void resetPaddingToInitialValues() {
18821        if (isRtlCompatibilityMode()) {
18822            mPaddingLeft = mUserPaddingLeftInitial;
18823            mPaddingRight = mUserPaddingRightInitial;
18824            return;
18825        }
18826        if (isLayoutRtl()) {
18827            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18828            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18829        } else {
18830            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18831            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18832        }
18833    }
18834
18835    /**
18836     * @hide
18837     */
18838    public Insets getOpticalInsets() {
18839        if (mLayoutInsets == null) {
18840            mLayoutInsets = computeOpticalInsets();
18841        }
18842        return mLayoutInsets;
18843    }
18844
18845    /**
18846     * Set this view's optical insets.
18847     *
18848     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18849     * property. Views that compute their own optical insets should call it as part of measurement.
18850     * This method does not request layout. If you are setting optical insets outside of
18851     * measure/layout itself you will want to call requestLayout() yourself.
18852     * </p>
18853     * @hide
18854     */
18855    public void setOpticalInsets(Insets insets) {
18856        mLayoutInsets = insets;
18857    }
18858
18859    /**
18860     * Changes the selection state of this view. A view can be selected or not.
18861     * Note that selection is not the same as focus. Views are typically
18862     * selected in the context of an AdapterView like ListView or GridView;
18863     * the selected view is the view that is highlighted.
18864     *
18865     * @param selected true if the view must be selected, false otherwise
18866     */
18867    public void setSelected(boolean selected) {
18868        //noinspection DoubleNegation
18869        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
18870            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
18871            if (!selected) resetPressedState();
18872            invalidate(true);
18873            refreshDrawableState();
18874            dispatchSetSelected(selected);
18875            if (selected) {
18876                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
18877            } else {
18878                notifyViewAccessibilityStateChangedIfNeeded(
18879                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
18880            }
18881        }
18882    }
18883
18884    /**
18885     * Dispatch setSelected to all of this View's children.
18886     *
18887     * @see #setSelected(boolean)
18888     *
18889     * @param selected The new selected state
18890     */
18891    protected void dispatchSetSelected(boolean selected) {
18892    }
18893
18894    /**
18895     * Indicates the selection state of this view.
18896     *
18897     * @return true if the view is selected, false otherwise
18898     */
18899    @ViewDebug.ExportedProperty
18900    public boolean isSelected() {
18901        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18902    }
18903
18904    /**
18905     * Changes the activated state of this view. A view can be activated or not.
18906     * Note that activation is not the same as selection.  Selection is
18907     * a transient property, representing the view (hierarchy) the user is
18908     * currently interacting with.  Activation is a longer-term state that the
18909     * user can move views in and out of.  For example, in a list view with
18910     * single or multiple selection enabled, the views in the current selection
18911     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18912     * here.)  The activated state is propagated down to children of the view it
18913     * is set on.
18914     *
18915     * @param activated true if the view must be activated, false otherwise
18916     */
18917    public void setActivated(boolean activated) {
18918        //noinspection DoubleNegation
18919        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18920            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18921            invalidate(true);
18922            refreshDrawableState();
18923            dispatchSetActivated(activated);
18924        }
18925    }
18926
18927    /**
18928     * Dispatch setActivated to all of this View's children.
18929     *
18930     * @see #setActivated(boolean)
18931     *
18932     * @param activated The new activated state
18933     */
18934    protected void dispatchSetActivated(boolean activated) {
18935    }
18936
18937    /**
18938     * Indicates the activation state of this view.
18939     *
18940     * @return true if the view is activated, false otherwise
18941     */
18942    @ViewDebug.ExportedProperty
18943    public boolean isActivated() {
18944        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18945    }
18946
18947    /**
18948     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18949     * observer can be used to get notifications when global events, like
18950     * layout, happen.
18951     *
18952     * The returned ViewTreeObserver observer is not guaranteed to remain
18953     * valid for the lifetime of this View. If the caller of this method keeps
18954     * a long-lived reference to ViewTreeObserver, it should always check for
18955     * the return value of {@link ViewTreeObserver#isAlive()}.
18956     *
18957     * @return The ViewTreeObserver for this view's hierarchy.
18958     */
18959    public ViewTreeObserver getViewTreeObserver() {
18960        if (mAttachInfo != null) {
18961            return mAttachInfo.mTreeObserver;
18962        }
18963        if (mFloatingTreeObserver == null) {
18964            mFloatingTreeObserver = new ViewTreeObserver();
18965        }
18966        return mFloatingTreeObserver;
18967    }
18968
18969    /**
18970     * <p>Finds the topmost view in the current view hierarchy.</p>
18971     *
18972     * @return the topmost view containing this view
18973     */
18974    public View getRootView() {
18975        if (mAttachInfo != null) {
18976            final View v = mAttachInfo.mRootView;
18977            if (v != null) {
18978                return v;
18979            }
18980        }
18981
18982        View parent = this;
18983
18984        while (parent.mParent != null && parent.mParent instanceof View) {
18985            parent = (View) parent.mParent;
18986        }
18987
18988        return parent;
18989    }
18990
18991    /**
18992     * Transforms a motion event from view-local coordinates to on-screen
18993     * coordinates.
18994     *
18995     * @param ev the view-local motion event
18996     * @return false if the transformation could not be applied
18997     * @hide
18998     */
18999    public boolean toGlobalMotionEvent(MotionEvent ev) {
19000        final AttachInfo info = mAttachInfo;
19001        if (info == null) {
19002            return false;
19003        }
19004
19005        final Matrix m = info.mTmpMatrix;
19006        m.set(Matrix.IDENTITY_MATRIX);
19007        transformMatrixToGlobal(m);
19008        ev.transform(m);
19009        return true;
19010    }
19011
19012    /**
19013     * Transforms a motion event from on-screen coordinates to view-local
19014     * coordinates.
19015     *
19016     * @param ev the on-screen motion event
19017     * @return false if the transformation could not be applied
19018     * @hide
19019     */
19020    public boolean toLocalMotionEvent(MotionEvent ev) {
19021        final AttachInfo info = mAttachInfo;
19022        if (info == null) {
19023            return false;
19024        }
19025
19026        final Matrix m = info.mTmpMatrix;
19027        m.set(Matrix.IDENTITY_MATRIX);
19028        transformMatrixToLocal(m);
19029        ev.transform(m);
19030        return true;
19031    }
19032
19033    /**
19034     * Modifies the input matrix such that it maps view-local coordinates to
19035     * on-screen coordinates.
19036     *
19037     * @param m input matrix to modify
19038     * @hide
19039     */
19040    public void transformMatrixToGlobal(Matrix m) {
19041        final ViewParent parent = mParent;
19042        if (parent instanceof View) {
19043            final View vp = (View) parent;
19044            vp.transformMatrixToGlobal(m);
19045            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19046        } else if (parent instanceof ViewRootImpl) {
19047            final ViewRootImpl vr = (ViewRootImpl) parent;
19048            vr.transformMatrixToGlobal(m);
19049            m.preTranslate(0, -vr.mCurScrollY);
19050        }
19051
19052        m.preTranslate(mLeft, mTop);
19053
19054        if (!hasIdentityMatrix()) {
19055            m.preConcat(getMatrix());
19056        }
19057    }
19058
19059    /**
19060     * Modifies the input matrix such that it maps on-screen coordinates to
19061     * view-local coordinates.
19062     *
19063     * @param m input matrix to modify
19064     * @hide
19065     */
19066    public void transformMatrixToLocal(Matrix m) {
19067        final ViewParent parent = mParent;
19068        if (parent instanceof View) {
19069            final View vp = (View) parent;
19070            vp.transformMatrixToLocal(m);
19071            m.postTranslate(vp.mScrollX, vp.mScrollY);
19072        } else if (parent instanceof ViewRootImpl) {
19073            final ViewRootImpl vr = (ViewRootImpl) parent;
19074            vr.transformMatrixToLocal(m);
19075            m.postTranslate(0, vr.mCurScrollY);
19076        }
19077
19078        m.postTranslate(-mLeft, -mTop);
19079
19080        if (!hasIdentityMatrix()) {
19081            m.postConcat(getInverseMatrix());
19082        }
19083    }
19084
19085    /**
19086     * @hide
19087     */
19088    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19089            @ViewDebug.IntToString(from = 0, to = "x"),
19090            @ViewDebug.IntToString(from = 1, to = "y")
19091    })
19092    public int[] getLocationOnScreen() {
19093        int[] location = new int[2];
19094        getLocationOnScreen(location);
19095        return location;
19096    }
19097
19098    /**
19099     * <p>Computes the coordinates of this view on the screen. The argument
19100     * must be an array of two integers. After the method returns, the array
19101     * contains the x and y location in that order.</p>
19102     *
19103     * @param outLocation an array of two integers in which to hold the coordinates
19104     */
19105    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19106        getLocationInWindow(outLocation);
19107
19108        final AttachInfo info = mAttachInfo;
19109        if (info != null) {
19110            outLocation[0] += info.mWindowLeft;
19111            outLocation[1] += info.mWindowTop;
19112        }
19113    }
19114
19115    /**
19116     * <p>Computes the coordinates of this view in its window. The argument
19117     * must be an array of two integers. After the method returns, the array
19118     * contains the x and y location in that order.</p>
19119     *
19120     * @param outLocation an array of two integers in which to hold the coordinates
19121     */
19122    public void getLocationInWindow(@Size(2) int[] outLocation) {
19123        if (outLocation == null || outLocation.length < 2) {
19124            throw new IllegalArgumentException("outLocation must be an array of two integers");
19125        }
19126
19127        outLocation[0] = 0;
19128        outLocation[1] = 0;
19129
19130        transformFromViewToWindowSpace(outLocation);
19131    }
19132
19133    /** @hide */
19134    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19135        if (inOutLocation == null || inOutLocation.length < 2) {
19136            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19137        }
19138
19139        if (mAttachInfo == null) {
19140            // When the view is not attached to a window, this method does not make sense
19141            inOutLocation[0] = inOutLocation[1] = 0;
19142            return;
19143        }
19144
19145        float position[] = mAttachInfo.mTmpTransformLocation;
19146        position[0] = inOutLocation[0];
19147        position[1] = inOutLocation[1];
19148
19149        if (!hasIdentityMatrix()) {
19150            getMatrix().mapPoints(position);
19151        }
19152
19153        position[0] += mLeft;
19154        position[1] += mTop;
19155
19156        ViewParent viewParent = mParent;
19157        while (viewParent instanceof View) {
19158            final View view = (View) viewParent;
19159
19160            position[0] -= view.mScrollX;
19161            position[1] -= view.mScrollY;
19162
19163            if (!view.hasIdentityMatrix()) {
19164                view.getMatrix().mapPoints(position);
19165            }
19166
19167            position[0] += view.mLeft;
19168            position[1] += view.mTop;
19169
19170            viewParent = view.mParent;
19171         }
19172
19173        if (viewParent instanceof ViewRootImpl) {
19174            // *cough*
19175            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19176            position[1] -= vr.mCurScrollY;
19177        }
19178
19179        inOutLocation[0] = Math.round(position[0]);
19180        inOutLocation[1] = Math.round(position[1]);
19181    }
19182
19183    /**
19184     * {@hide}
19185     * @param id the id of the view to be found
19186     * @return the view of the specified id, null if cannot be found
19187     */
19188    protected View findViewTraversal(@IdRes int id) {
19189        if (id == mID) {
19190            return this;
19191        }
19192        return null;
19193    }
19194
19195    /**
19196     * {@hide}
19197     * @param tag the tag of the view to be found
19198     * @return the view of specified tag, null if cannot be found
19199     */
19200    protected View findViewWithTagTraversal(Object tag) {
19201        if (tag != null && tag.equals(mTag)) {
19202            return this;
19203        }
19204        return null;
19205    }
19206
19207    /**
19208     * {@hide}
19209     * @param predicate The predicate to evaluate.
19210     * @param childToSkip If not null, ignores this child during the recursive traversal.
19211     * @return The first view that matches the predicate or null.
19212     */
19213    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19214        if (predicate.apply(this)) {
19215            return this;
19216        }
19217        return null;
19218    }
19219
19220    /**
19221     * Look for a child view with the given id.  If this view has the given
19222     * id, return this view.
19223     *
19224     * @param id The id to search for.
19225     * @return The view that has the given id in the hierarchy or null
19226     */
19227    @Nullable
19228    public final View findViewById(@IdRes int id) {
19229        if (id < 0) {
19230            return null;
19231        }
19232        return findViewTraversal(id);
19233    }
19234
19235    /**
19236     * Finds a view by its unuque and stable accessibility id.
19237     *
19238     * @param accessibilityId The searched accessibility id.
19239     * @return The found view.
19240     */
19241    final View findViewByAccessibilityId(int accessibilityId) {
19242        if (accessibilityId < 0) {
19243            return null;
19244        }
19245        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19246        if (view != null) {
19247            return view.includeForAccessibility() ? view : null;
19248        }
19249        return null;
19250    }
19251
19252    /**
19253     * Performs the traversal to find a view by its unuque and stable accessibility id.
19254     *
19255     * <strong>Note:</strong>This method does not stop at the root namespace
19256     * boundary since the user can touch the screen at an arbitrary location
19257     * potentially crossing the root namespace bounday which will send an
19258     * accessibility event to accessibility services and they should be able
19259     * to obtain the event source. Also accessibility ids are guaranteed to be
19260     * unique in the window.
19261     *
19262     * @param accessibilityId The accessibility id.
19263     * @return The found view.
19264     *
19265     * @hide
19266     */
19267    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19268        if (getAccessibilityViewId() == accessibilityId) {
19269            return this;
19270        }
19271        return null;
19272    }
19273
19274    /**
19275     * Look for a child view with the given tag.  If this view has the given
19276     * tag, return this view.
19277     *
19278     * @param tag The tag to search for, using "tag.equals(getTag())".
19279     * @return The View that has the given tag in the hierarchy or null
19280     */
19281    public final View findViewWithTag(Object tag) {
19282        if (tag == null) {
19283            return null;
19284        }
19285        return findViewWithTagTraversal(tag);
19286    }
19287
19288    /**
19289     * {@hide}
19290     * Look for a child view that matches the specified predicate.
19291     * If this view matches the predicate, return this view.
19292     *
19293     * @param predicate The predicate to evaluate.
19294     * @return The first view that matches the predicate or null.
19295     */
19296    public final View findViewByPredicate(Predicate<View> predicate) {
19297        return findViewByPredicateTraversal(predicate, null);
19298    }
19299
19300    /**
19301     * {@hide}
19302     * Look for a child view that matches the specified predicate,
19303     * starting with the specified view and its descendents and then
19304     * recusively searching the ancestors and siblings of that view
19305     * until this view is reached.
19306     *
19307     * This method is useful in cases where the predicate does not match
19308     * a single unique view (perhaps multiple views use the same id)
19309     * and we are trying to find the view that is "closest" in scope to the
19310     * starting view.
19311     *
19312     * @param start The view to start from.
19313     * @param predicate The predicate to evaluate.
19314     * @return The first view that matches the predicate or null.
19315     */
19316    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19317        View childToSkip = null;
19318        for (;;) {
19319            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19320            if (view != null || start == this) {
19321                return view;
19322            }
19323
19324            ViewParent parent = start.getParent();
19325            if (parent == null || !(parent instanceof View)) {
19326                return null;
19327            }
19328
19329            childToSkip = start;
19330            start = (View) parent;
19331        }
19332    }
19333
19334    /**
19335     * Sets the identifier for this view. The identifier does not have to be
19336     * unique in this view's hierarchy. The identifier should be a positive
19337     * number.
19338     *
19339     * @see #NO_ID
19340     * @see #getId()
19341     * @see #findViewById(int)
19342     *
19343     * @param id a number used to identify the view
19344     *
19345     * @attr ref android.R.styleable#View_id
19346     */
19347    public void setId(@IdRes int id) {
19348        mID = id;
19349        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19350            mID = generateViewId();
19351        }
19352    }
19353
19354    /**
19355     * {@hide}
19356     *
19357     * @param isRoot true if the view belongs to the root namespace, false
19358     *        otherwise
19359     */
19360    public void setIsRootNamespace(boolean isRoot) {
19361        if (isRoot) {
19362            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19363        } else {
19364            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19365        }
19366    }
19367
19368    /**
19369     * {@hide}
19370     *
19371     * @return true if the view belongs to the root namespace, false otherwise
19372     */
19373    public boolean isRootNamespace() {
19374        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19375    }
19376
19377    /**
19378     * Returns this view's identifier.
19379     *
19380     * @return a positive integer used to identify the view or {@link #NO_ID}
19381     *         if the view has no ID
19382     *
19383     * @see #setId(int)
19384     * @see #findViewById(int)
19385     * @attr ref android.R.styleable#View_id
19386     */
19387    @IdRes
19388    @ViewDebug.CapturedViewProperty
19389    public int getId() {
19390        return mID;
19391    }
19392
19393    /**
19394     * Returns this view's tag.
19395     *
19396     * @return the Object stored in this view as a tag, or {@code null} if not
19397     *         set
19398     *
19399     * @see #setTag(Object)
19400     * @see #getTag(int)
19401     */
19402    @ViewDebug.ExportedProperty
19403    public Object getTag() {
19404        return mTag;
19405    }
19406
19407    /**
19408     * Sets the tag associated with this view. A tag can be used to mark
19409     * a view in its hierarchy and does not have to be unique within the
19410     * hierarchy. Tags can also be used to store data within a view without
19411     * resorting to another data structure.
19412     *
19413     * @param tag an Object to tag the view with
19414     *
19415     * @see #getTag()
19416     * @see #setTag(int, Object)
19417     */
19418    public void setTag(final Object tag) {
19419        mTag = tag;
19420    }
19421
19422    /**
19423     * Returns the tag associated with this view and the specified key.
19424     *
19425     * @param key The key identifying the tag
19426     *
19427     * @return the Object stored in this view as a tag, or {@code null} if not
19428     *         set
19429     *
19430     * @see #setTag(int, Object)
19431     * @see #getTag()
19432     */
19433    public Object getTag(int key) {
19434        if (mKeyedTags != null) return mKeyedTags.get(key);
19435        return null;
19436    }
19437
19438    /**
19439     * Sets a tag associated with this view and a key. A tag can be used
19440     * to mark a view in its hierarchy and does not have to be unique within
19441     * the hierarchy. Tags can also be used to store data within a view
19442     * without resorting to another data structure.
19443     *
19444     * The specified key should be an id declared in the resources of the
19445     * application to ensure it is unique (see the <a
19446     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19447     * Keys identified as belonging to
19448     * the Android framework or not associated with any package will cause
19449     * an {@link IllegalArgumentException} to be thrown.
19450     *
19451     * @param key The key identifying the tag
19452     * @param tag An Object to tag the view with
19453     *
19454     * @throws IllegalArgumentException If they specified key is not valid
19455     *
19456     * @see #setTag(Object)
19457     * @see #getTag(int)
19458     */
19459    public void setTag(int key, final Object tag) {
19460        // If the package id is 0x00 or 0x01, it's either an undefined package
19461        // or a framework id
19462        if ((key >>> 24) < 2) {
19463            throw new IllegalArgumentException("The key must be an application-specific "
19464                    + "resource id.");
19465        }
19466
19467        setKeyedTag(key, tag);
19468    }
19469
19470    /**
19471     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19472     * framework id.
19473     *
19474     * @hide
19475     */
19476    public void setTagInternal(int key, Object tag) {
19477        if ((key >>> 24) != 0x1) {
19478            throw new IllegalArgumentException("The key must be a framework-specific "
19479                    + "resource id.");
19480        }
19481
19482        setKeyedTag(key, tag);
19483    }
19484
19485    private void setKeyedTag(int key, Object tag) {
19486        if (mKeyedTags == null) {
19487            mKeyedTags = new SparseArray<Object>(2);
19488        }
19489
19490        mKeyedTags.put(key, tag);
19491    }
19492
19493    /**
19494     * Prints information about this view in the log output, with the tag
19495     * {@link #VIEW_LOG_TAG}.
19496     *
19497     * @hide
19498     */
19499    public void debug() {
19500        debug(0);
19501    }
19502
19503    /**
19504     * Prints information about this view in the log output, with the tag
19505     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19506     * indentation defined by the <code>depth</code>.
19507     *
19508     * @param depth the indentation level
19509     *
19510     * @hide
19511     */
19512    protected void debug(int depth) {
19513        String output = debugIndent(depth - 1);
19514
19515        output += "+ " + this;
19516        int id = getId();
19517        if (id != -1) {
19518            output += " (id=" + id + ")";
19519        }
19520        Object tag = getTag();
19521        if (tag != null) {
19522            output += " (tag=" + tag + ")";
19523        }
19524        Log.d(VIEW_LOG_TAG, output);
19525
19526        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19527            output = debugIndent(depth) + " FOCUSED";
19528            Log.d(VIEW_LOG_TAG, output);
19529        }
19530
19531        output = debugIndent(depth);
19532        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19533                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19534                + "} ";
19535        Log.d(VIEW_LOG_TAG, output);
19536
19537        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19538                || mPaddingBottom != 0) {
19539            output = debugIndent(depth);
19540            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19541                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19542            Log.d(VIEW_LOG_TAG, output);
19543        }
19544
19545        output = debugIndent(depth);
19546        output += "mMeasureWidth=" + mMeasuredWidth +
19547                " mMeasureHeight=" + mMeasuredHeight;
19548        Log.d(VIEW_LOG_TAG, output);
19549
19550        output = debugIndent(depth);
19551        if (mLayoutParams == null) {
19552            output += "BAD! no layout params";
19553        } else {
19554            output = mLayoutParams.debug(output);
19555        }
19556        Log.d(VIEW_LOG_TAG, output);
19557
19558        output = debugIndent(depth);
19559        output += "flags={";
19560        output += View.printFlags(mViewFlags);
19561        output += "}";
19562        Log.d(VIEW_LOG_TAG, output);
19563
19564        output = debugIndent(depth);
19565        output += "privateFlags={";
19566        output += View.printPrivateFlags(mPrivateFlags);
19567        output += "}";
19568        Log.d(VIEW_LOG_TAG, output);
19569    }
19570
19571    /**
19572     * Creates a string of whitespaces used for indentation.
19573     *
19574     * @param depth the indentation level
19575     * @return a String containing (depth * 2 + 3) * 2 white spaces
19576     *
19577     * @hide
19578     */
19579    protected static String debugIndent(int depth) {
19580        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19581        for (int i = 0; i < (depth * 2) + 3; i++) {
19582            spaces.append(' ').append(' ');
19583        }
19584        return spaces.toString();
19585    }
19586
19587    /**
19588     * <p>Return the offset of the widget's text baseline from the widget's top
19589     * boundary. If this widget does not support baseline alignment, this
19590     * method returns -1. </p>
19591     *
19592     * @return the offset of the baseline within the widget's bounds or -1
19593     *         if baseline alignment is not supported
19594     */
19595    @ViewDebug.ExportedProperty(category = "layout")
19596    public int getBaseline() {
19597        return -1;
19598    }
19599
19600    /**
19601     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19602     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19603     * a layout pass.
19604     *
19605     * @return whether the view hierarchy is currently undergoing a layout pass
19606     */
19607    public boolean isInLayout() {
19608        ViewRootImpl viewRoot = getViewRootImpl();
19609        return (viewRoot != null && viewRoot.isInLayout());
19610    }
19611
19612    /**
19613     * Call this when something has changed which has invalidated the
19614     * layout of this view. This will schedule a layout pass of the view
19615     * tree. This should not be called while the view hierarchy is currently in a layout
19616     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19617     * end of the current layout pass (and then layout will run again) or after the current
19618     * frame is drawn and the next layout occurs.
19619     *
19620     * <p>Subclasses which override this method should call the superclass method to
19621     * handle possible request-during-layout errors correctly.</p>
19622     */
19623    @CallSuper
19624    public void requestLayout() {
19625        if (mMeasureCache != null) mMeasureCache.clear();
19626
19627        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19628            // Only trigger request-during-layout logic if this is the view requesting it,
19629            // not the views in its parent hierarchy
19630            ViewRootImpl viewRoot = getViewRootImpl();
19631            if (viewRoot != null && viewRoot.isInLayout()) {
19632                if (!viewRoot.requestLayoutDuringLayout(this)) {
19633                    return;
19634                }
19635            }
19636            mAttachInfo.mViewRequestingLayout = this;
19637        }
19638
19639        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19640        mPrivateFlags |= PFLAG_INVALIDATED;
19641
19642        if (mParent != null && !mParent.isLayoutRequested()) {
19643            mParent.requestLayout();
19644        }
19645        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19646            mAttachInfo.mViewRequestingLayout = null;
19647        }
19648    }
19649
19650    /**
19651     * Forces this view to be laid out during the next layout pass.
19652     * This method does not call requestLayout() or forceLayout()
19653     * on the parent.
19654     */
19655    public void forceLayout() {
19656        if (mMeasureCache != null) mMeasureCache.clear();
19657
19658        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19659        mPrivateFlags |= PFLAG_INVALIDATED;
19660    }
19661
19662    /**
19663     * <p>
19664     * This is called to find out how big a view should be. The parent
19665     * supplies constraint information in the width and height parameters.
19666     * </p>
19667     *
19668     * <p>
19669     * The actual measurement work of a view is performed in
19670     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19671     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19672     * </p>
19673     *
19674     *
19675     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19676     *        parent
19677     * @param heightMeasureSpec Vertical space requirements as imposed by the
19678     *        parent
19679     *
19680     * @see #onMeasure(int, int)
19681     */
19682    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19683        boolean optical = isLayoutModeOptical(this);
19684        if (optical != isLayoutModeOptical(mParent)) {
19685            Insets insets = getOpticalInsets();
19686            int oWidth  = insets.left + insets.right;
19687            int oHeight = insets.top  + insets.bottom;
19688            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19689            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19690        }
19691
19692        // Suppress sign extension for the low bytes
19693        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19694        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19695
19696        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19697
19698        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19699        // already measured as the correct size. In API 23 and below, this
19700        // extra pass is required to make LinearLayout re-distribute weight.
19701        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19702                || heightMeasureSpec != mOldHeightMeasureSpec;
19703        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19704                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19705        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19706                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19707        final boolean needsLayout = specChanged
19708                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19709
19710        if (forceLayout || needsLayout) {
19711            // first clears the measured dimension flag
19712            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19713
19714            resolveRtlPropertiesIfNeeded();
19715
19716            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19717            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19718                // measure ourselves, this should set the measured dimension flag back
19719                onMeasure(widthMeasureSpec, heightMeasureSpec);
19720                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19721            } else {
19722                long value = mMeasureCache.valueAt(cacheIndex);
19723                // Casting a long to int drops the high 32 bits, no mask needed
19724                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19725                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19726            }
19727
19728            // flag not set, setMeasuredDimension() was not invoked, we raise
19729            // an exception to warn the developer
19730            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19731                throw new IllegalStateException("View with id " + getId() + ": "
19732                        + getClass().getName() + "#onMeasure() did not set the"
19733                        + " measured dimension by calling"
19734                        + " setMeasuredDimension()");
19735            }
19736
19737            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19738        }
19739
19740        mOldWidthMeasureSpec = widthMeasureSpec;
19741        mOldHeightMeasureSpec = heightMeasureSpec;
19742
19743        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19744                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19745    }
19746
19747    /**
19748     * <p>
19749     * Measure the view and its content to determine the measured width and the
19750     * measured height. This method is invoked by {@link #measure(int, int)} and
19751     * should be overridden by subclasses to provide accurate and efficient
19752     * measurement of their contents.
19753     * </p>
19754     *
19755     * <p>
19756     * <strong>CONTRACT:</strong> When overriding this method, you
19757     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19758     * measured width and height of this view. Failure to do so will trigger an
19759     * <code>IllegalStateException</code>, thrown by
19760     * {@link #measure(int, int)}. Calling the superclass'
19761     * {@link #onMeasure(int, int)} is a valid use.
19762     * </p>
19763     *
19764     * <p>
19765     * The base class implementation of measure defaults to the background size,
19766     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19767     * override {@link #onMeasure(int, int)} to provide better measurements of
19768     * their content.
19769     * </p>
19770     *
19771     * <p>
19772     * If this method is overridden, it is the subclass's responsibility to make
19773     * sure the measured height and width are at least the view's minimum height
19774     * and width ({@link #getSuggestedMinimumHeight()} and
19775     * {@link #getSuggestedMinimumWidth()}).
19776     * </p>
19777     *
19778     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19779     *                         The requirements are encoded with
19780     *                         {@link android.view.View.MeasureSpec}.
19781     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19782     *                         The requirements are encoded with
19783     *                         {@link android.view.View.MeasureSpec}.
19784     *
19785     * @see #getMeasuredWidth()
19786     * @see #getMeasuredHeight()
19787     * @see #setMeasuredDimension(int, int)
19788     * @see #getSuggestedMinimumHeight()
19789     * @see #getSuggestedMinimumWidth()
19790     * @see android.view.View.MeasureSpec#getMode(int)
19791     * @see android.view.View.MeasureSpec#getSize(int)
19792     */
19793    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19794        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19795                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19796    }
19797
19798    /**
19799     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19800     * measured width and measured height. Failing to do so will trigger an
19801     * exception at measurement time.</p>
19802     *
19803     * @param measuredWidth The measured width of this view.  May be a complex
19804     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19805     * {@link #MEASURED_STATE_TOO_SMALL}.
19806     * @param measuredHeight The measured height of this view.  May be a complex
19807     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19808     * {@link #MEASURED_STATE_TOO_SMALL}.
19809     */
19810    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19811        boolean optical = isLayoutModeOptical(this);
19812        if (optical != isLayoutModeOptical(mParent)) {
19813            Insets insets = getOpticalInsets();
19814            int opticalWidth  = insets.left + insets.right;
19815            int opticalHeight = insets.top  + insets.bottom;
19816
19817            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19818            measuredHeight += optical ? opticalHeight : -opticalHeight;
19819        }
19820        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19821    }
19822
19823    /**
19824     * Sets the measured dimension without extra processing for things like optical bounds.
19825     * Useful for reapplying consistent values that have already been cooked with adjustments
19826     * for optical bounds, etc. such as those from the measurement cache.
19827     *
19828     * @param measuredWidth The measured width of this view.  May be a complex
19829     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19830     * {@link #MEASURED_STATE_TOO_SMALL}.
19831     * @param measuredHeight The measured height of this view.  May be a complex
19832     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19833     * {@link #MEASURED_STATE_TOO_SMALL}.
19834     */
19835    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19836        mMeasuredWidth = measuredWidth;
19837        mMeasuredHeight = measuredHeight;
19838
19839        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19840    }
19841
19842    /**
19843     * Merge two states as returned by {@link #getMeasuredState()}.
19844     * @param curState The current state as returned from a view or the result
19845     * of combining multiple views.
19846     * @param newState The new view state to combine.
19847     * @return Returns a new integer reflecting the combination of the two
19848     * states.
19849     */
19850    public static int combineMeasuredStates(int curState, int newState) {
19851        return curState | newState;
19852    }
19853
19854    /**
19855     * Version of {@link #resolveSizeAndState(int, int, int)}
19856     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19857     */
19858    public static int resolveSize(int size, int measureSpec) {
19859        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19860    }
19861
19862    /**
19863     * Utility to reconcile a desired size and state, with constraints imposed
19864     * by a MeasureSpec. Will take the desired size, unless a different size
19865     * is imposed by the constraints. The returned value is a compound integer,
19866     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
19867     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
19868     * resulting size is smaller than the size the view wants to be.
19869     *
19870     * @param size How big the view wants to be.
19871     * @param measureSpec Constraints imposed by the parent.
19872     * @param childMeasuredState Size information bit mask for the view's
19873     *                           children.
19874     * @return Size information bit mask as defined by
19875     *         {@link #MEASURED_SIZE_MASK} and
19876     *         {@link #MEASURED_STATE_TOO_SMALL}.
19877     */
19878    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
19879        final int specMode = MeasureSpec.getMode(measureSpec);
19880        final int specSize = MeasureSpec.getSize(measureSpec);
19881        final int result;
19882        switch (specMode) {
19883            case MeasureSpec.AT_MOST:
19884                if (specSize < size) {
19885                    result = specSize | MEASURED_STATE_TOO_SMALL;
19886                } else {
19887                    result = size;
19888                }
19889                break;
19890            case MeasureSpec.EXACTLY:
19891                result = specSize;
19892                break;
19893            case MeasureSpec.UNSPECIFIED:
19894            default:
19895                result = size;
19896        }
19897        return result | (childMeasuredState & MEASURED_STATE_MASK);
19898    }
19899
19900    /**
19901     * Utility to return a default size. Uses the supplied size if the
19902     * MeasureSpec imposed no constraints. Will get larger if allowed
19903     * by the MeasureSpec.
19904     *
19905     * @param size Default size for this view
19906     * @param measureSpec Constraints imposed by the parent
19907     * @return The size this view should be.
19908     */
19909    public static int getDefaultSize(int size, int measureSpec) {
19910        int result = size;
19911        int specMode = MeasureSpec.getMode(measureSpec);
19912        int specSize = MeasureSpec.getSize(measureSpec);
19913
19914        switch (specMode) {
19915        case MeasureSpec.UNSPECIFIED:
19916            result = size;
19917            break;
19918        case MeasureSpec.AT_MOST:
19919        case MeasureSpec.EXACTLY:
19920            result = specSize;
19921            break;
19922        }
19923        return result;
19924    }
19925
19926    /**
19927     * Returns the suggested minimum height that the view should use. This
19928     * returns the maximum of the view's minimum height
19929     * and the background's minimum height
19930     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19931     * <p>
19932     * When being used in {@link #onMeasure(int, int)}, the caller should still
19933     * ensure the returned height is within the requirements of the parent.
19934     *
19935     * @return The suggested minimum height of the view.
19936     */
19937    protected int getSuggestedMinimumHeight() {
19938        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19939
19940    }
19941
19942    /**
19943     * Returns the suggested minimum width that the view should use. This
19944     * returns the maximum of the view's minimum width
19945     * and the background's minimum width
19946     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19947     * <p>
19948     * When being used in {@link #onMeasure(int, int)}, the caller should still
19949     * ensure the returned width is within the requirements of the parent.
19950     *
19951     * @return The suggested minimum width of the view.
19952     */
19953    protected int getSuggestedMinimumWidth() {
19954        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19955    }
19956
19957    /**
19958     * Returns the minimum height of the view.
19959     *
19960     * @return the minimum height the view will try to be.
19961     *
19962     * @see #setMinimumHeight(int)
19963     *
19964     * @attr ref android.R.styleable#View_minHeight
19965     */
19966    public int getMinimumHeight() {
19967        return mMinHeight;
19968    }
19969
19970    /**
19971     * Sets the minimum height of the view. It is not guaranteed the view will
19972     * be able to achieve this minimum height (for example, if its parent layout
19973     * constrains it with less available height).
19974     *
19975     * @param minHeight The minimum height the view will try to be.
19976     *
19977     * @see #getMinimumHeight()
19978     *
19979     * @attr ref android.R.styleable#View_minHeight
19980     */
19981    @RemotableViewMethod
19982    public void setMinimumHeight(int minHeight) {
19983        mMinHeight = minHeight;
19984        requestLayout();
19985    }
19986
19987    /**
19988     * Returns the minimum width of the view.
19989     *
19990     * @return the minimum width the view will try to be.
19991     *
19992     * @see #setMinimumWidth(int)
19993     *
19994     * @attr ref android.R.styleable#View_minWidth
19995     */
19996    public int getMinimumWidth() {
19997        return mMinWidth;
19998    }
19999
20000    /**
20001     * Sets the minimum width of the view. It is not guaranteed the view will
20002     * be able to achieve this minimum width (for example, if its parent layout
20003     * constrains it with less available width).
20004     *
20005     * @param minWidth The minimum width the view will try to be.
20006     *
20007     * @see #getMinimumWidth()
20008     *
20009     * @attr ref android.R.styleable#View_minWidth
20010     */
20011    public void setMinimumWidth(int minWidth) {
20012        mMinWidth = minWidth;
20013        requestLayout();
20014
20015    }
20016
20017    /**
20018     * Get the animation currently associated with this view.
20019     *
20020     * @return The animation that is currently playing or
20021     *         scheduled to play for this view.
20022     */
20023    public Animation getAnimation() {
20024        return mCurrentAnimation;
20025    }
20026
20027    /**
20028     * Start the specified animation now.
20029     *
20030     * @param animation the animation to start now
20031     */
20032    public void startAnimation(Animation animation) {
20033        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20034        setAnimation(animation);
20035        invalidateParentCaches();
20036        invalidate(true);
20037    }
20038
20039    /**
20040     * Cancels any animations for this view.
20041     */
20042    public void clearAnimation() {
20043        if (mCurrentAnimation != null) {
20044            mCurrentAnimation.detach();
20045        }
20046        mCurrentAnimation = null;
20047        invalidateParentIfNeeded();
20048    }
20049
20050    /**
20051     * Sets the next animation to play for this view.
20052     * If you want the animation to play immediately, use
20053     * {@link #startAnimation(android.view.animation.Animation)} instead.
20054     * This method provides allows fine-grained
20055     * control over the start time and invalidation, but you
20056     * must make sure that 1) the animation has a start time set, and
20057     * 2) the view's parent (which controls animations on its children)
20058     * will be invalidated when the animation is supposed to
20059     * start.
20060     *
20061     * @param animation The next animation, or null.
20062     */
20063    public void setAnimation(Animation animation) {
20064        mCurrentAnimation = animation;
20065
20066        if (animation != null) {
20067            // If the screen is off assume the animation start time is now instead of
20068            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20069            // would cause the animation to start when the screen turns back on
20070            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20071                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20072                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20073            }
20074            animation.reset();
20075        }
20076    }
20077
20078    /**
20079     * Invoked by a parent ViewGroup to notify the start of the animation
20080     * currently associated with this view. If you override this method,
20081     * always call super.onAnimationStart();
20082     *
20083     * @see #setAnimation(android.view.animation.Animation)
20084     * @see #getAnimation()
20085     */
20086    @CallSuper
20087    protected void onAnimationStart() {
20088        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20089    }
20090
20091    /**
20092     * Invoked by a parent ViewGroup to notify the end of the animation
20093     * currently associated with this view. If you override this method,
20094     * always call super.onAnimationEnd();
20095     *
20096     * @see #setAnimation(android.view.animation.Animation)
20097     * @see #getAnimation()
20098     */
20099    @CallSuper
20100    protected void onAnimationEnd() {
20101        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20102    }
20103
20104    /**
20105     * Invoked if there is a Transform that involves alpha. Subclass that can
20106     * draw themselves with the specified alpha should return true, and then
20107     * respect that alpha when their onDraw() is called. If this returns false
20108     * then the view may be redirected to draw into an offscreen buffer to
20109     * fulfill the request, which will look fine, but may be slower than if the
20110     * subclass handles it internally. The default implementation returns false.
20111     *
20112     * @param alpha The alpha (0..255) to apply to the view's drawing
20113     * @return true if the view can draw with the specified alpha.
20114     */
20115    protected boolean onSetAlpha(int alpha) {
20116        return false;
20117    }
20118
20119    /**
20120     * This is used by the RootView to perform an optimization when
20121     * the view hierarchy contains one or several SurfaceView.
20122     * SurfaceView is always considered transparent, but its children are not,
20123     * therefore all View objects remove themselves from the global transparent
20124     * region (passed as a parameter to this function).
20125     *
20126     * @param region The transparent region for this ViewAncestor (window).
20127     *
20128     * @return Returns true if the effective visibility of the view at this
20129     * point is opaque, regardless of the transparent region; returns false
20130     * if it is possible for underlying windows to be seen behind the view.
20131     *
20132     * {@hide}
20133     */
20134    public boolean gatherTransparentRegion(Region region) {
20135        final AttachInfo attachInfo = mAttachInfo;
20136        if (region != null && attachInfo != null) {
20137            final int pflags = mPrivateFlags;
20138            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20139                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20140                // remove it from the transparent region.
20141                final int[] location = attachInfo.mTransparentLocation;
20142                getLocationInWindow(location);
20143                region.op(location[0], location[1], location[0] + mRight - mLeft,
20144                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20145            } else {
20146                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20147                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20148                    // the background drawable's non-transparent parts from this transparent region.
20149                    applyDrawableToTransparentRegion(mBackground, region);
20150                }
20151                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20152                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20153                    // Similarly, we remove the foreground drawable's non-transparent parts.
20154                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20155                }
20156            }
20157        }
20158        return true;
20159    }
20160
20161    /**
20162     * Play a sound effect for this view.
20163     *
20164     * <p>The framework will play sound effects for some built in actions, such as
20165     * clicking, but you may wish to play these effects in your widget,
20166     * for instance, for internal navigation.
20167     *
20168     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20169     * {@link #isSoundEffectsEnabled()} is true.
20170     *
20171     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20172     */
20173    public void playSoundEffect(int soundConstant) {
20174        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20175            return;
20176        }
20177        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20178    }
20179
20180    /**
20181     * BZZZTT!!1!
20182     *
20183     * <p>Provide haptic feedback to the user for this view.
20184     *
20185     * <p>The framework will provide haptic feedback for some built in actions,
20186     * such as long presses, but you may wish to provide feedback for your
20187     * own widget.
20188     *
20189     * <p>The feedback will only be performed if
20190     * {@link #isHapticFeedbackEnabled()} is true.
20191     *
20192     * @param feedbackConstant One of the constants defined in
20193     * {@link HapticFeedbackConstants}
20194     */
20195    public boolean performHapticFeedback(int feedbackConstant) {
20196        return performHapticFeedback(feedbackConstant, 0);
20197    }
20198
20199    /**
20200     * BZZZTT!!1!
20201     *
20202     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20203     *
20204     * @param feedbackConstant One of the constants defined in
20205     * {@link HapticFeedbackConstants}
20206     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20207     */
20208    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20209        if (mAttachInfo == null) {
20210            return false;
20211        }
20212        //noinspection SimplifiableIfStatement
20213        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20214                && !isHapticFeedbackEnabled()) {
20215            return false;
20216        }
20217        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20218                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20219    }
20220
20221    /**
20222     * Request that the visibility of the status bar or other screen/window
20223     * decorations be changed.
20224     *
20225     * <p>This method is used to put the over device UI into temporary modes
20226     * where the user's attention is focused more on the application content,
20227     * by dimming or hiding surrounding system affordances.  This is typically
20228     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20229     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20230     * to be placed behind the action bar (and with these flags other system
20231     * affordances) so that smooth transitions between hiding and showing them
20232     * can be done.
20233     *
20234     * <p>Two representative examples of the use of system UI visibility is
20235     * implementing a content browsing application (like a magazine reader)
20236     * and a video playing application.
20237     *
20238     * <p>The first code shows a typical implementation of a View in a content
20239     * browsing application.  In this implementation, the application goes
20240     * into a content-oriented mode by hiding the status bar and action bar,
20241     * and putting the navigation elements into lights out mode.  The user can
20242     * then interact with content while in this mode.  Such an application should
20243     * provide an easy way for the user to toggle out of the mode (such as to
20244     * check information in the status bar or access notifications).  In the
20245     * implementation here, this is done simply by tapping on the content.
20246     *
20247     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20248     *      content}
20249     *
20250     * <p>This second code sample shows a typical implementation of a View
20251     * in a video playing application.  In this situation, while the video is
20252     * playing the application would like to go into a complete full-screen mode,
20253     * to use as much of the display as possible for the video.  When in this state
20254     * the user can not interact with the application; the system intercepts
20255     * touching on the screen to pop the UI out of full screen mode.  See
20256     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20257     *
20258     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20259     *      content}
20260     *
20261     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20262     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20263     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20264     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20265     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20266     */
20267    public void setSystemUiVisibility(int visibility) {
20268        if (visibility != mSystemUiVisibility) {
20269            mSystemUiVisibility = visibility;
20270            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20271                mParent.recomputeViewAttributes(this);
20272            }
20273        }
20274    }
20275
20276    /**
20277     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20278     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20279     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20280     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20281     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20282     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20283     */
20284    public int getSystemUiVisibility() {
20285        return mSystemUiVisibility;
20286    }
20287
20288    /**
20289     * Returns the current system UI visibility that is currently set for
20290     * the entire window.  This is the combination of the
20291     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20292     * views in the window.
20293     */
20294    public int getWindowSystemUiVisibility() {
20295        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20296    }
20297
20298    /**
20299     * Override to find out when the window's requested system UI visibility
20300     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20301     * This is different from the callbacks received through
20302     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20303     * in that this is only telling you about the local request of the window,
20304     * not the actual values applied by the system.
20305     */
20306    public void onWindowSystemUiVisibilityChanged(int visible) {
20307    }
20308
20309    /**
20310     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20311     * the view hierarchy.
20312     */
20313    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20314        onWindowSystemUiVisibilityChanged(visible);
20315    }
20316
20317    /**
20318     * Set a listener to receive callbacks when the visibility of the system bar changes.
20319     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20320     */
20321    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20322        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20323        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20324            mParent.recomputeViewAttributes(this);
20325        }
20326    }
20327
20328    /**
20329     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20330     * the view hierarchy.
20331     */
20332    public void dispatchSystemUiVisibilityChanged(int visibility) {
20333        ListenerInfo li = mListenerInfo;
20334        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20335            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20336                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20337        }
20338    }
20339
20340    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20341        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20342        if (val != mSystemUiVisibility) {
20343            setSystemUiVisibility(val);
20344            return true;
20345        }
20346        return false;
20347    }
20348
20349    /** @hide */
20350    public void setDisabledSystemUiVisibility(int flags) {
20351        if (mAttachInfo != null) {
20352            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20353                mAttachInfo.mDisabledSystemUiVisibility = flags;
20354                if (mParent != null) {
20355                    mParent.recomputeViewAttributes(this);
20356                }
20357            }
20358        }
20359    }
20360
20361    /**
20362     * Creates an image that the system displays during the drag and drop
20363     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20364     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20365     * appearance as the given View. The default also positions the center of the drag shadow
20366     * directly under the touch point. If no View is provided (the constructor with no parameters
20367     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20368     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20369     * default is an invisible drag shadow.
20370     * <p>
20371     * You are not required to use the View you provide to the constructor as the basis of the
20372     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20373     * anything you want as the drag shadow.
20374     * </p>
20375     * <p>
20376     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20377     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20378     *  size and position of the drag shadow. It uses this data to construct a
20379     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20380     *  so that your application can draw the shadow image in the Canvas.
20381     * </p>
20382     *
20383     * <div class="special reference">
20384     * <h3>Developer Guides</h3>
20385     * <p>For a guide to implementing drag and drop features, read the
20386     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20387     * </div>
20388     */
20389    public static class DragShadowBuilder {
20390        private final WeakReference<View> mView;
20391
20392        /**
20393         * Constructs a shadow image builder based on a View. By default, the resulting drag
20394         * shadow will have the same appearance and dimensions as the View, with the touch point
20395         * over the center of the View.
20396         * @param view A View. Any View in scope can be used.
20397         */
20398        public DragShadowBuilder(View view) {
20399            mView = new WeakReference<View>(view);
20400        }
20401
20402        /**
20403         * Construct a shadow builder object with no associated View.  This
20404         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20405         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20406         * to supply the drag shadow's dimensions and appearance without
20407         * reference to any View object. If they are not overridden, then the result is an
20408         * invisible drag shadow.
20409         */
20410        public DragShadowBuilder() {
20411            mView = new WeakReference<View>(null);
20412        }
20413
20414        /**
20415         * Returns the View object that had been passed to the
20416         * {@link #View.DragShadowBuilder(View)}
20417         * constructor.  If that View parameter was {@code null} or if the
20418         * {@link #View.DragShadowBuilder()}
20419         * constructor was used to instantiate the builder object, this method will return
20420         * null.
20421         *
20422         * @return The View object associate with this builder object.
20423         */
20424        @SuppressWarnings({"JavadocReference"})
20425        final public View getView() {
20426            return mView.get();
20427        }
20428
20429        /**
20430         * Provides the metrics for the shadow image. These include the dimensions of
20431         * the shadow image, and the point within that shadow that should
20432         * be centered under the touch location while dragging.
20433         * <p>
20434         * The default implementation sets the dimensions of the shadow to be the
20435         * same as the dimensions of the View itself and centers the shadow under
20436         * the touch point.
20437         * </p>
20438         *
20439         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20440         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20441         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20442         * image.
20443         *
20444         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20445         * shadow image that should be underneath the touch point during the drag and drop
20446         * operation. Your application must set {@link android.graphics.Point#x} to the
20447         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20448         */
20449        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20450            final View view = mView.get();
20451            if (view != null) {
20452                outShadowSize.set(view.getWidth(), view.getHeight());
20453                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20454            } else {
20455                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20456            }
20457        }
20458
20459        /**
20460         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20461         * based on the dimensions it received from the
20462         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20463         *
20464         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20465         */
20466        public void onDrawShadow(Canvas canvas) {
20467            final View view = mView.get();
20468            if (view != null) {
20469                view.draw(canvas);
20470            } else {
20471                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20472            }
20473        }
20474    }
20475
20476    /**
20477     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20478     * startDragAndDrop()} for newer platform versions.
20479     */
20480    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20481                                   Object myLocalState, int flags) {
20482        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20483    }
20484
20485    /**
20486     * Starts a drag and drop operation. When your application calls this method, it passes a
20487     * {@link android.view.View.DragShadowBuilder} object to the system. The
20488     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20489     * to get metrics for the drag shadow, and then calls the object's
20490     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20491     * <p>
20492     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20493     *  drag events to all the View objects in your application that are currently visible. It does
20494     *  this either by calling the View object's drag listener (an implementation of
20495     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20496     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20497     *  Both are passed a {@link android.view.DragEvent} object that has a
20498     *  {@link android.view.DragEvent#getAction()} value of
20499     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20500     * </p>
20501     * <p>
20502     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20503     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20504     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20505     * to the View the user selected for dragging.
20506     * </p>
20507     * @param data A {@link android.content.ClipData} object pointing to the data to be
20508     * transferred by the drag and drop operation.
20509     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20510     * drag shadow.
20511     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20512     * drop operation. This Object is put into every DragEvent object sent by the system during the
20513     * current drag.
20514     * <p>
20515     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20516     * to the target Views. For example, it can contain flags that differentiate between a
20517     * a copy operation and a move operation.
20518     * </p>
20519     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
20520     * so the parameter should be set to 0.
20521     * @return {@code true} if the method completes successfully, or
20522     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20523     * do a drag, and so no drag operation is in progress.
20524     */
20525    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20526            Object myLocalState, int flags) {
20527        if (ViewDebug.DEBUG_DRAG) {
20528            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20529        }
20530        boolean okay = false;
20531
20532        Point shadowSize = new Point();
20533        Point shadowTouchPoint = new Point();
20534        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20535
20536        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20537                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20538            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20539        }
20540
20541        if (ViewDebug.DEBUG_DRAG) {
20542            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20543                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20544        }
20545        if (mAttachInfo.mDragSurface != null) {
20546            mAttachInfo.mDragSurface.release();
20547        }
20548        mAttachInfo.mDragSurface = new Surface();
20549        try {
20550            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20551                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20552            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20553                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20554            if (mAttachInfo.mDragToken != null) {
20555                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20556                try {
20557                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20558                    shadowBuilder.onDrawShadow(canvas);
20559                } finally {
20560                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20561                }
20562
20563                final ViewRootImpl root = getViewRootImpl();
20564
20565                // Cache the local state object for delivery with DragEvents
20566                root.setLocalDragState(myLocalState);
20567
20568                // repurpose 'shadowSize' for the last touch point
20569                root.getLastTouchPoint(shadowSize);
20570
20571                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20572                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20573                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20574                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20575            }
20576        } catch (Exception e) {
20577            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20578            mAttachInfo.mDragSurface.destroy();
20579            mAttachInfo.mDragSurface = null;
20580        }
20581
20582        return okay;
20583    }
20584
20585    /**
20586     * Cancels an ongoing drag and drop operation.
20587     * <p>
20588     * A {@link android.view.DragEvent} object with
20589     * {@link android.view.DragEvent#getAction()} value of
20590     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20591     * {@link android.view.DragEvent#getResult()} value of {@code false}
20592     * will be sent to every
20593     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20594     * even if they are not currently visible.
20595     * </p>
20596     * <p>
20597     * This method can be called on any View in the same window as the View on which
20598     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20599     * was called.
20600     * </p>
20601     */
20602    public final void cancelDragAndDrop() {
20603        if (ViewDebug.DEBUG_DRAG) {
20604            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20605        }
20606        if (mAttachInfo.mDragToken != null) {
20607            try {
20608                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20609            } catch (Exception e) {
20610                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20611            }
20612            mAttachInfo.mDragToken = null;
20613        } else {
20614            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20615        }
20616    }
20617
20618    /**
20619     * Updates the drag shadow for the ongoing drag and drop operation.
20620     *
20621     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20622     * new drag shadow.
20623     */
20624    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20625        if (ViewDebug.DEBUG_DRAG) {
20626            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20627        }
20628        if (mAttachInfo.mDragToken != null) {
20629            try {
20630                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20631                try {
20632                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20633                    shadowBuilder.onDrawShadow(canvas);
20634                } finally {
20635                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20636                }
20637            } catch (Exception e) {
20638                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20639            }
20640        } else {
20641            Log.e(VIEW_LOG_TAG, "No active drag");
20642        }
20643    }
20644
20645    /**
20646     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20647     * between {startX, startY} and the new cursor positon.
20648     * @param startX horizontal coordinate where the move started.
20649     * @param startY vertical coordinate where the move started.
20650     * @return whether moving was started successfully.
20651     * @hide
20652     */
20653    public final boolean startMovingTask(float startX, float startY) {
20654        if (ViewDebug.DEBUG_POSITIONING) {
20655            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20656        }
20657        try {
20658            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20659        } catch (RemoteException e) {
20660            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20661        }
20662        return false;
20663    }
20664
20665    /**
20666     * Handles drag events sent by the system following a call to
20667     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20668     * startDragAndDrop()}.
20669     *<p>
20670     * When the system calls this method, it passes a
20671     * {@link android.view.DragEvent} object. A call to
20672     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20673     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20674     * operation.
20675     * @param event The {@link android.view.DragEvent} sent by the system.
20676     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20677     * in DragEvent, indicating the type of drag event represented by this object.
20678     * @return {@code true} if the method was successful, otherwise {@code false}.
20679     * <p>
20680     *  The method should return {@code true} in response to an action type of
20681     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20682     *  operation.
20683     * </p>
20684     * <p>
20685     *  The method should also return {@code true} in response to an action type of
20686     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20687     *  {@code false} if it didn't.
20688     * </p>
20689     */
20690    public boolean onDragEvent(DragEvent event) {
20691        return false;
20692    }
20693
20694    /**
20695     * Detects if this View is enabled and has a drag event listener.
20696     * If both are true, then it calls the drag event listener with the
20697     * {@link android.view.DragEvent} it received. If the drag event listener returns
20698     * {@code true}, then dispatchDragEvent() returns {@code true}.
20699     * <p>
20700     * For all other cases, the method calls the
20701     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20702     * method and returns its result.
20703     * </p>
20704     * <p>
20705     * This ensures that a drag event is always consumed, even if the View does not have a drag
20706     * event listener. However, if the View has a listener and the listener returns true, then
20707     * onDragEvent() is not called.
20708     * </p>
20709     */
20710    public boolean dispatchDragEvent(DragEvent event) {
20711        ListenerInfo li = mListenerInfo;
20712        //noinspection SimplifiableIfStatement
20713        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20714                && li.mOnDragListener.onDrag(this, event)) {
20715            return true;
20716        }
20717        return onDragEvent(event);
20718    }
20719
20720    boolean canAcceptDrag() {
20721        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20722    }
20723
20724    /**
20725     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20726     * it is ever exposed at all.
20727     * @hide
20728     */
20729    public void onCloseSystemDialogs(String reason) {
20730    }
20731
20732    /**
20733     * Given a Drawable whose bounds have been set to draw into this view,
20734     * update a Region being computed for
20735     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20736     * that any non-transparent parts of the Drawable are removed from the
20737     * given transparent region.
20738     *
20739     * @param dr The Drawable whose transparency is to be applied to the region.
20740     * @param region A Region holding the current transparency information,
20741     * where any parts of the region that are set are considered to be
20742     * transparent.  On return, this region will be modified to have the
20743     * transparency information reduced by the corresponding parts of the
20744     * Drawable that are not transparent.
20745     * {@hide}
20746     */
20747    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20748        if (DBG) {
20749            Log.i("View", "Getting transparent region for: " + this);
20750        }
20751        final Region r = dr.getTransparentRegion();
20752        final Rect db = dr.getBounds();
20753        final AttachInfo attachInfo = mAttachInfo;
20754        if (r != null && attachInfo != null) {
20755            final int w = getRight()-getLeft();
20756            final int h = getBottom()-getTop();
20757            if (db.left > 0) {
20758                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20759                r.op(0, 0, db.left, h, Region.Op.UNION);
20760            }
20761            if (db.right < w) {
20762                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20763                r.op(db.right, 0, w, h, Region.Op.UNION);
20764            }
20765            if (db.top > 0) {
20766                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20767                r.op(0, 0, w, db.top, Region.Op.UNION);
20768            }
20769            if (db.bottom < h) {
20770                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20771                r.op(0, db.bottom, w, h, Region.Op.UNION);
20772            }
20773            final int[] location = attachInfo.mTransparentLocation;
20774            getLocationInWindow(location);
20775            r.translate(location[0], location[1]);
20776            region.op(r, Region.Op.INTERSECT);
20777        } else {
20778            region.op(db, Region.Op.DIFFERENCE);
20779        }
20780    }
20781
20782    private void checkForLongClick(int delayOffset, float x, float y) {
20783        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20784            mHasPerformedLongPress = false;
20785
20786            if (mPendingCheckForLongPress == null) {
20787                mPendingCheckForLongPress = new CheckForLongPress();
20788            }
20789            mPendingCheckForLongPress.setAnchor(x, y);
20790            mPendingCheckForLongPress.rememberWindowAttachCount();
20791            postDelayed(mPendingCheckForLongPress,
20792                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20793        }
20794    }
20795
20796    /**
20797     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20798     * LayoutInflater} class, which provides a full range of options for view inflation.
20799     *
20800     * @param context The Context object for your activity or application.
20801     * @param resource The resource ID to inflate
20802     * @param root A view group that will be the parent.  Used to properly inflate the
20803     * layout_* parameters.
20804     * @see LayoutInflater
20805     */
20806    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20807        LayoutInflater factory = LayoutInflater.from(context);
20808        return factory.inflate(resource, root);
20809    }
20810
20811    /**
20812     * Scroll the view with standard behavior for scrolling beyond the normal
20813     * content boundaries. Views that call this method should override
20814     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20815     * results of an over-scroll operation.
20816     *
20817     * Views can use this method to handle any touch or fling-based scrolling.
20818     *
20819     * @param deltaX Change in X in pixels
20820     * @param deltaY Change in Y in pixels
20821     * @param scrollX Current X scroll value in pixels before applying deltaX
20822     * @param scrollY Current Y scroll value in pixels before applying deltaY
20823     * @param scrollRangeX Maximum content scroll range along the X axis
20824     * @param scrollRangeY Maximum content scroll range along the Y axis
20825     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20826     *          along the X axis.
20827     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20828     *          along the Y axis.
20829     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20830     * @return true if scrolling was clamped to an over-scroll boundary along either
20831     *          axis, false otherwise.
20832     */
20833    @SuppressWarnings({"UnusedParameters"})
20834    protected boolean overScrollBy(int deltaX, int deltaY,
20835            int scrollX, int scrollY,
20836            int scrollRangeX, int scrollRangeY,
20837            int maxOverScrollX, int maxOverScrollY,
20838            boolean isTouchEvent) {
20839        final int overScrollMode = mOverScrollMode;
20840        final boolean canScrollHorizontal =
20841                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
20842        final boolean canScrollVertical =
20843                computeVerticalScrollRange() > computeVerticalScrollExtent();
20844        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
20845                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
20846        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
20847                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
20848
20849        int newScrollX = scrollX + deltaX;
20850        if (!overScrollHorizontal) {
20851            maxOverScrollX = 0;
20852        }
20853
20854        int newScrollY = scrollY + deltaY;
20855        if (!overScrollVertical) {
20856            maxOverScrollY = 0;
20857        }
20858
20859        // Clamp values if at the limits and record
20860        final int left = -maxOverScrollX;
20861        final int right = maxOverScrollX + scrollRangeX;
20862        final int top = -maxOverScrollY;
20863        final int bottom = maxOverScrollY + scrollRangeY;
20864
20865        boolean clampedX = false;
20866        if (newScrollX > right) {
20867            newScrollX = right;
20868            clampedX = true;
20869        } else if (newScrollX < left) {
20870            newScrollX = left;
20871            clampedX = true;
20872        }
20873
20874        boolean clampedY = false;
20875        if (newScrollY > bottom) {
20876            newScrollY = bottom;
20877            clampedY = true;
20878        } else if (newScrollY < top) {
20879            newScrollY = top;
20880            clampedY = true;
20881        }
20882
20883        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
20884
20885        return clampedX || clampedY;
20886    }
20887
20888    /**
20889     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
20890     * respond to the results of an over-scroll operation.
20891     *
20892     * @param scrollX New X scroll value in pixels
20893     * @param scrollY New Y scroll value in pixels
20894     * @param clampedX True if scrollX was clamped to an over-scroll boundary
20895     * @param clampedY True if scrollY was clamped to an over-scroll boundary
20896     */
20897    protected void onOverScrolled(int scrollX, int scrollY,
20898            boolean clampedX, boolean clampedY) {
20899        // Intentionally empty.
20900    }
20901
20902    /**
20903     * Returns the over-scroll mode for this view. The result will be
20904     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20905     * (allow over-scrolling only if the view content is larger than the container),
20906     * or {@link #OVER_SCROLL_NEVER}.
20907     *
20908     * @return This view's over-scroll mode.
20909     */
20910    public int getOverScrollMode() {
20911        return mOverScrollMode;
20912    }
20913
20914    /**
20915     * Set the over-scroll mode for this view. Valid over-scroll modes are
20916     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20917     * (allow over-scrolling only if the view content is larger than the container),
20918     * or {@link #OVER_SCROLL_NEVER}.
20919     *
20920     * Setting the over-scroll mode of a view will have an effect only if the
20921     * view is capable of scrolling.
20922     *
20923     * @param overScrollMode The new over-scroll mode for this view.
20924     */
20925    public void setOverScrollMode(int overScrollMode) {
20926        if (overScrollMode != OVER_SCROLL_ALWAYS &&
20927                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
20928                overScrollMode != OVER_SCROLL_NEVER) {
20929            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
20930        }
20931        mOverScrollMode = overScrollMode;
20932    }
20933
20934    /**
20935     * Enable or disable nested scrolling for this view.
20936     *
20937     * <p>If this property is set to true the view will be permitted to initiate nested
20938     * scrolling operations with a compatible parent view in the current hierarchy. If this
20939     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
20940     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
20941     * the nested scroll.</p>
20942     *
20943     * @param enabled true to enable nested scrolling, false to disable
20944     *
20945     * @see #isNestedScrollingEnabled()
20946     */
20947    public void setNestedScrollingEnabled(boolean enabled) {
20948        if (enabled) {
20949            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
20950        } else {
20951            stopNestedScroll();
20952            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
20953        }
20954    }
20955
20956    /**
20957     * Returns true if nested scrolling is enabled for this view.
20958     *
20959     * <p>If nested scrolling is enabled and this View class implementation supports it,
20960     * this view will act as a nested scrolling child view when applicable, forwarding data
20961     * about the scroll operation in progress to a compatible and cooperating nested scrolling
20962     * parent.</p>
20963     *
20964     * @return true if nested scrolling is enabled
20965     *
20966     * @see #setNestedScrollingEnabled(boolean)
20967     */
20968    public boolean isNestedScrollingEnabled() {
20969        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
20970                PFLAG3_NESTED_SCROLLING_ENABLED;
20971    }
20972
20973    /**
20974     * Begin a nestable scroll operation along the given axes.
20975     *
20976     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
20977     *
20978     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
20979     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
20980     * In the case of touch scrolling the nested scroll will be terminated automatically in
20981     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
20982     * In the event of programmatic scrolling the caller must explicitly call
20983     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
20984     *
20985     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
20986     * If it returns false the caller may ignore the rest of this contract until the next scroll.
20987     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
20988     *
20989     * <p>At each incremental step of the scroll the caller should invoke
20990     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
20991     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
20992     * parent at least partially consumed the scroll and the caller should adjust the amount it
20993     * scrolls by.</p>
20994     *
20995     * <p>After applying the remainder of the scroll delta the caller should invoke
20996     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
20997     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
20998     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
20999     * </p>
21000     *
21001     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21002     *             {@link #SCROLL_AXIS_VERTICAL}.
21003     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21004     *         the current gesture.
21005     *
21006     * @see #stopNestedScroll()
21007     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21008     * @see #dispatchNestedScroll(int, int, int, int, int[])
21009     */
21010    public boolean startNestedScroll(int axes) {
21011        if (hasNestedScrollingParent()) {
21012            // Already in progress
21013            return true;
21014        }
21015        if (isNestedScrollingEnabled()) {
21016            ViewParent p = getParent();
21017            View child = this;
21018            while (p != null) {
21019                try {
21020                    if (p.onStartNestedScroll(child, this, axes)) {
21021                        mNestedScrollingParent = p;
21022                        p.onNestedScrollAccepted(child, this, axes);
21023                        return true;
21024                    }
21025                } catch (AbstractMethodError e) {
21026                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21027                            "method onStartNestedScroll", e);
21028                    // Allow the search upward to continue
21029                }
21030                if (p instanceof View) {
21031                    child = (View) p;
21032                }
21033                p = p.getParent();
21034            }
21035        }
21036        return false;
21037    }
21038
21039    /**
21040     * Stop a nested scroll in progress.
21041     *
21042     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21043     *
21044     * @see #startNestedScroll(int)
21045     */
21046    public void stopNestedScroll() {
21047        if (mNestedScrollingParent != null) {
21048            mNestedScrollingParent.onStopNestedScroll(this);
21049            mNestedScrollingParent = null;
21050        }
21051    }
21052
21053    /**
21054     * Returns true if this view has a nested scrolling parent.
21055     *
21056     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21057     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21058     *
21059     * @return whether this view has a nested scrolling parent
21060     */
21061    public boolean hasNestedScrollingParent() {
21062        return mNestedScrollingParent != null;
21063    }
21064
21065    /**
21066     * Dispatch one step of a nested scroll in progress.
21067     *
21068     * <p>Implementations of views that support nested scrolling should call this to report
21069     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21070     * is not currently in progress or nested scrolling is not
21071     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21072     *
21073     * <p>Compatible View implementations should also call
21074     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21075     * consuming a component of the scroll event themselves.</p>
21076     *
21077     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21078     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21079     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21080     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21081     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21082     *                       in local view coordinates of this view from before this operation
21083     *                       to after it completes. View implementations may use this to adjust
21084     *                       expected input coordinate tracking.
21085     * @return true if the event was dispatched, false if it could not be dispatched.
21086     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21087     */
21088    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21089            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21090        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21091            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21092                int startX = 0;
21093                int startY = 0;
21094                if (offsetInWindow != null) {
21095                    getLocationInWindow(offsetInWindow);
21096                    startX = offsetInWindow[0];
21097                    startY = offsetInWindow[1];
21098                }
21099
21100                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21101                        dxUnconsumed, dyUnconsumed);
21102
21103                if (offsetInWindow != null) {
21104                    getLocationInWindow(offsetInWindow);
21105                    offsetInWindow[0] -= startX;
21106                    offsetInWindow[1] -= startY;
21107                }
21108                return true;
21109            } else if (offsetInWindow != null) {
21110                // No motion, no dispatch. Keep offsetInWindow up to date.
21111                offsetInWindow[0] = 0;
21112                offsetInWindow[1] = 0;
21113            }
21114        }
21115        return false;
21116    }
21117
21118    /**
21119     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21120     *
21121     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21122     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21123     * scrolling operation to consume some or all of the scroll operation before the child view
21124     * consumes it.</p>
21125     *
21126     * @param dx Horizontal scroll distance in pixels
21127     * @param dy Vertical scroll distance in pixels
21128     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21129     *                 and consumed[1] the consumed dy.
21130     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21131     *                       in local view coordinates of this view from before this operation
21132     *                       to after it completes. View implementations may use this to adjust
21133     *                       expected input coordinate tracking.
21134     * @return true if the parent consumed some or all of the scroll delta
21135     * @see #dispatchNestedScroll(int, int, int, int, int[])
21136     */
21137    public boolean dispatchNestedPreScroll(int dx, int dy,
21138            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21139        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21140            if (dx != 0 || dy != 0) {
21141                int startX = 0;
21142                int startY = 0;
21143                if (offsetInWindow != null) {
21144                    getLocationInWindow(offsetInWindow);
21145                    startX = offsetInWindow[0];
21146                    startY = offsetInWindow[1];
21147                }
21148
21149                if (consumed == null) {
21150                    if (mTempNestedScrollConsumed == null) {
21151                        mTempNestedScrollConsumed = new int[2];
21152                    }
21153                    consumed = mTempNestedScrollConsumed;
21154                }
21155                consumed[0] = 0;
21156                consumed[1] = 0;
21157                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21158
21159                if (offsetInWindow != null) {
21160                    getLocationInWindow(offsetInWindow);
21161                    offsetInWindow[0] -= startX;
21162                    offsetInWindow[1] -= startY;
21163                }
21164                return consumed[0] != 0 || consumed[1] != 0;
21165            } else if (offsetInWindow != null) {
21166                offsetInWindow[0] = 0;
21167                offsetInWindow[1] = 0;
21168            }
21169        }
21170        return false;
21171    }
21172
21173    /**
21174     * Dispatch a fling to a nested scrolling parent.
21175     *
21176     * <p>This method should be used to indicate that a nested scrolling child has detected
21177     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21178     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21179     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21180     * along a scrollable axis.</p>
21181     *
21182     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21183     * its own content, it can use this method to delegate the fling to its nested scrolling
21184     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21185     *
21186     * @param velocityX Horizontal fling velocity in pixels per second
21187     * @param velocityY Vertical fling velocity in pixels per second
21188     * @param consumed true if the child consumed the fling, false otherwise
21189     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21190     */
21191    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21192        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21193            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21194        }
21195        return false;
21196    }
21197
21198    /**
21199     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21200     *
21201     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21202     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21203     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21204     * before the child view consumes it. If this method returns <code>true</code>, a nested
21205     * parent view consumed the fling and this view should not scroll as a result.</p>
21206     *
21207     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21208     * the fling at a time. If a parent view consumed the fling this method will return false.
21209     * Custom view implementations should account for this in two ways:</p>
21210     *
21211     * <ul>
21212     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21213     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21214     *     position regardless.</li>
21215     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21216     *     even to settle back to a valid idle position.</li>
21217     * </ul>
21218     *
21219     * <p>Views should also not offer fling velocities to nested parent views along an axis
21220     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21221     * should not offer a horizontal fling velocity to its parents since scrolling along that
21222     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21223     *
21224     * @param velocityX Horizontal fling velocity in pixels per second
21225     * @param velocityY Vertical fling velocity in pixels per second
21226     * @return true if a nested scrolling parent consumed the fling
21227     */
21228    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21229        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21230            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21231        }
21232        return false;
21233    }
21234
21235    /**
21236     * Gets a scale factor that determines the distance the view should scroll
21237     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21238     * @return The vertical scroll scale factor.
21239     * @hide
21240     */
21241    protected float getVerticalScrollFactor() {
21242        if (mVerticalScrollFactor == 0) {
21243            TypedValue outValue = new TypedValue();
21244            if (!mContext.getTheme().resolveAttribute(
21245                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21246                throw new IllegalStateException(
21247                        "Expected theme to define listPreferredItemHeight.");
21248            }
21249            mVerticalScrollFactor = outValue.getDimension(
21250                    mContext.getResources().getDisplayMetrics());
21251        }
21252        return mVerticalScrollFactor;
21253    }
21254
21255    /**
21256     * Gets a scale factor that determines the distance the view should scroll
21257     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21258     * @return The horizontal scroll scale factor.
21259     * @hide
21260     */
21261    protected float getHorizontalScrollFactor() {
21262        // TODO: Should use something else.
21263        return getVerticalScrollFactor();
21264    }
21265
21266    /**
21267     * Return the value specifying the text direction or policy that was set with
21268     * {@link #setTextDirection(int)}.
21269     *
21270     * @return the defined text direction. It can be one of:
21271     *
21272     * {@link #TEXT_DIRECTION_INHERIT},
21273     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21274     * {@link #TEXT_DIRECTION_ANY_RTL},
21275     * {@link #TEXT_DIRECTION_LTR},
21276     * {@link #TEXT_DIRECTION_RTL},
21277     * {@link #TEXT_DIRECTION_LOCALE},
21278     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21279     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21280     *
21281     * @attr ref android.R.styleable#View_textDirection
21282     *
21283     * @hide
21284     */
21285    @ViewDebug.ExportedProperty(category = "text", mapping = {
21286            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21287            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21288            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21289            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21290            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21291            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21292            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21293            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21294    })
21295    public int getRawTextDirection() {
21296        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21297    }
21298
21299    /**
21300     * Set the text direction.
21301     *
21302     * @param textDirection the direction to set. Should be one of:
21303     *
21304     * {@link #TEXT_DIRECTION_INHERIT},
21305     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21306     * {@link #TEXT_DIRECTION_ANY_RTL},
21307     * {@link #TEXT_DIRECTION_LTR},
21308     * {@link #TEXT_DIRECTION_RTL},
21309     * {@link #TEXT_DIRECTION_LOCALE}
21310     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21311     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21312     *
21313     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21314     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21315     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21316     *
21317     * @attr ref android.R.styleable#View_textDirection
21318     */
21319    public void setTextDirection(int textDirection) {
21320        if (getRawTextDirection() != textDirection) {
21321            // Reset the current text direction and the resolved one
21322            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21323            resetResolvedTextDirection();
21324            // Set the new text direction
21325            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21326            // Do resolution
21327            resolveTextDirection();
21328            // Notify change
21329            onRtlPropertiesChanged(getLayoutDirection());
21330            // Refresh
21331            requestLayout();
21332            invalidate(true);
21333        }
21334    }
21335
21336    /**
21337     * Return the resolved text direction.
21338     *
21339     * @return the resolved text direction. Returns one of:
21340     *
21341     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21342     * {@link #TEXT_DIRECTION_ANY_RTL},
21343     * {@link #TEXT_DIRECTION_LTR},
21344     * {@link #TEXT_DIRECTION_RTL},
21345     * {@link #TEXT_DIRECTION_LOCALE},
21346     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21347     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21348     *
21349     * @attr ref android.R.styleable#View_textDirection
21350     */
21351    @ViewDebug.ExportedProperty(category = "text", mapping = {
21352            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21353            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21354            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21355            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21356            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21357            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21358            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21359            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21360    })
21361    public int getTextDirection() {
21362        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21363    }
21364
21365    /**
21366     * Resolve the text direction.
21367     *
21368     * @return true if resolution has been done, false otherwise.
21369     *
21370     * @hide
21371     */
21372    public boolean resolveTextDirection() {
21373        // Reset any previous text direction resolution
21374        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21375
21376        if (hasRtlSupport()) {
21377            // Set resolved text direction flag depending on text direction flag
21378            final int textDirection = getRawTextDirection();
21379            switch(textDirection) {
21380                case TEXT_DIRECTION_INHERIT:
21381                    if (!canResolveTextDirection()) {
21382                        // We cannot do the resolution if there is no parent, so use the default one
21383                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21384                        // Resolution will need to happen again later
21385                        return false;
21386                    }
21387
21388                    // Parent has not yet resolved, so we still return the default
21389                    try {
21390                        if (!mParent.isTextDirectionResolved()) {
21391                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21392                            // Resolution will need to happen again later
21393                            return false;
21394                        }
21395                    } catch (AbstractMethodError e) {
21396                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21397                                " does not fully implement ViewParent", e);
21398                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21399                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21400                        return true;
21401                    }
21402
21403                    // Set current resolved direction to the same value as the parent's one
21404                    int parentResolvedDirection;
21405                    try {
21406                        parentResolvedDirection = mParent.getTextDirection();
21407                    } catch (AbstractMethodError e) {
21408                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21409                                " does not fully implement ViewParent", e);
21410                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21411                    }
21412                    switch (parentResolvedDirection) {
21413                        case TEXT_DIRECTION_FIRST_STRONG:
21414                        case TEXT_DIRECTION_ANY_RTL:
21415                        case TEXT_DIRECTION_LTR:
21416                        case TEXT_DIRECTION_RTL:
21417                        case TEXT_DIRECTION_LOCALE:
21418                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21419                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21420                            mPrivateFlags2 |=
21421                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21422                            break;
21423                        default:
21424                            // Default resolved direction is "first strong" heuristic
21425                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21426                    }
21427                    break;
21428                case TEXT_DIRECTION_FIRST_STRONG:
21429                case TEXT_DIRECTION_ANY_RTL:
21430                case TEXT_DIRECTION_LTR:
21431                case TEXT_DIRECTION_RTL:
21432                case TEXT_DIRECTION_LOCALE:
21433                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21434                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21435                    // Resolved direction is the same as text direction
21436                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21437                    break;
21438                default:
21439                    // Default resolved direction is "first strong" heuristic
21440                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21441            }
21442        } else {
21443            // Default resolved direction is "first strong" heuristic
21444            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21445        }
21446
21447        // Set to resolved
21448        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21449        return true;
21450    }
21451
21452    /**
21453     * Check if text direction resolution can be done.
21454     *
21455     * @return true if text direction resolution can be done otherwise return false.
21456     */
21457    public boolean canResolveTextDirection() {
21458        switch (getRawTextDirection()) {
21459            case TEXT_DIRECTION_INHERIT:
21460                if (mParent != null) {
21461                    try {
21462                        return mParent.canResolveTextDirection();
21463                    } catch (AbstractMethodError e) {
21464                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21465                                " does not fully implement ViewParent", e);
21466                    }
21467                }
21468                return false;
21469
21470            default:
21471                return true;
21472        }
21473    }
21474
21475    /**
21476     * Reset resolved text direction. Text direction will be resolved during a call to
21477     * {@link #onMeasure(int, int)}.
21478     *
21479     * @hide
21480     */
21481    public void resetResolvedTextDirection() {
21482        // Reset any previous text direction resolution
21483        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21484        // Set to default value
21485        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21486    }
21487
21488    /**
21489     * @return true if text direction is inherited.
21490     *
21491     * @hide
21492     */
21493    public boolean isTextDirectionInherited() {
21494        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21495    }
21496
21497    /**
21498     * @return true if text direction is resolved.
21499     */
21500    public boolean isTextDirectionResolved() {
21501        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21502    }
21503
21504    /**
21505     * Return the value specifying the text alignment or policy that was set with
21506     * {@link #setTextAlignment(int)}.
21507     *
21508     * @return the defined text alignment. It can be one of:
21509     *
21510     * {@link #TEXT_ALIGNMENT_INHERIT},
21511     * {@link #TEXT_ALIGNMENT_GRAVITY},
21512     * {@link #TEXT_ALIGNMENT_CENTER},
21513     * {@link #TEXT_ALIGNMENT_TEXT_START},
21514     * {@link #TEXT_ALIGNMENT_TEXT_END},
21515     * {@link #TEXT_ALIGNMENT_VIEW_START},
21516     * {@link #TEXT_ALIGNMENT_VIEW_END}
21517     *
21518     * @attr ref android.R.styleable#View_textAlignment
21519     *
21520     * @hide
21521     */
21522    @ViewDebug.ExportedProperty(category = "text", mapping = {
21523            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21524            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21525            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21526            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21527            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21528            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21529            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21530    })
21531    @TextAlignment
21532    public int getRawTextAlignment() {
21533        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21534    }
21535
21536    /**
21537     * Set the text alignment.
21538     *
21539     * @param textAlignment The text alignment to set. Should be one of
21540     *
21541     * {@link #TEXT_ALIGNMENT_INHERIT},
21542     * {@link #TEXT_ALIGNMENT_GRAVITY},
21543     * {@link #TEXT_ALIGNMENT_CENTER},
21544     * {@link #TEXT_ALIGNMENT_TEXT_START},
21545     * {@link #TEXT_ALIGNMENT_TEXT_END},
21546     * {@link #TEXT_ALIGNMENT_VIEW_START},
21547     * {@link #TEXT_ALIGNMENT_VIEW_END}
21548     *
21549     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21550     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21551     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21552     *
21553     * @attr ref android.R.styleable#View_textAlignment
21554     */
21555    public void setTextAlignment(@TextAlignment int textAlignment) {
21556        if (textAlignment != getRawTextAlignment()) {
21557            // Reset the current and resolved text alignment
21558            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21559            resetResolvedTextAlignment();
21560            // Set the new text alignment
21561            mPrivateFlags2 |=
21562                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21563            // Do resolution
21564            resolveTextAlignment();
21565            // Notify change
21566            onRtlPropertiesChanged(getLayoutDirection());
21567            // Refresh
21568            requestLayout();
21569            invalidate(true);
21570        }
21571    }
21572
21573    /**
21574     * Return the resolved text alignment.
21575     *
21576     * @return the resolved text alignment. Returns one of:
21577     *
21578     * {@link #TEXT_ALIGNMENT_GRAVITY},
21579     * {@link #TEXT_ALIGNMENT_CENTER},
21580     * {@link #TEXT_ALIGNMENT_TEXT_START},
21581     * {@link #TEXT_ALIGNMENT_TEXT_END},
21582     * {@link #TEXT_ALIGNMENT_VIEW_START},
21583     * {@link #TEXT_ALIGNMENT_VIEW_END}
21584     *
21585     * @attr ref android.R.styleable#View_textAlignment
21586     */
21587    @ViewDebug.ExportedProperty(category = "text", mapping = {
21588            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21589            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21590            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21591            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21592            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21593            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21594            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21595    })
21596    @TextAlignment
21597    public int getTextAlignment() {
21598        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21599                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21600    }
21601
21602    /**
21603     * Resolve the text alignment.
21604     *
21605     * @return true if resolution has been done, false otherwise.
21606     *
21607     * @hide
21608     */
21609    public boolean resolveTextAlignment() {
21610        // Reset any previous text alignment resolution
21611        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21612
21613        if (hasRtlSupport()) {
21614            // Set resolved text alignment flag depending on text alignment flag
21615            final int textAlignment = getRawTextAlignment();
21616            switch (textAlignment) {
21617                case TEXT_ALIGNMENT_INHERIT:
21618                    // Check if we can resolve the text alignment
21619                    if (!canResolveTextAlignment()) {
21620                        // We cannot do the resolution if there is no parent so use the default
21621                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21622                        // Resolution will need to happen again later
21623                        return false;
21624                    }
21625
21626                    // Parent has not yet resolved, so we still return the default
21627                    try {
21628                        if (!mParent.isTextAlignmentResolved()) {
21629                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21630                            // Resolution will need to happen again later
21631                            return false;
21632                        }
21633                    } catch (AbstractMethodError e) {
21634                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21635                                " does not fully implement ViewParent", e);
21636                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21637                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21638                        return true;
21639                    }
21640
21641                    int parentResolvedTextAlignment;
21642                    try {
21643                        parentResolvedTextAlignment = mParent.getTextAlignment();
21644                    } catch (AbstractMethodError e) {
21645                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21646                                " does not fully implement ViewParent", e);
21647                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21648                    }
21649                    switch (parentResolvedTextAlignment) {
21650                        case TEXT_ALIGNMENT_GRAVITY:
21651                        case TEXT_ALIGNMENT_TEXT_START:
21652                        case TEXT_ALIGNMENT_TEXT_END:
21653                        case TEXT_ALIGNMENT_CENTER:
21654                        case TEXT_ALIGNMENT_VIEW_START:
21655                        case TEXT_ALIGNMENT_VIEW_END:
21656                            // Resolved text alignment is the same as the parent resolved
21657                            // text alignment
21658                            mPrivateFlags2 |=
21659                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21660                            break;
21661                        default:
21662                            // Use default resolved text alignment
21663                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21664                    }
21665                    break;
21666                case TEXT_ALIGNMENT_GRAVITY:
21667                case TEXT_ALIGNMENT_TEXT_START:
21668                case TEXT_ALIGNMENT_TEXT_END:
21669                case TEXT_ALIGNMENT_CENTER:
21670                case TEXT_ALIGNMENT_VIEW_START:
21671                case TEXT_ALIGNMENT_VIEW_END:
21672                    // Resolved text alignment is the same as text alignment
21673                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21674                    break;
21675                default:
21676                    // Use default resolved text alignment
21677                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21678            }
21679        } else {
21680            // Use default resolved text alignment
21681            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21682        }
21683
21684        // Set the resolved
21685        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21686        return true;
21687    }
21688
21689    /**
21690     * Check if text alignment resolution can be done.
21691     *
21692     * @return true if text alignment resolution can be done otherwise return false.
21693     */
21694    public boolean canResolveTextAlignment() {
21695        switch (getRawTextAlignment()) {
21696            case TEXT_DIRECTION_INHERIT:
21697                if (mParent != null) {
21698                    try {
21699                        return mParent.canResolveTextAlignment();
21700                    } catch (AbstractMethodError e) {
21701                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21702                                " does not fully implement ViewParent", e);
21703                    }
21704                }
21705                return false;
21706
21707            default:
21708                return true;
21709        }
21710    }
21711
21712    /**
21713     * Reset resolved text alignment. Text alignment will be resolved during a call to
21714     * {@link #onMeasure(int, int)}.
21715     *
21716     * @hide
21717     */
21718    public void resetResolvedTextAlignment() {
21719        // Reset any previous text alignment resolution
21720        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21721        // Set to default
21722        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21723    }
21724
21725    /**
21726     * @return true if text alignment is inherited.
21727     *
21728     * @hide
21729     */
21730    public boolean isTextAlignmentInherited() {
21731        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21732    }
21733
21734    /**
21735     * @return true if text alignment is resolved.
21736     */
21737    public boolean isTextAlignmentResolved() {
21738        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21739    }
21740
21741    /**
21742     * Generate a value suitable for use in {@link #setId(int)}.
21743     * This value will not collide with ID values generated at build time by aapt for R.id.
21744     *
21745     * @return a generated ID value
21746     */
21747    public static int generateViewId() {
21748        for (;;) {
21749            final int result = sNextGeneratedId.get();
21750            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21751            int newValue = result + 1;
21752            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21753            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21754                return result;
21755            }
21756        }
21757    }
21758
21759    /**
21760     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21761     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21762     *                           a normal View or a ViewGroup with
21763     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21764     * @hide
21765     */
21766    public void captureTransitioningViews(List<View> transitioningViews) {
21767        if (getVisibility() == View.VISIBLE) {
21768            transitioningViews.add(this);
21769        }
21770    }
21771
21772    /**
21773     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21774     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21775     * @hide
21776     */
21777    public void findNamedViews(Map<String, View> namedElements) {
21778        if (getVisibility() == VISIBLE || mGhostView != null) {
21779            String transitionName = getTransitionName();
21780            if (transitionName != null) {
21781                namedElements.put(transitionName, this);
21782            }
21783        }
21784    }
21785
21786    /**
21787     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21788     * The default implementation does not care the location or event types, but some subclasses
21789     * may use it (such as WebViews).
21790     * @param event The MotionEvent from a mouse
21791     * @param x The x position of the event, local to the view
21792     * @param y The y position of the event, local to the view
21793     * @see PointerIcon
21794     */
21795    public PointerIcon getPointerIcon(MotionEvent event, float x, float y) {
21796        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21797            return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW);
21798        }
21799        return mPointerIcon;
21800    }
21801
21802    /**
21803     * Set the pointer icon for the current view.
21804     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21805     */
21806    public void setPointerIcon(PointerIcon pointerIcon) {
21807        mPointerIcon = pointerIcon;
21808        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21809            return;
21810        }
21811        try {
21812            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21813        } catch (RemoteException e) {
21814        }
21815    }
21816
21817    /**
21818     * Request capturing further mouse events.
21819     *
21820     * When the view captures, the mouse pointer icon will disappear and will not change its
21821     * position. Further mouse events will come to the capturing view, and the mouse movements
21822     * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and
21823     * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not
21824     * be affected.
21825     *
21826     * The capture will be released through {@link #releasePointerCapture()}, or will be lost
21827     * automatically when the view or containing window disappear.
21828     *
21829     * @return true when succeeds.
21830     * @see #releasePointerCapture()
21831     * @see #hasPointerCapture()
21832     */
21833    public void setPointerCapture() {
21834        final ViewRootImpl viewRootImpl = getViewRootImpl();
21835        if (viewRootImpl != null) {
21836            viewRootImpl.setPointerCapture(this);
21837        }
21838    }
21839
21840
21841    /**
21842     * Release the current capture of mouse events.
21843     *
21844     * If the view does not have the capture, it will do nothing.
21845     * @see #setPointerCapture()
21846     * @see #hasPointerCapture()
21847     */
21848    public void releasePointerCapture() {
21849        final ViewRootImpl viewRootImpl = getViewRootImpl();
21850        if (viewRootImpl != null) {
21851            viewRootImpl.releasePointerCapture(this);
21852        }
21853    }
21854
21855    /**
21856     * Checks the capture status of mouse events.
21857     *
21858     * @return true if the view has the capture.
21859     * @see #setPointerCapture()
21860     * @see #hasPointerCapture()
21861     */
21862    public boolean hasPointerCapture() {
21863        final ViewRootImpl viewRootImpl = getViewRootImpl();
21864        return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this);
21865    }
21866
21867    //
21868    // Properties
21869    //
21870    /**
21871     * A Property wrapper around the <code>alpha</code> functionality handled by the
21872     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21873     */
21874    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21875        @Override
21876        public void setValue(View object, float value) {
21877            object.setAlpha(value);
21878        }
21879
21880        @Override
21881        public Float get(View object) {
21882            return object.getAlpha();
21883        }
21884    };
21885
21886    /**
21887     * A Property wrapper around the <code>translationX</code> functionality handled by the
21888     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
21889     */
21890    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
21891        @Override
21892        public void setValue(View object, float value) {
21893            object.setTranslationX(value);
21894        }
21895
21896                @Override
21897        public Float get(View object) {
21898            return object.getTranslationX();
21899        }
21900    };
21901
21902    /**
21903     * A Property wrapper around the <code>translationY</code> functionality handled by the
21904     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
21905     */
21906    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
21907        @Override
21908        public void setValue(View object, float value) {
21909            object.setTranslationY(value);
21910        }
21911
21912        @Override
21913        public Float get(View object) {
21914            return object.getTranslationY();
21915        }
21916    };
21917
21918    /**
21919     * A Property wrapper around the <code>translationZ</code> functionality handled by the
21920     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
21921     */
21922    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
21923        @Override
21924        public void setValue(View object, float value) {
21925            object.setTranslationZ(value);
21926        }
21927
21928        @Override
21929        public Float get(View object) {
21930            return object.getTranslationZ();
21931        }
21932    };
21933
21934    /**
21935     * A Property wrapper around the <code>x</code> functionality handled by the
21936     * {@link View#setX(float)} and {@link View#getX()} methods.
21937     */
21938    public static final Property<View, Float> X = new FloatProperty<View>("x") {
21939        @Override
21940        public void setValue(View object, float value) {
21941            object.setX(value);
21942        }
21943
21944        @Override
21945        public Float get(View object) {
21946            return object.getX();
21947        }
21948    };
21949
21950    /**
21951     * A Property wrapper around the <code>y</code> functionality handled by the
21952     * {@link View#setY(float)} and {@link View#getY()} methods.
21953     */
21954    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
21955        @Override
21956        public void setValue(View object, float value) {
21957            object.setY(value);
21958        }
21959
21960        @Override
21961        public Float get(View object) {
21962            return object.getY();
21963        }
21964    };
21965
21966    /**
21967     * A Property wrapper around the <code>z</code> functionality handled by the
21968     * {@link View#setZ(float)} and {@link View#getZ()} methods.
21969     */
21970    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
21971        @Override
21972        public void setValue(View object, float value) {
21973            object.setZ(value);
21974        }
21975
21976        @Override
21977        public Float get(View object) {
21978            return object.getZ();
21979        }
21980    };
21981
21982    /**
21983     * A Property wrapper around the <code>rotation</code> functionality handled by the
21984     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
21985     */
21986    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
21987        @Override
21988        public void setValue(View object, float value) {
21989            object.setRotation(value);
21990        }
21991
21992        @Override
21993        public Float get(View object) {
21994            return object.getRotation();
21995        }
21996    };
21997
21998    /**
21999     * A Property wrapper around the <code>rotationX</code> functionality handled by the
22000     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
22001     */
22002    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22003        @Override
22004        public void setValue(View object, float value) {
22005            object.setRotationX(value);
22006        }
22007
22008        @Override
22009        public Float get(View object) {
22010            return object.getRotationX();
22011        }
22012    };
22013
22014    /**
22015     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22016     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22017     */
22018    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22019        @Override
22020        public void setValue(View object, float value) {
22021            object.setRotationY(value);
22022        }
22023
22024        @Override
22025        public Float get(View object) {
22026            return object.getRotationY();
22027        }
22028    };
22029
22030    /**
22031     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22032     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22033     */
22034    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22035        @Override
22036        public void setValue(View object, float value) {
22037            object.setScaleX(value);
22038        }
22039
22040        @Override
22041        public Float get(View object) {
22042            return object.getScaleX();
22043        }
22044    };
22045
22046    /**
22047     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22048     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22049     */
22050    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22051        @Override
22052        public void setValue(View object, float value) {
22053            object.setScaleY(value);
22054        }
22055
22056        @Override
22057        public Float get(View object) {
22058            return object.getScaleY();
22059        }
22060    };
22061
22062    /**
22063     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22064     * Each MeasureSpec represents a requirement for either the width or the height.
22065     * A MeasureSpec is comprised of a size and a mode. There are three possible
22066     * modes:
22067     * <dl>
22068     * <dt>UNSPECIFIED</dt>
22069     * <dd>
22070     * The parent has not imposed any constraint on the child. It can be whatever size
22071     * it wants.
22072     * </dd>
22073     *
22074     * <dt>EXACTLY</dt>
22075     * <dd>
22076     * The parent has determined an exact size for the child. The child is going to be
22077     * given those bounds regardless of how big it wants to be.
22078     * </dd>
22079     *
22080     * <dt>AT_MOST</dt>
22081     * <dd>
22082     * The child can be as large as it wants up to the specified size.
22083     * </dd>
22084     * </dl>
22085     *
22086     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22087     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22088     */
22089    public static class MeasureSpec {
22090        private static final int MODE_SHIFT = 30;
22091        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22092
22093        /** @hide */
22094        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22095        @Retention(RetentionPolicy.SOURCE)
22096        public @interface MeasureSpecMode {}
22097
22098        /**
22099         * Measure specification mode: The parent has not imposed any constraint
22100         * on the child. It can be whatever size it wants.
22101         */
22102        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22103
22104        /**
22105         * Measure specification mode: The parent has determined an exact size
22106         * for the child. The child is going to be given those bounds regardless
22107         * of how big it wants to be.
22108         */
22109        public static final int EXACTLY     = 1 << MODE_SHIFT;
22110
22111        /**
22112         * Measure specification mode: The child can be as large as it wants up
22113         * to the specified size.
22114         */
22115        public static final int AT_MOST     = 2 << MODE_SHIFT;
22116
22117        /**
22118         * Creates a measure specification based on the supplied size and mode.
22119         *
22120         * The mode must always be one of the following:
22121         * <ul>
22122         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22123         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22124         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22125         * </ul>
22126         *
22127         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22128         * implementation was such that the order of arguments did not matter
22129         * and overflow in either value could impact the resulting MeasureSpec.
22130         * {@link android.widget.RelativeLayout} was affected by this bug.
22131         * Apps targeting API levels greater than 17 will get the fixed, more strict
22132         * behavior.</p>
22133         *
22134         * @param size the size of the measure specification
22135         * @param mode the mode of the measure specification
22136         * @return the measure specification based on size and mode
22137         */
22138        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22139                                          @MeasureSpecMode int mode) {
22140            if (sUseBrokenMakeMeasureSpec) {
22141                return size + mode;
22142            } else {
22143                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22144            }
22145        }
22146
22147        /**
22148         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22149         * will automatically get a size of 0. Older apps expect this.
22150         *
22151         * @hide internal use only for compatibility with system widgets and older apps
22152         */
22153        public static int makeSafeMeasureSpec(int size, int mode) {
22154            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22155                return 0;
22156            }
22157            return makeMeasureSpec(size, mode);
22158        }
22159
22160        /**
22161         * Extracts the mode from the supplied measure specification.
22162         *
22163         * @param measureSpec the measure specification to extract the mode from
22164         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22165         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22166         *         {@link android.view.View.MeasureSpec#EXACTLY}
22167         */
22168        @MeasureSpecMode
22169        public static int getMode(int measureSpec) {
22170            //noinspection ResourceType
22171            return (measureSpec & MODE_MASK);
22172        }
22173
22174        /**
22175         * Extracts the size from the supplied measure specification.
22176         *
22177         * @param measureSpec the measure specification to extract the size from
22178         * @return the size in pixels defined in the supplied measure specification
22179         */
22180        public static int getSize(int measureSpec) {
22181            return (measureSpec & ~MODE_MASK);
22182        }
22183
22184        static int adjust(int measureSpec, int delta) {
22185            final int mode = getMode(measureSpec);
22186            int size = getSize(measureSpec);
22187            if (mode == UNSPECIFIED) {
22188                // No need to adjust size for UNSPECIFIED mode.
22189                return makeMeasureSpec(size, UNSPECIFIED);
22190            }
22191            size += delta;
22192            if (size < 0) {
22193                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22194                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22195                size = 0;
22196            }
22197            return makeMeasureSpec(size, mode);
22198        }
22199
22200        /**
22201         * Returns a String representation of the specified measure
22202         * specification.
22203         *
22204         * @param measureSpec the measure specification to convert to a String
22205         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22206         */
22207        public static String toString(int measureSpec) {
22208            int mode = getMode(measureSpec);
22209            int size = getSize(measureSpec);
22210
22211            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22212
22213            if (mode == UNSPECIFIED)
22214                sb.append("UNSPECIFIED ");
22215            else if (mode == EXACTLY)
22216                sb.append("EXACTLY ");
22217            else if (mode == AT_MOST)
22218                sb.append("AT_MOST ");
22219            else
22220                sb.append(mode).append(" ");
22221
22222            sb.append(size);
22223            return sb.toString();
22224        }
22225    }
22226
22227    private final class CheckForLongPress implements Runnable {
22228        private int mOriginalWindowAttachCount;
22229        private float mX;
22230        private float mY;
22231
22232        @Override
22233        public void run() {
22234            if (isPressed() && (mParent != null)
22235                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22236                if (performLongClick(mX, mY)) {
22237                    mHasPerformedLongPress = true;
22238                }
22239            }
22240        }
22241
22242        public void setAnchor(float x, float y) {
22243            mX = x;
22244            mY = y;
22245        }
22246
22247        public void rememberWindowAttachCount() {
22248            mOriginalWindowAttachCount = mWindowAttachCount;
22249        }
22250    }
22251
22252    private final class CheckForTap implements Runnable {
22253        public float x;
22254        public float y;
22255
22256        @Override
22257        public void run() {
22258            mPrivateFlags &= ~PFLAG_PREPRESSED;
22259            setPressed(true, x, y);
22260            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22261        }
22262    }
22263
22264    private final class PerformClick implements Runnable {
22265        @Override
22266        public void run() {
22267            performClick();
22268        }
22269    }
22270
22271    /**
22272     * This method returns a ViewPropertyAnimator object, which can be used to animate
22273     * specific properties on this View.
22274     *
22275     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22276     */
22277    public ViewPropertyAnimator animate() {
22278        if (mAnimator == null) {
22279            mAnimator = new ViewPropertyAnimator(this);
22280        }
22281        return mAnimator;
22282    }
22283
22284    /**
22285     * Sets the name of the View to be used to identify Views in Transitions.
22286     * Names should be unique in the View hierarchy.
22287     *
22288     * @param transitionName The name of the View to uniquely identify it for Transitions.
22289     */
22290    public final void setTransitionName(String transitionName) {
22291        mTransitionName = transitionName;
22292    }
22293
22294    /**
22295     * Returns the name of the View to be used to identify Views in Transitions.
22296     * Names should be unique in the View hierarchy.
22297     *
22298     * <p>This returns null if the View has not been given a name.</p>
22299     *
22300     * @return The name used of the View to be used to identify Views in Transitions or null
22301     * if no name has been given.
22302     */
22303    @ViewDebug.ExportedProperty
22304    public String getTransitionName() {
22305        return mTransitionName;
22306    }
22307
22308    /**
22309     * @hide
22310     */
22311    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22312        // Do nothing.
22313    }
22314
22315    /**
22316     * Interface definition for a callback to be invoked when a hardware key event is
22317     * dispatched to this view. The callback will be invoked before the key event is
22318     * given to the view. This is only useful for hardware keyboards; a software input
22319     * method has no obligation to trigger this listener.
22320     */
22321    public interface OnKeyListener {
22322        /**
22323         * Called when a hardware key is dispatched to a view. This allows listeners to
22324         * get a chance to respond before the target view.
22325         * <p>Key presses in software keyboards will generally NOT trigger this method,
22326         * although some may elect to do so in some situations. Do not assume a
22327         * software input method has to be key-based; even if it is, it may use key presses
22328         * in a different way than you expect, so there is no way to reliably catch soft
22329         * input key presses.
22330         *
22331         * @param v The view the key has been dispatched to.
22332         * @param keyCode The code for the physical key that was pressed
22333         * @param event The KeyEvent object containing full information about
22334         *        the event.
22335         * @return True if the listener has consumed the event, false otherwise.
22336         */
22337        boolean onKey(View v, int keyCode, KeyEvent event);
22338    }
22339
22340    /**
22341     * Interface definition for a callback to be invoked when a touch event is
22342     * dispatched to this view. The callback will be invoked before the touch
22343     * event is given to the view.
22344     */
22345    public interface OnTouchListener {
22346        /**
22347         * Called when a touch event is dispatched to a view. This allows listeners to
22348         * get a chance to respond before the target view.
22349         *
22350         * @param v The view the touch event has been dispatched to.
22351         * @param event The MotionEvent object containing full information about
22352         *        the event.
22353         * @return True if the listener has consumed the event, false otherwise.
22354         */
22355        boolean onTouch(View v, MotionEvent event);
22356    }
22357
22358    /**
22359     * Interface definition for a callback to be invoked when a hover event is
22360     * dispatched to this view. The callback will be invoked before the hover
22361     * event is given to the view.
22362     */
22363    public interface OnHoverListener {
22364        /**
22365         * Called when a hover event is dispatched to a view. This allows listeners to
22366         * get a chance to respond before the target view.
22367         *
22368         * @param v The view the hover event has been dispatched to.
22369         * @param event The MotionEvent object containing full information about
22370         *        the event.
22371         * @return True if the listener has consumed the event, false otherwise.
22372         */
22373        boolean onHover(View v, MotionEvent event);
22374    }
22375
22376    /**
22377     * Interface definition for a callback to be invoked when a generic motion event is
22378     * dispatched to this view. The callback will be invoked before the generic motion
22379     * event is given to the view.
22380     */
22381    public interface OnGenericMotionListener {
22382        /**
22383         * Called when a generic motion event is dispatched to a view. This allows listeners to
22384         * get a chance to respond before the target view.
22385         *
22386         * @param v The view the generic motion event has been dispatched to.
22387         * @param event The MotionEvent object containing full information about
22388         *        the event.
22389         * @return True if the listener has consumed the event, false otherwise.
22390         */
22391        boolean onGenericMotion(View v, MotionEvent event);
22392    }
22393
22394    /**
22395     * Interface definition for a callback to be invoked when a view has been clicked and held.
22396     */
22397    public interface OnLongClickListener {
22398        /**
22399         * Called when a view has been clicked and held.
22400         *
22401         * @param v The view that was clicked and held.
22402         *
22403         * @return true if the callback consumed the long click, false otherwise.
22404         */
22405        boolean onLongClick(View v);
22406    }
22407
22408    /**
22409     * Interface definition for a callback to be invoked when a drag is being dispatched
22410     * to this view.  The callback will be invoked before the hosting view's own
22411     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22412     * onDrag(event) behavior, it should return 'false' from this callback.
22413     *
22414     * <div class="special reference">
22415     * <h3>Developer Guides</h3>
22416     * <p>For a guide to implementing drag and drop features, read the
22417     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22418     * </div>
22419     */
22420    public interface OnDragListener {
22421        /**
22422         * Called when a drag event is dispatched to a view. This allows listeners
22423         * to get a chance to override base View behavior.
22424         *
22425         * @param v The View that received the drag event.
22426         * @param event The {@link android.view.DragEvent} object for the drag event.
22427         * @return {@code true} if the drag event was handled successfully, or {@code false}
22428         * if the drag event was not handled. Note that {@code false} will trigger the View
22429         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22430         */
22431        boolean onDrag(View v, DragEvent event);
22432    }
22433
22434    /**
22435     * Interface definition for a callback to be invoked when the focus state of
22436     * a view changed.
22437     */
22438    public interface OnFocusChangeListener {
22439        /**
22440         * Called when the focus state of a view has changed.
22441         *
22442         * @param v The view whose state has changed.
22443         * @param hasFocus The new focus state of v.
22444         */
22445        void onFocusChange(View v, boolean hasFocus);
22446    }
22447
22448    /**
22449     * Interface definition for a callback to be invoked when a view is clicked.
22450     */
22451    public interface OnClickListener {
22452        /**
22453         * Called when a view has been clicked.
22454         *
22455         * @param v The view that was clicked.
22456         */
22457        void onClick(View v);
22458    }
22459
22460    /**
22461     * Interface definition for a callback to be invoked when a view is context clicked.
22462     */
22463    public interface OnContextClickListener {
22464        /**
22465         * Called when a view is context clicked.
22466         *
22467         * @param v The view that has been context clicked.
22468         * @return true if the callback consumed the context click, false otherwise.
22469         */
22470        boolean onContextClick(View v);
22471    }
22472
22473    /**
22474     * Interface definition for a callback to be invoked when the context menu
22475     * for this view is being built.
22476     */
22477    public interface OnCreateContextMenuListener {
22478        /**
22479         * Called when the context menu for this view is being built. It is not
22480         * safe to hold onto the menu after this method returns.
22481         *
22482         * @param menu The context menu that is being built
22483         * @param v The view for which the context menu is being built
22484         * @param menuInfo Extra information about the item for which the
22485         *            context menu should be shown. This information will vary
22486         *            depending on the class of v.
22487         */
22488        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22489    }
22490
22491    /**
22492     * Interface definition for a callback to be invoked when the status bar changes
22493     * visibility.  This reports <strong>global</strong> changes to the system UI
22494     * state, not what the application is requesting.
22495     *
22496     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22497     */
22498    public interface OnSystemUiVisibilityChangeListener {
22499        /**
22500         * Called when the status bar changes visibility because of a call to
22501         * {@link View#setSystemUiVisibility(int)}.
22502         *
22503         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22504         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22505         * This tells you the <strong>global</strong> state of these UI visibility
22506         * flags, not what your app is currently applying.
22507         */
22508        public void onSystemUiVisibilityChange(int visibility);
22509    }
22510
22511    /**
22512     * Interface definition for a callback to be invoked when this view is attached
22513     * or detached from its window.
22514     */
22515    public interface OnAttachStateChangeListener {
22516        /**
22517         * Called when the view is attached to a window.
22518         * @param v The view that was attached
22519         */
22520        public void onViewAttachedToWindow(View v);
22521        /**
22522         * Called when the view is detached from a window.
22523         * @param v The view that was detached
22524         */
22525        public void onViewDetachedFromWindow(View v);
22526    }
22527
22528    /**
22529     * Listener for applying window insets on a view in a custom way.
22530     *
22531     * <p>Apps may choose to implement this interface if they want to apply custom policy
22532     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22533     * is set, its
22534     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22535     * method will be called instead of the View's own
22536     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22537     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22538     * the View's normal behavior as part of its own.</p>
22539     */
22540    public interface OnApplyWindowInsetsListener {
22541        /**
22542         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22543         * on a View, this listener method will be called instead of the view's own
22544         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22545         *
22546         * @param v The view applying window insets
22547         * @param insets The insets to apply
22548         * @return The insets supplied, minus any insets that were consumed
22549         */
22550        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22551    }
22552
22553    private final class UnsetPressedState implements Runnable {
22554        @Override
22555        public void run() {
22556            setPressed(false);
22557        }
22558    }
22559
22560    /**
22561     * Base class for derived classes that want to save and restore their own
22562     * state in {@link android.view.View#onSaveInstanceState()}.
22563     */
22564    public static class BaseSavedState extends AbsSavedState {
22565        String mStartActivityRequestWhoSaved;
22566
22567        /**
22568         * Constructor used when reading from a parcel. Reads the state of the superclass.
22569         *
22570         * @param source parcel to read from
22571         */
22572        public BaseSavedState(Parcel source) {
22573            this(source, null);
22574        }
22575
22576        /**
22577         * Constructor used when reading from a parcel using a given class loader.
22578         * Reads the state of the superclass.
22579         *
22580         * @param source parcel to read from
22581         * @param loader ClassLoader to use for reading
22582         */
22583        public BaseSavedState(Parcel source, ClassLoader loader) {
22584            super(source, loader);
22585            mStartActivityRequestWhoSaved = source.readString();
22586        }
22587
22588        /**
22589         * Constructor called by derived classes when creating their SavedState objects
22590         *
22591         * @param superState The state of the superclass of this view
22592         */
22593        public BaseSavedState(Parcelable superState) {
22594            super(superState);
22595        }
22596
22597        @Override
22598        public void writeToParcel(Parcel out, int flags) {
22599            super.writeToParcel(out, flags);
22600            out.writeString(mStartActivityRequestWhoSaved);
22601        }
22602
22603        public static final Parcelable.Creator<BaseSavedState> CREATOR
22604                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
22605            @Override
22606            public BaseSavedState createFromParcel(Parcel in) {
22607                return new BaseSavedState(in);
22608            }
22609
22610            @Override
22611            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
22612                return new BaseSavedState(in, loader);
22613            }
22614
22615            @Override
22616            public BaseSavedState[] newArray(int size) {
22617                return new BaseSavedState[size];
22618            }
22619        };
22620    }
22621
22622    /**
22623     * A set of information given to a view when it is attached to its parent
22624     * window.
22625     */
22626    final static class AttachInfo {
22627        interface Callbacks {
22628            void playSoundEffect(int effectId);
22629            boolean performHapticFeedback(int effectId, boolean always);
22630        }
22631
22632        /**
22633         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22634         * to a Handler. This class contains the target (View) to invalidate and
22635         * the coordinates of the dirty rectangle.
22636         *
22637         * For performance purposes, this class also implements a pool of up to
22638         * POOL_LIMIT objects that get reused. This reduces memory allocations
22639         * whenever possible.
22640         */
22641        static class InvalidateInfo {
22642            private static final int POOL_LIMIT = 10;
22643
22644            private static final SynchronizedPool<InvalidateInfo> sPool =
22645                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22646
22647            View target;
22648
22649            int left;
22650            int top;
22651            int right;
22652            int bottom;
22653
22654            public static InvalidateInfo obtain() {
22655                InvalidateInfo instance = sPool.acquire();
22656                return (instance != null) ? instance : new InvalidateInfo();
22657            }
22658
22659            public void recycle() {
22660                target = null;
22661                sPool.release(this);
22662            }
22663        }
22664
22665        final IWindowSession mSession;
22666
22667        final IWindow mWindow;
22668
22669        final IBinder mWindowToken;
22670
22671        final Display mDisplay;
22672
22673        final Callbacks mRootCallbacks;
22674
22675        IWindowId mIWindowId;
22676        WindowId mWindowId;
22677
22678        /**
22679         * The top view of the hierarchy.
22680         */
22681        View mRootView;
22682
22683        IBinder mPanelParentWindowToken;
22684
22685        boolean mHardwareAccelerated;
22686        boolean mHardwareAccelerationRequested;
22687        ThreadedRenderer mHardwareRenderer;
22688        List<RenderNode> mPendingAnimatingRenderNodes;
22689
22690        /**
22691         * The state of the display to which the window is attached, as reported
22692         * by {@link Display#getState()}.  Note that the display state constants
22693         * declared by {@link Display} do not exactly line up with the screen state
22694         * constants declared by {@link View} (there are more display states than
22695         * screen states).
22696         */
22697        int mDisplayState = Display.STATE_UNKNOWN;
22698
22699        /**
22700         * Scale factor used by the compatibility mode
22701         */
22702        float mApplicationScale;
22703
22704        /**
22705         * Indicates whether the application is in compatibility mode
22706         */
22707        boolean mScalingRequired;
22708
22709        /**
22710         * Left position of this view's window
22711         */
22712        int mWindowLeft;
22713
22714        /**
22715         * Top position of this view's window
22716         */
22717        int mWindowTop;
22718
22719        /**
22720         * Indicates whether views need to use 32-bit drawing caches
22721         */
22722        boolean mUse32BitDrawingCache;
22723
22724        /**
22725         * For windows that are full-screen but using insets to layout inside
22726         * of the screen areas, these are the current insets to appear inside
22727         * the overscan area of the display.
22728         */
22729        final Rect mOverscanInsets = new Rect();
22730
22731        /**
22732         * For windows that are full-screen but using insets to layout inside
22733         * of the screen decorations, these are the current insets for the
22734         * content of the window.
22735         */
22736        final Rect mContentInsets = new Rect();
22737
22738        /**
22739         * For windows that are full-screen but using insets to layout inside
22740         * of the screen decorations, these are the current insets for the
22741         * actual visible parts of the window.
22742         */
22743        final Rect mVisibleInsets = new Rect();
22744
22745        /**
22746         * For windows that are full-screen but using insets to layout inside
22747         * of the screen decorations, these are the current insets for the
22748         * stable system windows.
22749         */
22750        final Rect mStableInsets = new Rect();
22751
22752        /**
22753         * For windows that include areas that are not covered by real surface these are the outsets
22754         * for real surface.
22755         */
22756        final Rect mOutsets = new Rect();
22757
22758        /**
22759         * In multi-window we force show the navigation bar. Because we don't want that the surface
22760         * size changes in this mode, we instead have a flag whether the navigation bar size should
22761         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22762         */
22763        boolean mAlwaysConsumeNavBar;
22764
22765        /**
22766         * The internal insets given by this window.  This value is
22767         * supplied by the client (through
22768         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22769         * be given to the window manager when changed to be used in laying
22770         * out windows behind it.
22771         */
22772        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22773                = new ViewTreeObserver.InternalInsetsInfo();
22774
22775        /**
22776         * Set to true when mGivenInternalInsets is non-empty.
22777         */
22778        boolean mHasNonEmptyGivenInternalInsets;
22779
22780        /**
22781         * All views in the window's hierarchy that serve as scroll containers,
22782         * used to determine if the window can be resized or must be panned
22783         * to adjust for a soft input area.
22784         */
22785        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22786
22787        final KeyEvent.DispatcherState mKeyDispatchState
22788                = new KeyEvent.DispatcherState();
22789
22790        /**
22791         * Indicates whether the view's window currently has the focus.
22792         */
22793        boolean mHasWindowFocus;
22794
22795        /**
22796         * The current visibility of the window.
22797         */
22798        int mWindowVisibility;
22799
22800        /**
22801         * Indicates the time at which drawing started to occur.
22802         */
22803        long mDrawingTime;
22804
22805        /**
22806         * Indicates whether or not ignoring the DIRTY_MASK flags.
22807         */
22808        boolean mIgnoreDirtyState;
22809
22810        /**
22811         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22812         * to avoid clearing that flag prematurely.
22813         */
22814        boolean mSetIgnoreDirtyState = false;
22815
22816        /**
22817         * Indicates whether the view's window is currently in touch mode.
22818         */
22819        boolean mInTouchMode;
22820
22821        /**
22822         * Indicates whether the view has requested unbuffered input dispatching for the current
22823         * event stream.
22824         */
22825        boolean mUnbufferedDispatchRequested;
22826
22827        /**
22828         * Indicates that ViewAncestor should trigger a global layout change
22829         * the next time it performs a traversal
22830         */
22831        boolean mRecomputeGlobalAttributes;
22832
22833        /**
22834         * Always report new attributes at next traversal.
22835         */
22836        boolean mForceReportNewAttributes;
22837
22838        /**
22839         * Set during a traveral if any views want to keep the screen on.
22840         */
22841        boolean mKeepScreenOn;
22842
22843        /**
22844         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22845         */
22846        int mSystemUiVisibility;
22847
22848        /**
22849         * Hack to force certain system UI visibility flags to be cleared.
22850         */
22851        int mDisabledSystemUiVisibility;
22852
22853        /**
22854         * Last global system UI visibility reported by the window manager.
22855         */
22856        int mGlobalSystemUiVisibility;
22857
22858        /**
22859         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22860         * attached.
22861         */
22862        boolean mHasSystemUiListeners;
22863
22864        /**
22865         * Set if the window has requested to extend into the overscan region
22866         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22867         */
22868        boolean mOverscanRequested;
22869
22870        /**
22871         * Set if the visibility of any views has changed.
22872         */
22873        boolean mViewVisibilityChanged;
22874
22875        /**
22876         * Set to true if a view has been scrolled.
22877         */
22878        boolean mViewScrollChanged;
22879
22880        /**
22881         * Set to true if high contrast mode enabled
22882         */
22883        boolean mHighContrastText;
22884
22885        /**
22886         * Set to true if a pointer event is currently being handled.
22887         */
22888        boolean mHandlingPointerEvent;
22889
22890        /**
22891         * Global to the view hierarchy used as a temporary for dealing with
22892         * x/y points in the transparent region computations.
22893         */
22894        final int[] mTransparentLocation = new int[2];
22895
22896        /**
22897         * Global to the view hierarchy used as a temporary for dealing with
22898         * x/y points in the ViewGroup.invalidateChild implementation.
22899         */
22900        final int[] mInvalidateChildLocation = new int[2];
22901
22902        /**
22903         * Global to the view hierarchy used as a temporary for dealng with
22904         * computing absolute on-screen location.
22905         */
22906        final int[] mTmpLocation = new int[2];
22907
22908        /**
22909         * Global to the view hierarchy used as a temporary for dealing with
22910         * x/y location when view is transformed.
22911         */
22912        final float[] mTmpTransformLocation = new float[2];
22913
22914        /**
22915         * The view tree observer used to dispatch global events like
22916         * layout, pre-draw, touch mode change, etc.
22917         */
22918        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
22919
22920        /**
22921         * A Canvas used by the view hierarchy to perform bitmap caching.
22922         */
22923        Canvas mCanvas;
22924
22925        /**
22926         * The view root impl.
22927         */
22928        final ViewRootImpl mViewRootImpl;
22929
22930        /**
22931         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
22932         * handler can be used to pump events in the UI events queue.
22933         */
22934        final Handler mHandler;
22935
22936        /**
22937         * Temporary for use in computing invalidate rectangles while
22938         * calling up the hierarchy.
22939         */
22940        final Rect mTmpInvalRect = new Rect();
22941
22942        /**
22943         * Temporary for use in computing hit areas with transformed views
22944         */
22945        final RectF mTmpTransformRect = new RectF();
22946
22947        /**
22948         * Temporary for use in computing hit areas with transformed views
22949         */
22950        final RectF mTmpTransformRect1 = new RectF();
22951
22952        /**
22953         * Temporary list of rectanges.
22954         */
22955        final List<RectF> mTmpRectList = new ArrayList<>();
22956
22957        /**
22958         * Temporary for use in transforming invalidation rect
22959         */
22960        final Matrix mTmpMatrix = new Matrix();
22961
22962        /**
22963         * Temporary for use in transforming invalidation rect
22964         */
22965        final Transformation mTmpTransformation = new Transformation();
22966
22967        /**
22968         * Temporary for use in querying outlines from OutlineProviders
22969         */
22970        final Outline mTmpOutline = new Outline();
22971
22972        /**
22973         * Temporary list for use in collecting focusable descendents of a view.
22974         */
22975        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
22976
22977        /**
22978         * The id of the window for accessibility purposes.
22979         */
22980        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
22981
22982        /**
22983         * Flags related to accessibility processing.
22984         *
22985         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
22986         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
22987         */
22988        int mAccessibilityFetchFlags;
22989
22990        /**
22991         * The drawable for highlighting accessibility focus.
22992         */
22993        Drawable mAccessibilityFocusDrawable;
22994
22995        /**
22996         * Show where the margins, bounds and layout bounds are for each view.
22997         */
22998        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
22999
23000        /**
23001         * Point used to compute visible regions.
23002         */
23003        final Point mPoint = new Point();
23004
23005        /**
23006         * Used to track which View originated a requestLayout() call, used when
23007         * requestLayout() is called during layout.
23008         */
23009        View mViewRequestingLayout;
23010
23011        /**
23012         * Used to track views that need (at least) a partial relayout at their current size
23013         * during the next traversal.
23014         */
23015        List<View> mPartialLayoutViews = new ArrayList<>();
23016
23017        /**
23018         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23019         * modification. Lazily assigned during ViewRootImpl layout.
23020         */
23021        List<View> mEmptyPartialLayoutViews;
23022
23023        /**
23024         * Used to track the identity of the current drag operation.
23025         */
23026        IBinder mDragToken;
23027
23028        /**
23029         * The drag shadow surface for the current drag operation.
23030         */
23031        public Surface mDragSurface;
23032
23033        /**
23034         * Creates a new set of attachment information with the specified
23035         * events handler and thread.
23036         *
23037         * @param handler the events handler the view must use
23038         */
23039        AttachInfo(IWindowSession session, IWindow window, Display display,
23040                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
23041            mSession = session;
23042            mWindow = window;
23043            mWindowToken = window.asBinder();
23044            mDisplay = display;
23045            mViewRootImpl = viewRootImpl;
23046            mHandler = handler;
23047            mRootCallbacks = effectPlayer;
23048        }
23049    }
23050
23051    /**
23052     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23053     * is supported. This avoids keeping too many unused fields in most
23054     * instances of View.</p>
23055     */
23056    private static class ScrollabilityCache implements Runnable {
23057
23058        /**
23059         * Scrollbars are not visible
23060         */
23061        public static final int OFF = 0;
23062
23063        /**
23064         * Scrollbars are visible
23065         */
23066        public static final int ON = 1;
23067
23068        /**
23069         * Scrollbars are fading away
23070         */
23071        public static final int FADING = 2;
23072
23073        public boolean fadeScrollBars;
23074
23075        public int fadingEdgeLength;
23076        public int scrollBarDefaultDelayBeforeFade;
23077        public int scrollBarFadeDuration;
23078
23079        public int scrollBarSize;
23080        public ScrollBarDrawable scrollBar;
23081        public float[] interpolatorValues;
23082        public View host;
23083
23084        public final Paint paint;
23085        public final Matrix matrix;
23086        public Shader shader;
23087
23088        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23089
23090        private static final float[] OPAQUE = { 255 };
23091        private static final float[] TRANSPARENT = { 0.0f };
23092
23093        /**
23094         * When fading should start. This time moves into the future every time
23095         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23096         */
23097        public long fadeStartTime;
23098
23099
23100        /**
23101         * The current state of the scrollbars: ON, OFF, or FADING
23102         */
23103        public int state = OFF;
23104
23105        private int mLastColor;
23106
23107        public final Rect mScrollBarBounds = new Rect();
23108
23109        public static final int NOT_DRAGGING = 0;
23110        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23111        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23112        public int mScrollBarDraggingState = NOT_DRAGGING;
23113
23114        public float mScrollBarDraggingPos = 0;
23115
23116        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23117            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23118            scrollBarSize = configuration.getScaledScrollBarSize();
23119            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23120            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23121
23122            paint = new Paint();
23123            matrix = new Matrix();
23124            // use use a height of 1, and then wack the matrix each time we
23125            // actually use it.
23126            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23127            paint.setShader(shader);
23128            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23129
23130            this.host = host;
23131        }
23132
23133        public void setFadeColor(int color) {
23134            if (color != mLastColor) {
23135                mLastColor = color;
23136
23137                if (color != 0) {
23138                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23139                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23140                    paint.setShader(shader);
23141                    // Restore the default transfer mode (src_over)
23142                    paint.setXfermode(null);
23143                } else {
23144                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23145                    paint.setShader(shader);
23146                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23147                }
23148            }
23149        }
23150
23151        public void run() {
23152            long now = AnimationUtils.currentAnimationTimeMillis();
23153            if (now >= fadeStartTime) {
23154
23155                // the animation fades the scrollbars out by changing
23156                // the opacity (alpha) from fully opaque to fully
23157                // transparent
23158                int nextFrame = (int) now;
23159                int framesCount = 0;
23160
23161                Interpolator interpolator = scrollBarInterpolator;
23162
23163                // Start opaque
23164                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23165
23166                // End transparent
23167                nextFrame += scrollBarFadeDuration;
23168                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23169
23170                state = FADING;
23171
23172                // Kick off the fade animation
23173                host.invalidate(true);
23174            }
23175        }
23176    }
23177
23178    /**
23179     * Resuable callback for sending
23180     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23181     */
23182    private class SendViewScrolledAccessibilityEvent implements Runnable {
23183        public volatile boolean mIsPending;
23184
23185        public void run() {
23186            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23187            mIsPending = false;
23188        }
23189    }
23190
23191    /**
23192     * <p>
23193     * This class represents a delegate that can be registered in a {@link View}
23194     * to enhance accessibility support via composition rather via inheritance.
23195     * It is specifically targeted to widget developers that extend basic View
23196     * classes i.e. classes in package android.view, that would like their
23197     * applications to be backwards compatible.
23198     * </p>
23199     * <div class="special reference">
23200     * <h3>Developer Guides</h3>
23201     * <p>For more information about making applications accessible, read the
23202     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23203     * developer guide.</p>
23204     * </div>
23205     * <p>
23206     * A scenario in which a developer would like to use an accessibility delegate
23207     * is overriding a method introduced in a later API version then the minimal API
23208     * version supported by the application. For example, the method
23209     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23210     * in API version 4 when the accessibility APIs were first introduced. If a
23211     * developer would like his application to run on API version 4 devices (assuming
23212     * all other APIs used by the application are version 4 or lower) and take advantage
23213     * of this method, instead of overriding the method which would break the application's
23214     * backwards compatibility, he can override the corresponding method in this
23215     * delegate and register the delegate in the target View if the API version of
23216     * the system is high enough i.e. the API version is same or higher to the API
23217     * version that introduced
23218     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23219     * </p>
23220     * <p>
23221     * Here is an example implementation:
23222     * </p>
23223     * <code><pre><p>
23224     * if (Build.VERSION.SDK_INT >= 14) {
23225     *     // If the API version is equal of higher than the version in
23226     *     // which onInitializeAccessibilityNodeInfo was introduced we
23227     *     // register a delegate with a customized implementation.
23228     *     View view = findViewById(R.id.view_id);
23229     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23230     *         public void onInitializeAccessibilityNodeInfo(View host,
23231     *                 AccessibilityNodeInfo info) {
23232     *             // Let the default implementation populate the info.
23233     *             super.onInitializeAccessibilityNodeInfo(host, info);
23234     *             // Set some other information.
23235     *             info.setEnabled(host.isEnabled());
23236     *         }
23237     *     });
23238     * }
23239     * </code></pre></p>
23240     * <p>
23241     * This delegate contains methods that correspond to the accessibility methods
23242     * in View. If a delegate has been specified the implementation in View hands
23243     * off handling to the corresponding method in this delegate. The default
23244     * implementation the delegate methods behaves exactly as the corresponding
23245     * method in View for the case of no accessibility delegate been set. Hence,
23246     * to customize the behavior of a View method, clients can override only the
23247     * corresponding delegate method without altering the behavior of the rest
23248     * accessibility related methods of the host view.
23249     * </p>
23250     * <p>
23251     * <strong>Note:</strong> On platform versions prior to
23252     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23253     * views in the {@code android.widget.*} package are called <i>before</i>
23254     * host methods. This prevents certain properties such as class name from
23255     * being modified by overriding
23256     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23257     * as any changes will be overwritten by the host class.
23258     * <p>
23259     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23260     * methods are called <i>after</i> host methods, which all properties to be
23261     * modified without being overwritten by the host class.
23262     */
23263    public static class AccessibilityDelegate {
23264
23265        /**
23266         * Sends an accessibility event of the given type. If accessibility is not
23267         * enabled this method has no effect.
23268         * <p>
23269         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23270         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23271         * been set.
23272         * </p>
23273         *
23274         * @param host The View hosting the delegate.
23275         * @param eventType The type of the event to send.
23276         *
23277         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23278         */
23279        public void sendAccessibilityEvent(View host, int eventType) {
23280            host.sendAccessibilityEventInternal(eventType);
23281        }
23282
23283        /**
23284         * Performs the specified accessibility action on the view. For
23285         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23286         * <p>
23287         * The default implementation behaves as
23288         * {@link View#performAccessibilityAction(int, Bundle)
23289         *  View#performAccessibilityAction(int, Bundle)} for the case of
23290         *  no accessibility delegate been set.
23291         * </p>
23292         *
23293         * @param action The action to perform.
23294         * @return Whether the action was performed.
23295         *
23296         * @see View#performAccessibilityAction(int, Bundle)
23297         *      View#performAccessibilityAction(int, Bundle)
23298         */
23299        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23300            return host.performAccessibilityActionInternal(action, args);
23301        }
23302
23303        /**
23304         * Sends an accessibility event. This method behaves exactly as
23305         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23306         * empty {@link AccessibilityEvent} and does not perform a check whether
23307         * accessibility is enabled.
23308         * <p>
23309         * The default implementation behaves as
23310         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23311         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23312         * the case of no accessibility delegate been set.
23313         * </p>
23314         *
23315         * @param host The View hosting the delegate.
23316         * @param event The event to send.
23317         *
23318         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23319         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23320         */
23321        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23322            host.sendAccessibilityEventUncheckedInternal(event);
23323        }
23324
23325        /**
23326         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23327         * to its children for adding their text content to the event.
23328         * <p>
23329         * The default implementation behaves as
23330         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23331         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23332         * the case of no accessibility delegate been set.
23333         * </p>
23334         *
23335         * @param host The View hosting the delegate.
23336         * @param event The event.
23337         * @return True if the event population was completed.
23338         *
23339         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23340         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23341         */
23342        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23343            return host.dispatchPopulateAccessibilityEventInternal(event);
23344        }
23345
23346        /**
23347         * Gives a chance to the host View to populate the accessibility event with its
23348         * text content.
23349         * <p>
23350         * The default implementation behaves as
23351         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23352         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23353         * the case of no accessibility delegate been set.
23354         * </p>
23355         *
23356         * @param host The View hosting the delegate.
23357         * @param event The accessibility event which to populate.
23358         *
23359         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23360         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23361         */
23362        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23363            host.onPopulateAccessibilityEventInternal(event);
23364        }
23365
23366        /**
23367         * Initializes an {@link AccessibilityEvent} with information about the
23368         * the host View which is the event source.
23369         * <p>
23370         * The default implementation behaves as
23371         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23372         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23373         * the case of no accessibility delegate been set.
23374         * </p>
23375         *
23376         * @param host The View hosting the delegate.
23377         * @param event The event to initialize.
23378         *
23379         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23380         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23381         */
23382        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23383            host.onInitializeAccessibilityEventInternal(event);
23384        }
23385
23386        /**
23387         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23388         * <p>
23389         * The default implementation behaves as
23390         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23391         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23392         * the case of no accessibility delegate been set.
23393         * </p>
23394         *
23395         * @param host The View hosting the delegate.
23396         * @param info The instance to initialize.
23397         *
23398         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23399         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23400         */
23401        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23402            host.onInitializeAccessibilityNodeInfoInternal(info);
23403        }
23404
23405        /**
23406         * Called when a child of the host View has requested sending an
23407         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23408         * to augment the event.
23409         * <p>
23410         * The default implementation behaves as
23411         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23412         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23413         * the case of no accessibility delegate been set.
23414         * </p>
23415         *
23416         * @param host The View hosting the delegate.
23417         * @param child The child which requests sending the event.
23418         * @param event The event to be sent.
23419         * @return True if the event should be sent
23420         *
23421         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23422         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23423         */
23424        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23425                AccessibilityEvent event) {
23426            return host.onRequestSendAccessibilityEventInternal(child, event);
23427        }
23428
23429        /**
23430         * Gets the provider for managing a virtual view hierarchy rooted at this View
23431         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23432         * that explore the window content.
23433         * <p>
23434         * The default implementation behaves as
23435         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23436         * the case of no accessibility delegate been set.
23437         * </p>
23438         *
23439         * @return The provider.
23440         *
23441         * @see AccessibilityNodeProvider
23442         */
23443        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23444            return null;
23445        }
23446
23447        /**
23448         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23449         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23450         * This method is responsible for obtaining an accessibility node info from a
23451         * pool of reusable instances and calling
23452         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23453         * view to initialize the former.
23454         * <p>
23455         * <strong>Note:</strong> The client is responsible for recycling the obtained
23456         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23457         * creation.
23458         * </p>
23459         * <p>
23460         * The default implementation behaves as
23461         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23462         * the case of no accessibility delegate been set.
23463         * </p>
23464         * @return A populated {@link AccessibilityNodeInfo}.
23465         *
23466         * @see AccessibilityNodeInfo
23467         *
23468         * @hide
23469         */
23470        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23471            return host.createAccessibilityNodeInfoInternal();
23472        }
23473    }
23474
23475    private class MatchIdPredicate implements Predicate<View> {
23476        public int mId;
23477
23478        @Override
23479        public boolean apply(View view) {
23480            return (view.mID == mId);
23481        }
23482    }
23483
23484    private class MatchLabelForPredicate implements Predicate<View> {
23485        private int mLabeledId;
23486
23487        @Override
23488        public boolean apply(View view) {
23489            return (view.mLabelForId == mLabeledId);
23490        }
23491    }
23492
23493    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23494        private int mChangeTypes = 0;
23495        private boolean mPosted;
23496        private boolean mPostedWithDelay;
23497        private long mLastEventTimeMillis;
23498
23499        @Override
23500        public void run() {
23501            mPosted = false;
23502            mPostedWithDelay = false;
23503            mLastEventTimeMillis = SystemClock.uptimeMillis();
23504            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23505                final AccessibilityEvent event = AccessibilityEvent.obtain();
23506                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23507                event.setContentChangeTypes(mChangeTypes);
23508                sendAccessibilityEventUnchecked(event);
23509            }
23510            mChangeTypes = 0;
23511        }
23512
23513        public void runOrPost(int changeType) {
23514            mChangeTypes |= changeType;
23515
23516            // If this is a live region or the child of a live region, collect
23517            // all events from this frame and send them on the next frame.
23518            if (inLiveRegion()) {
23519                // If we're already posted with a delay, remove that.
23520                if (mPostedWithDelay) {
23521                    removeCallbacks(this);
23522                    mPostedWithDelay = false;
23523                }
23524                // Only post if we're not already posted.
23525                if (!mPosted) {
23526                    post(this);
23527                    mPosted = true;
23528                }
23529                return;
23530            }
23531
23532            if (mPosted) {
23533                return;
23534            }
23535
23536            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23537            final long minEventIntevalMillis =
23538                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23539            if (timeSinceLastMillis >= minEventIntevalMillis) {
23540                removeCallbacks(this);
23541                run();
23542            } else {
23543                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23544                mPostedWithDelay = true;
23545            }
23546        }
23547    }
23548
23549    private boolean inLiveRegion() {
23550        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23551            return true;
23552        }
23553
23554        ViewParent parent = getParent();
23555        while (parent instanceof View) {
23556            if (((View) parent).getAccessibilityLiveRegion()
23557                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23558                return true;
23559            }
23560            parent = parent.getParent();
23561        }
23562
23563        return false;
23564    }
23565
23566    /**
23567     * Dump all private flags in readable format, useful for documentation and
23568     * sanity checking.
23569     */
23570    private static void dumpFlags() {
23571        final HashMap<String, String> found = Maps.newHashMap();
23572        try {
23573            for (Field field : View.class.getDeclaredFields()) {
23574                final int modifiers = field.getModifiers();
23575                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23576                    if (field.getType().equals(int.class)) {
23577                        final int value = field.getInt(null);
23578                        dumpFlag(found, field.getName(), value);
23579                    } else if (field.getType().equals(int[].class)) {
23580                        final int[] values = (int[]) field.get(null);
23581                        for (int i = 0; i < values.length; i++) {
23582                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23583                        }
23584                    }
23585                }
23586            }
23587        } catch (IllegalAccessException e) {
23588            throw new RuntimeException(e);
23589        }
23590
23591        final ArrayList<String> keys = Lists.newArrayList();
23592        keys.addAll(found.keySet());
23593        Collections.sort(keys);
23594        for (String key : keys) {
23595            Log.d(VIEW_LOG_TAG, found.get(key));
23596        }
23597    }
23598
23599    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23600        // Sort flags by prefix, then by bits, always keeping unique keys
23601        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23602        final int prefix = name.indexOf('_');
23603        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23604        final String output = bits + " " + name;
23605        found.put(key, output);
23606    }
23607
23608    /** {@hide} */
23609    public void encode(@NonNull ViewHierarchyEncoder stream) {
23610        stream.beginObject(this);
23611        encodeProperties(stream);
23612        stream.endObject();
23613    }
23614
23615    /** {@hide} */
23616    @CallSuper
23617    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23618        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23619        if (resolveId instanceof String) {
23620            stream.addProperty("id", (String) resolveId);
23621        } else {
23622            stream.addProperty("id", mID);
23623        }
23624
23625        stream.addProperty("misc:transformation.alpha",
23626                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23627        stream.addProperty("misc:transitionName", getTransitionName());
23628
23629        // layout
23630        stream.addProperty("layout:left", mLeft);
23631        stream.addProperty("layout:right", mRight);
23632        stream.addProperty("layout:top", mTop);
23633        stream.addProperty("layout:bottom", mBottom);
23634        stream.addProperty("layout:width", getWidth());
23635        stream.addProperty("layout:height", getHeight());
23636        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23637        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23638        stream.addProperty("layout:hasTransientState", hasTransientState());
23639        stream.addProperty("layout:baseline", getBaseline());
23640
23641        // layout params
23642        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23643        if (layoutParams != null) {
23644            stream.addPropertyKey("layoutParams");
23645            layoutParams.encode(stream);
23646        }
23647
23648        // scrolling
23649        stream.addProperty("scrolling:scrollX", mScrollX);
23650        stream.addProperty("scrolling:scrollY", mScrollY);
23651
23652        // padding
23653        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23654        stream.addProperty("padding:paddingRight", mPaddingRight);
23655        stream.addProperty("padding:paddingTop", mPaddingTop);
23656        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23657        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23658        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23659        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23660        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23661        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23662
23663        // measurement
23664        stream.addProperty("measurement:minHeight", mMinHeight);
23665        stream.addProperty("measurement:minWidth", mMinWidth);
23666        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23667        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23668
23669        // drawing
23670        stream.addProperty("drawing:elevation", getElevation());
23671        stream.addProperty("drawing:translationX", getTranslationX());
23672        stream.addProperty("drawing:translationY", getTranslationY());
23673        stream.addProperty("drawing:translationZ", getTranslationZ());
23674        stream.addProperty("drawing:rotation", getRotation());
23675        stream.addProperty("drawing:rotationX", getRotationX());
23676        stream.addProperty("drawing:rotationY", getRotationY());
23677        stream.addProperty("drawing:scaleX", getScaleX());
23678        stream.addProperty("drawing:scaleY", getScaleY());
23679        stream.addProperty("drawing:pivotX", getPivotX());
23680        stream.addProperty("drawing:pivotY", getPivotY());
23681        stream.addProperty("drawing:opaque", isOpaque());
23682        stream.addProperty("drawing:alpha", getAlpha());
23683        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23684        stream.addProperty("drawing:shadow", hasShadow());
23685        stream.addProperty("drawing:solidColor", getSolidColor());
23686        stream.addProperty("drawing:layerType", mLayerType);
23687        stream.addProperty("drawing:willNotDraw", willNotDraw());
23688        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23689        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23690        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23691        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23692
23693        // focus
23694        stream.addProperty("focus:hasFocus", hasFocus());
23695        stream.addProperty("focus:isFocused", isFocused());
23696        stream.addProperty("focus:isFocusable", isFocusable());
23697        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23698
23699        stream.addProperty("misc:clickable", isClickable());
23700        stream.addProperty("misc:pressed", isPressed());
23701        stream.addProperty("misc:selected", isSelected());
23702        stream.addProperty("misc:touchMode", isInTouchMode());
23703        stream.addProperty("misc:hovered", isHovered());
23704        stream.addProperty("misc:activated", isActivated());
23705
23706        stream.addProperty("misc:visibility", getVisibility());
23707        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23708        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23709
23710        stream.addProperty("misc:enabled", isEnabled());
23711        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23712        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23713
23714        // theme attributes
23715        Resources.Theme theme = getContext().getTheme();
23716        if (theme != null) {
23717            stream.addPropertyKey("theme");
23718            theme.encode(stream);
23719        }
23720
23721        // view attribute information
23722        int n = mAttributes != null ? mAttributes.length : 0;
23723        stream.addProperty("meta:__attrCount__", n/2);
23724        for (int i = 0; i < n; i += 2) {
23725            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23726        }
23727
23728        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23729
23730        // text
23731        stream.addProperty("text:textDirection", getTextDirection());
23732        stream.addProperty("text:textAlignment", getTextAlignment());
23733
23734        // accessibility
23735        CharSequence contentDescription = getContentDescription();
23736        stream.addProperty("accessibility:contentDescription",
23737                contentDescription == null ? "" : contentDescription.toString());
23738        stream.addProperty("accessibility:labelFor", getLabelFor());
23739        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23740    }
23741}
23742