View.java revision f96d962aac31b0cf7d58fee384c3c9ca16eb5980
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.TYPE_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 with targetSdkVersion >=
3748     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3749     * in the drag operation and receive the dragged content.
3750     *
3751     * If this is the only flag set, then the drag recipient will only have access to text data
3752     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3753     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags.
3754     */
3755    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3756
3757    /**
3758     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3759     * request read access to the content URI(s) contained in the {@link ClipData} object.
3760     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3761     */
3762    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3763
3764    /**
3765     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3766     * request write access to the content URI(s) contained in the {@link ClipData} object.
3767     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3768     */
3769    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3770
3771    /**
3772     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3773     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3774     * reboots until explicitly revoked with
3775     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3776     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3777     */
3778    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3779            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3780
3781    /**
3782     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3783     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3784     * match against the original granted URI.
3785     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3786     */
3787    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3788            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3789
3790    /**
3791     * Flag indicating that the drag shadow will be opaque.  When
3792     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3793     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3794     */
3795    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3796
3797    /**
3798     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3799     */
3800    private float mVerticalScrollFactor;
3801
3802    /**
3803     * Position of the vertical scroll bar.
3804     */
3805    private int mVerticalScrollbarPosition;
3806
3807    /**
3808     * Position the scroll bar at the default position as determined by the system.
3809     */
3810    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3811
3812    /**
3813     * Position the scroll bar along the left edge.
3814     */
3815    public static final int SCROLLBAR_POSITION_LEFT = 1;
3816
3817    /**
3818     * Position the scroll bar along the right edge.
3819     */
3820    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3821
3822    /**
3823     * Indicates that the view does not have a layer.
3824     *
3825     * @see #getLayerType()
3826     * @see #setLayerType(int, android.graphics.Paint)
3827     * @see #LAYER_TYPE_SOFTWARE
3828     * @see #LAYER_TYPE_HARDWARE
3829     */
3830    public static final int LAYER_TYPE_NONE = 0;
3831
3832    /**
3833     * <p>Indicates that the view has a software layer. A software layer is backed
3834     * by a bitmap and causes the view to be rendered using Android's software
3835     * rendering pipeline, even if hardware acceleration is enabled.</p>
3836     *
3837     * <p>Software layers have various usages:</p>
3838     * <p>When the application is not using hardware acceleration, a software layer
3839     * is useful to apply a specific color filter and/or blending mode and/or
3840     * translucency to a view and all its children.</p>
3841     * <p>When the application is using hardware acceleration, a software layer
3842     * is useful to render drawing primitives not supported by the hardware
3843     * accelerated pipeline. It can also be used to cache a complex view tree
3844     * into a texture and reduce the complexity of drawing operations. For instance,
3845     * when animating a complex view tree with a translation, a software layer can
3846     * be used to render the view tree only once.</p>
3847     * <p>Software layers should be avoided when the affected view tree updates
3848     * often. Every update will require to re-render the software layer, which can
3849     * potentially be slow (particularly when hardware acceleration is turned on
3850     * since the layer will have to be uploaded into a hardware texture after every
3851     * update.)</p>
3852     *
3853     * @see #getLayerType()
3854     * @see #setLayerType(int, android.graphics.Paint)
3855     * @see #LAYER_TYPE_NONE
3856     * @see #LAYER_TYPE_HARDWARE
3857     */
3858    public static final int LAYER_TYPE_SOFTWARE = 1;
3859
3860    /**
3861     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3862     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3863     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3864     * rendering pipeline, but only if hardware acceleration is turned on for the
3865     * view hierarchy. When hardware acceleration is turned off, hardware layers
3866     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3867     *
3868     * <p>A hardware layer is useful to apply a specific color filter and/or
3869     * blending mode and/or translucency to a view and all its children.</p>
3870     * <p>A hardware layer can be used to cache a complex view tree into a
3871     * texture and reduce the complexity of drawing operations. For instance,
3872     * when animating a complex view tree with a translation, a hardware layer can
3873     * be used to render the view tree only once.</p>
3874     * <p>A hardware layer can also be used to increase the rendering quality when
3875     * rotation transformations are applied on a view. It can also be used to
3876     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3877     *
3878     * @see #getLayerType()
3879     * @see #setLayerType(int, android.graphics.Paint)
3880     * @see #LAYER_TYPE_NONE
3881     * @see #LAYER_TYPE_SOFTWARE
3882     */
3883    public static final int LAYER_TYPE_HARDWARE = 2;
3884
3885    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3886            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3887            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3888            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3889    })
3890    int mLayerType = LAYER_TYPE_NONE;
3891    Paint mLayerPaint;
3892
3893    /**
3894     * Set to true when drawing cache is enabled and cannot be created.
3895     *
3896     * @hide
3897     */
3898    public boolean mCachingFailed;
3899    private Bitmap mDrawingCache;
3900    private Bitmap mUnscaledDrawingCache;
3901
3902    /**
3903     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3904     * <p>
3905     * When non-null and valid, this is expected to contain an up-to-date copy
3906     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3907     * cleanup.
3908     */
3909    final RenderNode mRenderNode;
3910
3911    /**
3912     * Set to true when the view is sending hover accessibility events because it
3913     * is the innermost hovered view.
3914     */
3915    private boolean mSendingHoverAccessibilityEvents;
3916
3917    /**
3918     * Delegate for injecting accessibility functionality.
3919     */
3920    AccessibilityDelegate mAccessibilityDelegate;
3921
3922    /**
3923     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3924     * and add/remove objects to/from the overlay directly through the Overlay methods.
3925     */
3926    ViewOverlay mOverlay;
3927
3928    /**
3929     * The currently active parent view for receiving delegated nested scrolling events.
3930     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3931     * by {@link #stopNestedScroll()} at the same point where we clear
3932     * requestDisallowInterceptTouchEvent.
3933     */
3934    private ViewParent mNestedScrollingParent;
3935
3936    /**
3937     * Consistency verifier for debugging purposes.
3938     * @hide
3939     */
3940    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3941            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3942                    new InputEventConsistencyVerifier(this, 0) : null;
3943
3944    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3945
3946    private int[] mTempNestedScrollConsumed;
3947
3948    /**
3949     * An overlay is going to draw this View instead of being drawn as part of this
3950     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3951     * when this view is invalidated.
3952     */
3953    GhostView mGhostView;
3954
3955    /**
3956     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3957     * @hide
3958     */
3959    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3960    public String[] mAttributes;
3961
3962    /**
3963     * Maps a Resource id to its name.
3964     */
3965    private static SparseArray<String> mAttributeMap;
3966
3967    /**
3968     * Queue of pending runnables. Used to postpone calls to post() until this
3969     * view is attached and has a handler.
3970     */
3971    private HandlerActionQueue mRunQueue;
3972
3973    /**
3974     * The pointer icon when the mouse hovers on this view. The default is null.
3975     */
3976    private PointerIcon mPointerIcon;
3977
3978    /**
3979     * @hide
3980     */
3981    String mStartActivityRequestWho;
3982
3983    /**
3984     * Simple constructor to use when creating a view from code.
3985     *
3986     * @param context The Context the view is running in, through which it can
3987     *        access the current theme, resources, etc.
3988     */
3989    public View(Context context) {
3990        mContext = context;
3991        mResources = context != null ? context.getResources() : null;
3992        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3993        // Set some flags defaults
3994        mPrivateFlags2 =
3995                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3996                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3997                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3998                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3999                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4000                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4001        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4002        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4003        mUserPaddingStart = UNDEFINED_PADDING;
4004        mUserPaddingEnd = UNDEFINED_PADDING;
4005        mRenderNode = RenderNode.create(getClass().getName(), this);
4006
4007        if (!sCompatibilityDone && context != null) {
4008            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4009
4010            // Older apps may need this compatibility hack for measurement.
4011            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4012
4013            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4014            // of whether a layout was requested on that View.
4015            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4016
4017            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4018
4019            // In M and newer, our widgets can pass a "hint" value in the size
4020            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4021            // know what the expected parent size is going to be, so e.g. list items can size
4022            // themselves at 1/3 the size of their container. It breaks older apps though,
4023            // specifically apps that use some popular open source libraries.
4024            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4025
4026            // Old versions of the platform would give different results from
4027            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4028            // modes, so we always need to run an additional EXACTLY pass.
4029            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4030
4031            // Prior to N, layout params could change without requiring a
4032            // subsequent call to setLayoutParams() and they would usually
4033            // work. Partial layout breaks this assumption.
4034            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4035
4036            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4037            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4038            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4039
4040            sCompatibilityDone = true;
4041        }
4042    }
4043
4044    /**
4045     * Constructor that is called when inflating a view from XML. This is called
4046     * when a view is being constructed from an XML file, supplying attributes
4047     * that were specified in the XML file. This version uses a default style of
4048     * 0, so the only attribute values applied are those in the Context's Theme
4049     * and the given AttributeSet.
4050     *
4051     * <p>
4052     * The method onFinishInflate() will be called after all children have been
4053     * added.
4054     *
4055     * @param context The Context the view is running in, through which it can
4056     *        access the current theme, resources, etc.
4057     * @param attrs The attributes of the XML tag that is inflating the view.
4058     * @see #View(Context, AttributeSet, int)
4059     */
4060    public View(Context context, @Nullable AttributeSet attrs) {
4061        this(context, attrs, 0);
4062    }
4063
4064    /**
4065     * Perform inflation from XML and apply a class-specific base style from a
4066     * theme attribute. This constructor of View allows subclasses to use their
4067     * own base style when they are inflating. For example, a Button class's
4068     * constructor would call this version of the super class constructor and
4069     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4070     * allows the theme's button style to modify all of the base view attributes
4071     * (in particular its background) as well as the Button class's attributes.
4072     *
4073     * @param context The Context the view is running in, through which it can
4074     *        access the current theme, resources, etc.
4075     * @param attrs The attributes of the XML tag that is inflating the view.
4076     * @param defStyleAttr An attribute in the current theme that contains a
4077     *        reference to a style resource that supplies default values for
4078     *        the view. Can be 0 to not look for defaults.
4079     * @see #View(Context, AttributeSet)
4080     */
4081    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4082        this(context, attrs, defStyleAttr, 0);
4083    }
4084
4085    /**
4086     * Perform inflation from XML and apply a class-specific base style from a
4087     * theme attribute or style resource. This constructor of View allows
4088     * subclasses to use their own base style when they are inflating.
4089     * <p>
4090     * When determining the final value of a particular attribute, there are
4091     * four inputs that come into play:
4092     * <ol>
4093     * <li>Any attribute values in the given AttributeSet.
4094     * <li>The style resource specified in the AttributeSet (named "style").
4095     * <li>The default style specified by <var>defStyleAttr</var>.
4096     * <li>The default style specified by <var>defStyleRes</var>.
4097     * <li>The base values in this theme.
4098     * </ol>
4099     * <p>
4100     * Each of these inputs is considered in-order, with the first listed taking
4101     * precedence over the following ones. In other words, if in the
4102     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4103     * , then the button's text will <em>always</em> be black, regardless of
4104     * what is specified in any of the styles.
4105     *
4106     * @param context The Context the view is running in, through which it can
4107     *        access the current theme, resources, etc.
4108     * @param attrs The attributes of the XML tag that is inflating the view.
4109     * @param defStyleAttr An attribute in the current theme that contains a
4110     *        reference to a style resource that supplies default values for
4111     *        the view. Can be 0 to not look for defaults.
4112     * @param defStyleRes A resource identifier of a style resource that
4113     *        supplies default values for the view, used only if
4114     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4115     *        to not look for defaults.
4116     * @see #View(Context, AttributeSet, int)
4117     */
4118    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4119        this(context);
4120
4121        final TypedArray a = context.obtainStyledAttributes(
4122                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4123
4124        if (mDebugViewAttributes) {
4125            saveAttributeData(attrs, a);
4126        }
4127
4128        Drawable background = null;
4129
4130        int leftPadding = -1;
4131        int topPadding = -1;
4132        int rightPadding = -1;
4133        int bottomPadding = -1;
4134        int startPadding = UNDEFINED_PADDING;
4135        int endPadding = UNDEFINED_PADDING;
4136
4137        int padding = -1;
4138
4139        int viewFlagValues = 0;
4140        int viewFlagMasks = 0;
4141
4142        boolean setScrollContainer = false;
4143
4144        int x = 0;
4145        int y = 0;
4146
4147        float tx = 0;
4148        float ty = 0;
4149        float tz = 0;
4150        float elevation = 0;
4151        float rotation = 0;
4152        float rotationX = 0;
4153        float rotationY = 0;
4154        float sx = 1f;
4155        float sy = 1f;
4156        boolean transformSet = false;
4157
4158        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4159        int overScrollMode = mOverScrollMode;
4160        boolean initializeScrollbars = false;
4161        boolean initializeScrollIndicators = false;
4162
4163        boolean startPaddingDefined = false;
4164        boolean endPaddingDefined = false;
4165        boolean leftPaddingDefined = false;
4166        boolean rightPaddingDefined = false;
4167
4168        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4169
4170        final int N = a.getIndexCount();
4171        for (int i = 0; i < N; i++) {
4172            int attr = a.getIndex(i);
4173            switch (attr) {
4174                case com.android.internal.R.styleable.View_background:
4175                    background = a.getDrawable(attr);
4176                    break;
4177                case com.android.internal.R.styleable.View_padding:
4178                    padding = a.getDimensionPixelSize(attr, -1);
4179                    mUserPaddingLeftInitial = padding;
4180                    mUserPaddingRightInitial = padding;
4181                    leftPaddingDefined = true;
4182                    rightPaddingDefined = true;
4183                    break;
4184                 case com.android.internal.R.styleable.View_paddingLeft:
4185                    leftPadding = a.getDimensionPixelSize(attr, -1);
4186                    mUserPaddingLeftInitial = leftPadding;
4187                    leftPaddingDefined = true;
4188                    break;
4189                case com.android.internal.R.styleable.View_paddingTop:
4190                    topPadding = a.getDimensionPixelSize(attr, -1);
4191                    break;
4192                case com.android.internal.R.styleable.View_paddingRight:
4193                    rightPadding = a.getDimensionPixelSize(attr, -1);
4194                    mUserPaddingRightInitial = rightPadding;
4195                    rightPaddingDefined = true;
4196                    break;
4197                case com.android.internal.R.styleable.View_paddingBottom:
4198                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4199                    break;
4200                case com.android.internal.R.styleable.View_paddingStart:
4201                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4202                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4203                    break;
4204                case com.android.internal.R.styleable.View_paddingEnd:
4205                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4206                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4207                    break;
4208                case com.android.internal.R.styleable.View_scrollX:
4209                    x = a.getDimensionPixelOffset(attr, 0);
4210                    break;
4211                case com.android.internal.R.styleable.View_scrollY:
4212                    y = a.getDimensionPixelOffset(attr, 0);
4213                    break;
4214                case com.android.internal.R.styleable.View_alpha:
4215                    setAlpha(a.getFloat(attr, 1f));
4216                    break;
4217                case com.android.internal.R.styleable.View_transformPivotX:
4218                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4219                    break;
4220                case com.android.internal.R.styleable.View_transformPivotY:
4221                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4222                    break;
4223                case com.android.internal.R.styleable.View_translationX:
4224                    tx = a.getDimensionPixelOffset(attr, 0);
4225                    transformSet = true;
4226                    break;
4227                case com.android.internal.R.styleable.View_translationY:
4228                    ty = a.getDimensionPixelOffset(attr, 0);
4229                    transformSet = true;
4230                    break;
4231                case com.android.internal.R.styleable.View_translationZ:
4232                    tz = a.getDimensionPixelOffset(attr, 0);
4233                    transformSet = true;
4234                    break;
4235                case com.android.internal.R.styleable.View_elevation:
4236                    elevation = a.getDimensionPixelOffset(attr, 0);
4237                    transformSet = true;
4238                    break;
4239                case com.android.internal.R.styleable.View_rotation:
4240                    rotation = a.getFloat(attr, 0);
4241                    transformSet = true;
4242                    break;
4243                case com.android.internal.R.styleable.View_rotationX:
4244                    rotationX = a.getFloat(attr, 0);
4245                    transformSet = true;
4246                    break;
4247                case com.android.internal.R.styleable.View_rotationY:
4248                    rotationY = a.getFloat(attr, 0);
4249                    transformSet = true;
4250                    break;
4251                case com.android.internal.R.styleable.View_scaleX:
4252                    sx = a.getFloat(attr, 1f);
4253                    transformSet = true;
4254                    break;
4255                case com.android.internal.R.styleable.View_scaleY:
4256                    sy = a.getFloat(attr, 1f);
4257                    transformSet = true;
4258                    break;
4259                case com.android.internal.R.styleable.View_id:
4260                    mID = a.getResourceId(attr, NO_ID);
4261                    break;
4262                case com.android.internal.R.styleable.View_tag:
4263                    mTag = a.getText(attr);
4264                    break;
4265                case com.android.internal.R.styleable.View_fitsSystemWindows:
4266                    if (a.getBoolean(attr, false)) {
4267                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4268                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4269                    }
4270                    break;
4271                case com.android.internal.R.styleable.View_focusable:
4272                    if (a.getBoolean(attr, false)) {
4273                        viewFlagValues |= FOCUSABLE;
4274                        viewFlagMasks |= FOCUSABLE_MASK;
4275                    }
4276                    break;
4277                case com.android.internal.R.styleable.View_focusableInTouchMode:
4278                    if (a.getBoolean(attr, false)) {
4279                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4280                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4281                    }
4282                    break;
4283                case com.android.internal.R.styleable.View_clickable:
4284                    if (a.getBoolean(attr, false)) {
4285                        viewFlagValues |= CLICKABLE;
4286                        viewFlagMasks |= CLICKABLE;
4287                    }
4288                    break;
4289                case com.android.internal.R.styleable.View_longClickable:
4290                    if (a.getBoolean(attr, false)) {
4291                        viewFlagValues |= LONG_CLICKABLE;
4292                        viewFlagMasks |= LONG_CLICKABLE;
4293                    }
4294                    break;
4295                case com.android.internal.R.styleable.View_contextClickable:
4296                    if (a.getBoolean(attr, false)) {
4297                        viewFlagValues |= CONTEXT_CLICKABLE;
4298                        viewFlagMasks |= CONTEXT_CLICKABLE;
4299                    }
4300                    break;
4301                case com.android.internal.R.styleable.View_saveEnabled:
4302                    if (!a.getBoolean(attr, true)) {
4303                        viewFlagValues |= SAVE_DISABLED;
4304                        viewFlagMasks |= SAVE_DISABLED_MASK;
4305                    }
4306                    break;
4307                case com.android.internal.R.styleable.View_duplicateParentState:
4308                    if (a.getBoolean(attr, false)) {
4309                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4310                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4311                    }
4312                    break;
4313                case com.android.internal.R.styleable.View_visibility:
4314                    final int visibility = a.getInt(attr, 0);
4315                    if (visibility != 0) {
4316                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4317                        viewFlagMasks |= VISIBILITY_MASK;
4318                    }
4319                    break;
4320                case com.android.internal.R.styleable.View_layoutDirection:
4321                    // Clear any layout direction flags (included resolved bits) already set
4322                    mPrivateFlags2 &=
4323                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4324                    // Set the layout direction flags depending on the value of the attribute
4325                    final int layoutDirection = a.getInt(attr, -1);
4326                    final int value = (layoutDirection != -1) ?
4327                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4328                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4329                    break;
4330                case com.android.internal.R.styleable.View_drawingCacheQuality:
4331                    final int cacheQuality = a.getInt(attr, 0);
4332                    if (cacheQuality != 0) {
4333                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4334                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4335                    }
4336                    break;
4337                case com.android.internal.R.styleable.View_contentDescription:
4338                    setContentDescription(a.getString(attr));
4339                    break;
4340                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4341                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4342                    break;
4343                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4344                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4345                    break;
4346                case com.android.internal.R.styleable.View_labelFor:
4347                    setLabelFor(a.getResourceId(attr, NO_ID));
4348                    break;
4349                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4350                    if (!a.getBoolean(attr, true)) {
4351                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4352                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4353                    }
4354                    break;
4355                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4356                    if (!a.getBoolean(attr, true)) {
4357                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4358                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4359                    }
4360                    break;
4361                case R.styleable.View_scrollbars:
4362                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4363                    if (scrollbars != SCROLLBARS_NONE) {
4364                        viewFlagValues |= scrollbars;
4365                        viewFlagMasks |= SCROLLBARS_MASK;
4366                        initializeScrollbars = true;
4367                    }
4368                    break;
4369                //noinspection deprecation
4370                case R.styleable.View_fadingEdge:
4371                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4372                        // Ignore the attribute starting with ICS
4373                        break;
4374                    }
4375                    // With builds < ICS, fall through and apply fading edges
4376                case R.styleable.View_requiresFadingEdge:
4377                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4378                    if (fadingEdge != FADING_EDGE_NONE) {
4379                        viewFlagValues |= fadingEdge;
4380                        viewFlagMasks |= FADING_EDGE_MASK;
4381                        initializeFadingEdgeInternal(a);
4382                    }
4383                    break;
4384                case R.styleable.View_scrollbarStyle:
4385                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4386                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4387                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4388                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4389                    }
4390                    break;
4391                case R.styleable.View_isScrollContainer:
4392                    setScrollContainer = true;
4393                    if (a.getBoolean(attr, false)) {
4394                        setScrollContainer(true);
4395                    }
4396                    break;
4397                case com.android.internal.R.styleable.View_keepScreenOn:
4398                    if (a.getBoolean(attr, false)) {
4399                        viewFlagValues |= KEEP_SCREEN_ON;
4400                        viewFlagMasks |= KEEP_SCREEN_ON;
4401                    }
4402                    break;
4403                case R.styleable.View_filterTouchesWhenObscured:
4404                    if (a.getBoolean(attr, false)) {
4405                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4406                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4407                    }
4408                    break;
4409                case R.styleable.View_nextFocusLeft:
4410                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4411                    break;
4412                case R.styleable.View_nextFocusRight:
4413                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4414                    break;
4415                case R.styleable.View_nextFocusUp:
4416                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4417                    break;
4418                case R.styleable.View_nextFocusDown:
4419                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4420                    break;
4421                case R.styleable.View_nextFocusForward:
4422                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4423                    break;
4424                case R.styleable.View_minWidth:
4425                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4426                    break;
4427                case R.styleable.View_minHeight:
4428                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4429                    break;
4430                case R.styleable.View_onClick:
4431                    if (context.isRestricted()) {
4432                        throw new IllegalStateException("The android:onClick attribute cannot "
4433                                + "be used within a restricted context");
4434                    }
4435
4436                    final String handlerName = a.getString(attr);
4437                    if (handlerName != null) {
4438                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4439                    }
4440                    break;
4441                case R.styleable.View_overScrollMode:
4442                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4443                    break;
4444                case R.styleable.View_verticalScrollbarPosition:
4445                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4446                    break;
4447                case R.styleable.View_layerType:
4448                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4449                    break;
4450                case R.styleable.View_textDirection:
4451                    // Clear any text direction flag already set
4452                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4453                    // Set the text direction flags depending on the value of the attribute
4454                    final int textDirection = a.getInt(attr, -1);
4455                    if (textDirection != -1) {
4456                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4457                    }
4458                    break;
4459                case R.styleable.View_textAlignment:
4460                    // Clear any text alignment flag already set
4461                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4462                    // Set the text alignment flag depending on the value of the attribute
4463                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4464                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4465                    break;
4466                case R.styleable.View_importantForAccessibility:
4467                    setImportantForAccessibility(a.getInt(attr,
4468                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4469                    break;
4470                case R.styleable.View_accessibilityLiveRegion:
4471                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4472                    break;
4473                case R.styleable.View_transitionName:
4474                    setTransitionName(a.getString(attr));
4475                    break;
4476                case R.styleable.View_nestedScrollingEnabled:
4477                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4478                    break;
4479                case R.styleable.View_stateListAnimator:
4480                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4481                            a.getResourceId(attr, 0)));
4482                    break;
4483                case R.styleable.View_backgroundTint:
4484                    // This will get applied later during setBackground().
4485                    if (mBackgroundTint == null) {
4486                        mBackgroundTint = new TintInfo();
4487                    }
4488                    mBackgroundTint.mTintList = a.getColorStateList(
4489                            R.styleable.View_backgroundTint);
4490                    mBackgroundTint.mHasTintList = true;
4491                    break;
4492                case R.styleable.View_backgroundTintMode:
4493                    // This will get applied later during setBackground().
4494                    if (mBackgroundTint == null) {
4495                        mBackgroundTint = new TintInfo();
4496                    }
4497                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4498                            R.styleable.View_backgroundTintMode, -1), null);
4499                    mBackgroundTint.mHasTintMode = true;
4500                    break;
4501                case R.styleable.View_outlineProvider:
4502                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4503                            PROVIDER_BACKGROUND));
4504                    break;
4505                case R.styleable.View_foreground:
4506                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4507                        setForeground(a.getDrawable(attr));
4508                    }
4509                    break;
4510                case R.styleable.View_foregroundGravity:
4511                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4512                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4513                    }
4514                    break;
4515                case R.styleable.View_foregroundTintMode:
4516                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4517                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4518                    }
4519                    break;
4520                case R.styleable.View_foregroundTint:
4521                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4522                        setForegroundTintList(a.getColorStateList(attr));
4523                    }
4524                    break;
4525                case R.styleable.View_foregroundInsidePadding:
4526                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4527                        if (mForegroundInfo == null) {
4528                            mForegroundInfo = new ForegroundInfo();
4529                        }
4530                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4531                                mForegroundInfo.mInsidePadding);
4532                    }
4533                    break;
4534                case R.styleable.View_scrollIndicators:
4535                    final int scrollIndicators =
4536                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4537                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4538                    if (scrollIndicators != 0) {
4539                        mPrivateFlags3 |= scrollIndicators;
4540                        initializeScrollIndicators = true;
4541                    }
4542                    break;
4543                case R.styleable.View_pointerIcon:
4544                    final int resourceId = a.getResourceId(attr, 0);
4545                    if (resourceId != 0) {
4546                        setPointerIcon(PointerIcon.load(
4547                                context.getResources(), resourceId));
4548                    } else {
4549                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4550                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4551                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4552                        }
4553                    }
4554                    break;
4555                case R.styleable.View_forceHasOverlappingRendering:
4556                    if (a.peekValue(attr) != null) {
4557                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4558                    }
4559                    break;
4560
4561            }
4562        }
4563
4564        setOverScrollMode(overScrollMode);
4565
4566        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4567        // the resolved layout direction). Those cached values will be used later during padding
4568        // resolution.
4569        mUserPaddingStart = startPadding;
4570        mUserPaddingEnd = endPadding;
4571
4572        if (background != null) {
4573            setBackground(background);
4574        }
4575
4576        // setBackground above will record that padding is currently provided by the background.
4577        // If we have padding specified via xml, record that here instead and use it.
4578        mLeftPaddingDefined = leftPaddingDefined;
4579        mRightPaddingDefined = rightPaddingDefined;
4580
4581        if (padding >= 0) {
4582            leftPadding = padding;
4583            topPadding = padding;
4584            rightPadding = padding;
4585            bottomPadding = padding;
4586            mUserPaddingLeftInitial = padding;
4587            mUserPaddingRightInitial = padding;
4588        }
4589
4590        if (isRtlCompatibilityMode()) {
4591            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4592            // left / right padding are used if defined (meaning here nothing to do). If they are not
4593            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4594            // start / end and resolve them as left / right (layout direction is not taken into account).
4595            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4596            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4597            // defined.
4598            if (!mLeftPaddingDefined && startPaddingDefined) {
4599                leftPadding = startPadding;
4600            }
4601            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4602            if (!mRightPaddingDefined && endPaddingDefined) {
4603                rightPadding = endPadding;
4604            }
4605            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4606        } else {
4607            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4608            // values defined. Otherwise, left /right values are used.
4609            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4610            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4611            // defined.
4612            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4613
4614            if (mLeftPaddingDefined && !hasRelativePadding) {
4615                mUserPaddingLeftInitial = leftPadding;
4616            }
4617            if (mRightPaddingDefined && !hasRelativePadding) {
4618                mUserPaddingRightInitial = rightPadding;
4619            }
4620        }
4621
4622        internalSetPadding(
4623                mUserPaddingLeftInitial,
4624                topPadding >= 0 ? topPadding : mPaddingTop,
4625                mUserPaddingRightInitial,
4626                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4627
4628        if (viewFlagMasks != 0) {
4629            setFlags(viewFlagValues, viewFlagMasks);
4630        }
4631
4632        if (initializeScrollbars) {
4633            initializeScrollbarsInternal(a);
4634        }
4635
4636        if (initializeScrollIndicators) {
4637            initializeScrollIndicatorsInternal();
4638        }
4639
4640        a.recycle();
4641
4642        // Needs to be called after mViewFlags is set
4643        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4644            recomputePadding();
4645        }
4646
4647        if (x != 0 || y != 0) {
4648            scrollTo(x, y);
4649        }
4650
4651        if (transformSet) {
4652            setTranslationX(tx);
4653            setTranslationY(ty);
4654            setTranslationZ(tz);
4655            setElevation(elevation);
4656            setRotation(rotation);
4657            setRotationX(rotationX);
4658            setRotationY(rotationY);
4659            setScaleX(sx);
4660            setScaleY(sy);
4661        }
4662
4663        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4664            setScrollContainer(true);
4665        }
4666
4667        computeOpaqueFlags();
4668    }
4669
4670    /**
4671     * An implementation of OnClickListener that attempts to lazily load a
4672     * named click handling method from a parent or ancestor context.
4673     */
4674    private static class DeclaredOnClickListener implements OnClickListener {
4675        private final View mHostView;
4676        private final String mMethodName;
4677
4678        private Method mResolvedMethod;
4679        private Context mResolvedContext;
4680
4681        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4682            mHostView = hostView;
4683            mMethodName = methodName;
4684        }
4685
4686        @Override
4687        public void onClick(@NonNull View v) {
4688            if (mResolvedMethod == null) {
4689                resolveMethod(mHostView.getContext(), mMethodName);
4690            }
4691
4692            try {
4693                mResolvedMethod.invoke(mResolvedContext, v);
4694            } catch (IllegalAccessException e) {
4695                throw new IllegalStateException(
4696                        "Could not execute non-public method for android:onClick", e);
4697            } catch (InvocationTargetException e) {
4698                throw new IllegalStateException(
4699                        "Could not execute method for android:onClick", e);
4700            }
4701        }
4702
4703        @NonNull
4704        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4705            while (context != null) {
4706                try {
4707                    if (!context.isRestricted()) {
4708                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4709                        if (method != null) {
4710                            mResolvedMethod = method;
4711                            mResolvedContext = context;
4712                            return;
4713                        }
4714                    }
4715                } catch (NoSuchMethodException e) {
4716                    // Failed to find method, keep searching up the hierarchy.
4717                }
4718
4719                if (context instanceof ContextWrapper) {
4720                    context = ((ContextWrapper) context).getBaseContext();
4721                } else {
4722                    // Can't search up the hierarchy, null out and fail.
4723                    context = null;
4724                }
4725            }
4726
4727            final int id = mHostView.getId();
4728            final String idText = id == NO_ID ? "" : " with id '"
4729                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4730            throw new IllegalStateException("Could not find method " + mMethodName
4731                    + "(View) in a parent or ancestor Context for android:onClick "
4732                    + "attribute defined on view " + mHostView.getClass() + idText);
4733        }
4734    }
4735
4736    /**
4737     * Non-public constructor for use in testing
4738     */
4739    View() {
4740        mResources = null;
4741        mRenderNode = RenderNode.create(getClass().getName(), this);
4742    }
4743
4744    private static SparseArray<String> getAttributeMap() {
4745        if (mAttributeMap == null) {
4746            mAttributeMap = new SparseArray<>();
4747        }
4748        return mAttributeMap;
4749    }
4750
4751    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4752        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4753        final int indexCount = t.getIndexCount();
4754        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4755
4756        int i = 0;
4757
4758        // Store raw XML attributes.
4759        for (int j = 0; j < attrsCount; ++j) {
4760            attributes[i] = attrs.getAttributeName(j);
4761            attributes[i + 1] = attrs.getAttributeValue(j);
4762            i += 2;
4763        }
4764
4765        // Store resolved styleable attributes.
4766        final Resources res = t.getResources();
4767        final SparseArray<String> attributeMap = getAttributeMap();
4768        for (int j = 0; j < indexCount; ++j) {
4769            final int index = t.getIndex(j);
4770            if (!t.hasValueOrEmpty(index)) {
4771                // Value is undefined. Skip it.
4772                continue;
4773            }
4774
4775            final int resourceId = t.getResourceId(index, 0);
4776            if (resourceId == 0) {
4777                // Value is not a reference. Skip it.
4778                continue;
4779            }
4780
4781            String resourceName = attributeMap.get(resourceId);
4782            if (resourceName == null) {
4783                try {
4784                    resourceName = res.getResourceName(resourceId);
4785                } catch (Resources.NotFoundException e) {
4786                    resourceName = "0x" + Integer.toHexString(resourceId);
4787                }
4788                attributeMap.put(resourceId, resourceName);
4789            }
4790
4791            attributes[i] = resourceName;
4792            attributes[i + 1] = t.getString(index);
4793            i += 2;
4794        }
4795
4796        // Trim to fit contents.
4797        final String[] trimmed = new String[i];
4798        System.arraycopy(attributes, 0, trimmed, 0, i);
4799        mAttributes = trimmed;
4800    }
4801
4802    public String toString() {
4803        StringBuilder out = new StringBuilder(128);
4804        out.append(getClass().getName());
4805        out.append('{');
4806        out.append(Integer.toHexString(System.identityHashCode(this)));
4807        out.append(' ');
4808        switch (mViewFlags&VISIBILITY_MASK) {
4809            case VISIBLE: out.append('V'); break;
4810            case INVISIBLE: out.append('I'); break;
4811            case GONE: out.append('G'); break;
4812            default: out.append('.'); break;
4813        }
4814        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4815        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4816        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4817        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4818        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4819        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4820        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4821        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4822        out.append(' ');
4823        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4824        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4825        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4826        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4827            out.append('p');
4828        } else {
4829            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4830        }
4831        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4832        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4833        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4834        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4835        out.append(' ');
4836        out.append(mLeft);
4837        out.append(',');
4838        out.append(mTop);
4839        out.append('-');
4840        out.append(mRight);
4841        out.append(',');
4842        out.append(mBottom);
4843        final int id = getId();
4844        if (id != NO_ID) {
4845            out.append(" #");
4846            out.append(Integer.toHexString(id));
4847            final Resources r = mResources;
4848            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4849                try {
4850                    String pkgname;
4851                    switch (id&0xff000000) {
4852                        case 0x7f000000:
4853                            pkgname="app";
4854                            break;
4855                        case 0x01000000:
4856                            pkgname="android";
4857                            break;
4858                        default:
4859                            pkgname = r.getResourcePackageName(id);
4860                            break;
4861                    }
4862                    String typename = r.getResourceTypeName(id);
4863                    String entryname = r.getResourceEntryName(id);
4864                    out.append(" ");
4865                    out.append(pkgname);
4866                    out.append(":");
4867                    out.append(typename);
4868                    out.append("/");
4869                    out.append(entryname);
4870                } catch (Resources.NotFoundException e) {
4871                }
4872            }
4873        }
4874        out.append("}");
4875        return out.toString();
4876    }
4877
4878    /**
4879     * <p>
4880     * Initializes the fading edges from a given set of styled attributes. This
4881     * method should be called by subclasses that need fading edges and when an
4882     * instance of these subclasses is created programmatically rather than
4883     * being inflated from XML. This method is automatically called when the XML
4884     * is inflated.
4885     * </p>
4886     *
4887     * @param a the styled attributes set to initialize the fading edges from
4888     *
4889     * @removed
4890     */
4891    protected void initializeFadingEdge(TypedArray a) {
4892        // This method probably shouldn't have been included in the SDK to begin with.
4893        // It relies on 'a' having been initialized using an attribute filter array that is
4894        // not publicly available to the SDK. The old method has been renamed
4895        // to initializeFadingEdgeInternal and hidden for framework use only;
4896        // this one initializes using defaults to make it safe to call for apps.
4897
4898        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4899
4900        initializeFadingEdgeInternal(arr);
4901
4902        arr.recycle();
4903    }
4904
4905    /**
4906     * <p>
4907     * Initializes the fading edges from a given set of styled attributes. This
4908     * method should be called by subclasses that need fading edges and when an
4909     * instance of these subclasses is created programmatically rather than
4910     * being inflated from XML. This method is automatically called when the XML
4911     * is inflated.
4912     * </p>
4913     *
4914     * @param a the styled attributes set to initialize the fading edges from
4915     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4916     */
4917    protected void initializeFadingEdgeInternal(TypedArray a) {
4918        initScrollCache();
4919
4920        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4921                R.styleable.View_fadingEdgeLength,
4922                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4923    }
4924
4925    /**
4926     * Returns the size of the vertical faded edges used to indicate that more
4927     * content in this view is visible.
4928     *
4929     * @return The size in pixels of the vertical faded edge or 0 if vertical
4930     *         faded edges are not enabled for this view.
4931     * @attr ref android.R.styleable#View_fadingEdgeLength
4932     */
4933    public int getVerticalFadingEdgeLength() {
4934        if (isVerticalFadingEdgeEnabled()) {
4935            ScrollabilityCache cache = mScrollCache;
4936            if (cache != null) {
4937                return cache.fadingEdgeLength;
4938            }
4939        }
4940        return 0;
4941    }
4942
4943    /**
4944     * Set the size of the faded edge used to indicate that more content in this
4945     * view is available.  Will not change whether the fading edge is enabled; use
4946     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4947     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4948     * for the vertical or horizontal fading edges.
4949     *
4950     * @param length The size in pixels of the faded edge used to indicate that more
4951     *        content in this view is visible.
4952     */
4953    public void setFadingEdgeLength(int length) {
4954        initScrollCache();
4955        mScrollCache.fadingEdgeLength = length;
4956    }
4957
4958    /**
4959     * Returns the size of the horizontal faded edges used to indicate that more
4960     * content in this view is visible.
4961     *
4962     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4963     *         faded edges are not enabled for this view.
4964     * @attr ref android.R.styleable#View_fadingEdgeLength
4965     */
4966    public int getHorizontalFadingEdgeLength() {
4967        if (isHorizontalFadingEdgeEnabled()) {
4968            ScrollabilityCache cache = mScrollCache;
4969            if (cache != null) {
4970                return cache.fadingEdgeLength;
4971            }
4972        }
4973        return 0;
4974    }
4975
4976    /**
4977     * Returns the width of the vertical scrollbar.
4978     *
4979     * @return The width in pixels of the vertical scrollbar or 0 if there
4980     *         is no vertical scrollbar.
4981     */
4982    public int getVerticalScrollbarWidth() {
4983        ScrollabilityCache cache = mScrollCache;
4984        if (cache != null) {
4985            ScrollBarDrawable scrollBar = cache.scrollBar;
4986            if (scrollBar != null) {
4987                int size = scrollBar.getSize(true);
4988                if (size <= 0) {
4989                    size = cache.scrollBarSize;
4990                }
4991                return size;
4992            }
4993            return 0;
4994        }
4995        return 0;
4996    }
4997
4998    /**
4999     * Returns the height of the horizontal scrollbar.
5000     *
5001     * @return The height in pixels of the horizontal scrollbar or 0 if
5002     *         there is no horizontal scrollbar.
5003     */
5004    protected int getHorizontalScrollbarHeight() {
5005        ScrollabilityCache cache = mScrollCache;
5006        if (cache != null) {
5007            ScrollBarDrawable scrollBar = cache.scrollBar;
5008            if (scrollBar != null) {
5009                int size = scrollBar.getSize(false);
5010                if (size <= 0) {
5011                    size = cache.scrollBarSize;
5012                }
5013                return size;
5014            }
5015            return 0;
5016        }
5017        return 0;
5018    }
5019
5020    /**
5021     * <p>
5022     * Initializes the scrollbars from a given set of styled attributes. This
5023     * method should be called by subclasses that need scrollbars and when an
5024     * instance of these subclasses is created programmatically rather than
5025     * being inflated from XML. This method is automatically called when the XML
5026     * is inflated.
5027     * </p>
5028     *
5029     * @param a the styled attributes set to initialize the scrollbars from
5030     *
5031     * @removed
5032     */
5033    protected void initializeScrollbars(TypedArray a) {
5034        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5035        // using the View filter array which is not available to the SDK. As such, internal
5036        // framework usage now uses initializeScrollbarsInternal and we grab a default
5037        // TypedArray with the right filter instead here.
5038        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5039
5040        initializeScrollbarsInternal(arr);
5041
5042        // We ignored the method parameter. Recycle the one we actually did use.
5043        arr.recycle();
5044    }
5045
5046    /**
5047     * <p>
5048     * Initializes the scrollbars from a given set of styled attributes. This
5049     * method should be called by subclasses that need scrollbars and when an
5050     * instance of these subclasses is created programmatically rather than
5051     * being inflated from XML. This method is automatically called when the XML
5052     * is inflated.
5053     * </p>
5054     *
5055     * @param a the styled attributes set to initialize the scrollbars from
5056     * @hide
5057     */
5058    protected void initializeScrollbarsInternal(TypedArray a) {
5059        initScrollCache();
5060
5061        final ScrollabilityCache scrollabilityCache = mScrollCache;
5062
5063        if (scrollabilityCache.scrollBar == null) {
5064            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5065            scrollabilityCache.scrollBar.setState(getDrawableState());
5066            scrollabilityCache.scrollBar.setCallback(this);
5067        }
5068
5069        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5070
5071        if (!fadeScrollbars) {
5072            scrollabilityCache.state = ScrollabilityCache.ON;
5073        }
5074        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5075
5076
5077        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5078                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5079                        .getScrollBarFadeDuration());
5080        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5081                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5082                ViewConfiguration.getScrollDefaultDelay());
5083
5084
5085        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5086                com.android.internal.R.styleable.View_scrollbarSize,
5087                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5088
5089        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5090        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5091
5092        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5093        if (thumb != null) {
5094            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5095        }
5096
5097        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5098                false);
5099        if (alwaysDraw) {
5100            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5101        }
5102
5103        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5104        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5105
5106        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5107        if (thumb != null) {
5108            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5109        }
5110
5111        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5112                false);
5113        if (alwaysDraw) {
5114            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5115        }
5116
5117        // Apply layout direction to the new Drawables if needed
5118        final int layoutDirection = getLayoutDirection();
5119        if (track != null) {
5120            track.setLayoutDirection(layoutDirection);
5121        }
5122        if (thumb != null) {
5123            thumb.setLayoutDirection(layoutDirection);
5124        }
5125
5126        // Re-apply user/background padding so that scrollbar(s) get added
5127        resolvePadding();
5128    }
5129
5130    private void initializeScrollIndicatorsInternal() {
5131        // Some day maybe we'll break this into top/left/start/etc. and let the
5132        // client control it. Until then, you can have any scroll indicator you
5133        // want as long as it's a 1dp foreground-colored rectangle.
5134        if (mScrollIndicatorDrawable == null) {
5135            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5136        }
5137    }
5138
5139    /**
5140     * <p>
5141     * Initalizes the scrollability cache if necessary.
5142     * </p>
5143     */
5144    private void initScrollCache() {
5145        if (mScrollCache == null) {
5146            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5147        }
5148    }
5149
5150    private ScrollabilityCache getScrollCache() {
5151        initScrollCache();
5152        return mScrollCache;
5153    }
5154
5155    /**
5156     * Set the position of the vertical scroll bar. Should be one of
5157     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5158     * {@link #SCROLLBAR_POSITION_RIGHT}.
5159     *
5160     * @param position Where the vertical scroll bar should be positioned.
5161     */
5162    public void setVerticalScrollbarPosition(int position) {
5163        if (mVerticalScrollbarPosition != position) {
5164            mVerticalScrollbarPosition = position;
5165            computeOpaqueFlags();
5166            resolvePadding();
5167        }
5168    }
5169
5170    /**
5171     * @return The position where the vertical scroll bar will show, if applicable.
5172     * @see #setVerticalScrollbarPosition(int)
5173     */
5174    public int getVerticalScrollbarPosition() {
5175        return mVerticalScrollbarPosition;
5176    }
5177
5178    boolean isOnScrollbar(float x, float y) {
5179        if (mScrollCache == null) {
5180            return false;
5181        }
5182        x += getScrollX();
5183        y += getScrollY();
5184        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5185            final Rect bounds = mScrollCache.mScrollBarBounds;
5186            getVerticalScrollBarBounds(bounds);
5187            if (bounds.contains((int)x, (int)y)) {
5188                return true;
5189            }
5190        }
5191        if (isHorizontalScrollBarEnabled()) {
5192            final Rect bounds = mScrollCache.mScrollBarBounds;
5193            getHorizontalScrollBarBounds(bounds);
5194            if (bounds.contains((int)x, (int)y)) {
5195                return true;
5196            }
5197        }
5198        return false;
5199    }
5200
5201    boolean isOnScrollbarThumb(float x, float y) {
5202        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5203    }
5204
5205    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5206        if (mScrollCache == null) {
5207            return false;
5208        }
5209        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5210            x += getScrollX();
5211            y += getScrollY();
5212            final Rect bounds = mScrollCache.mScrollBarBounds;
5213            getVerticalScrollBarBounds(bounds);
5214            final int range = computeVerticalScrollRange();
5215            final int offset = computeVerticalScrollOffset();
5216            final int extent = computeVerticalScrollExtent();
5217            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5218                    extent, range);
5219            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5220                    extent, range, offset);
5221            final int thumbTop = bounds.top + thumbOffset;
5222            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5223                    && y <= thumbTop + thumbLength) {
5224                return true;
5225            }
5226        }
5227        return false;
5228    }
5229
5230    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5231        if (mScrollCache == null) {
5232            return false;
5233        }
5234        if (isHorizontalScrollBarEnabled()) {
5235            x += getScrollX();
5236            y += getScrollY();
5237            final Rect bounds = mScrollCache.mScrollBarBounds;
5238            getHorizontalScrollBarBounds(bounds);
5239            final int range = computeHorizontalScrollRange();
5240            final int offset = computeHorizontalScrollOffset();
5241            final int extent = computeHorizontalScrollExtent();
5242            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5243                    extent, range);
5244            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5245                    extent, range, offset);
5246            final int thumbLeft = bounds.left + thumbOffset;
5247            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5248                    && y <= bounds.bottom) {
5249                return true;
5250            }
5251        }
5252        return false;
5253    }
5254
5255    boolean isDraggingScrollBar() {
5256        return mScrollCache != null
5257                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5258    }
5259
5260    /**
5261     * Sets the state of all scroll indicators.
5262     * <p>
5263     * See {@link #setScrollIndicators(int, int)} for usage information.
5264     *
5265     * @param indicators a bitmask of indicators that should be enabled, or
5266     *                   {@code 0} to disable all indicators
5267     * @see #setScrollIndicators(int, int)
5268     * @see #getScrollIndicators()
5269     * @attr ref android.R.styleable#View_scrollIndicators
5270     */
5271    public void setScrollIndicators(@ScrollIndicators int indicators) {
5272        setScrollIndicators(indicators,
5273                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5274    }
5275
5276    /**
5277     * Sets the state of the scroll indicators specified by the mask. To change
5278     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5279     * <p>
5280     * When a scroll indicator is enabled, it will be displayed if the view
5281     * can scroll in the direction of the indicator.
5282     * <p>
5283     * Multiple indicator types may be enabled or disabled by passing the
5284     * logical OR of the desired types. If multiple types are specified, they
5285     * will all be set to the same enabled state.
5286     * <p>
5287     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5288     *
5289     * @param indicators the indicator direction, or the logical OR of multiple
5290     *             indicator directions. One or more of:
5291     *             <ul>
5292     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5293     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5294     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5295     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5296     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5297     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5298     *             </ul>
5299     * @see #setScrollIndicators(int)
5300     * @see #getScrollIndicators()
5301     * @attr ref android.R.styleable#View_scrollIndicators
5302     */
5303    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5304        // Shift and sanitize mask.
5305        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5306        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5307
5308        // Shift and mask indicators.
5309        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5310        indicators &= mask;
5311
5312        // Merge with non-masked flags.
5313        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5314
5315        if (mPrivateFlags3 != updatedFlags) {
5316            mPrivateFlags3 = updatedFlags;
5317
5318            if (indicators != 0) {
5319                initializeScrollIndicatorsInternal();
5320            }
5321            invalidate();
5322        }
5323    }
5324
5325    /**
5326     * Returns a bitmask representing the enabled scroll indicators.
5327     * <p>
5328     * For example, if the top and left scroll indicators are enabled and all
5329     * other indicators are disabled, the return value will be
5330     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5331     * <p>
5332     * To check whether the bottom scroll indicator is enabled, use the value
5333     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5334     *
5335     * @return a bitmask representing the enabled scroll indicators
5336     */
5337    @ScrollIndicators
5338    public int getScrollIndicators() {
5339        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5340                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5341    }
5342
5343    ListenerInfo getListenerInfo() {
5344        if (mListenerInfo != null) {
5345            return mListenerInfo;
5346        }
5347        mListenerInfo = new ListenerInfo();
5348        return mListenerInfo;
5349    }
5350
5351    /**
5352     * Register a callback to be invoked when the scroll X or Y positions of
5353     * this view change.
5354     * <p>
5355     * <b>Note:</b> Some views handle scrolling independently from View and may
5356     * have their own separate listeners for scroll-type events. For example,
5357     * {@link android.widget.ListView ListView} allows clients to register an
5358     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5359     * to listen for changes in list scroll position.
5360     *
5361     * @param l The listener to notify when the scroll X or Y position changes.
5362     * @see android.view.View#getScrollX()
5363     * @see android.view.View#getScrollY()
5364     */
5365    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5366        getListenerInfo().mOnScrollChangeListener = l;
5367    }
5368
5369    /**
5370     * Register a callback to be invoked when focus of this view changed.
5371     *
5372     * @param l The callback that will run.
5373     */
5374    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5375        getListenerInfo().mOnFocusChangeListener = l;
5376    }
5377
5378    /**
5379     * Add a listener that will be called when the bounds of the view change due to
5380     * layout processing.
5381     *
5382     * @param listener The listener that will be called when layout bounds change.
5383     */
5384    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5385        ListenerInfo li = getListenerInfo();
5386        if (li.mOnLayoutChangeListeners == null) {
5387            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5388        }
5389        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5390            li.mOnLayoutChangeListeners.add(listener);
5391        }
5392    }
5393
5394    /**
5395     * Remove a listener for layout changes.
5396     *
5397     * @param listener The listener for layout bounds change.
5398     */
5399    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5400        ListenerInfo li = mListenerInfo;
5401        if (li == null || li.mOnLayoutChangeListeners == null) {
5402            return;
5403        }
5404        li.mOnLayoutChangeListeners.remove(listener);
5405    }
5406
5407    /**
5408     * Add a listener for attach state changes.
5409     *
5410     * This listener will be called whenever this view is attached or detached
5411     * from a window. Remove the listener using
5412     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5413     *
5414     * @param listener Listener to attach
5415     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5416     */
5417    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5418        ListenerInfo li = getListenerInfo();
5419        if (li.mOnAttachStateChangeListeners == null) {
5420            li.mOnAttachStateChangeListeners
5421                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5422        }
5423        li.mOnAttachStateChangeListeners.add(listener);
5424    }
5425
5426    /**
5427     * Remove a listener for attach state changes. The listener will receive no further
5428     * notification of window attach/detach events.
5429     *
5430     * @param listener Listener to remove
5431     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5432     */
5433    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5434        ListenerInfo li = mListenerInfo;
5435        if (li == null || li.mOnAttachStateChangeListeners == null) {
5436            return;
5437        }
5438        li.mOnAttachStateChangeListeners.remove(listener);
5439    }
5440
5441    /**
5442     * Returns the focus-change callback registered for this view.
5443     *
5444     * @return The callback, or null if one is not registered.
5445     */
5446    public OnFocusChangeListener getOnFocusChangeListener() {
5447        ListenerInfo li = mListenerInfo;
5448        return li != null ? li.mOnFocusChangeListener : null;
5449    }
5450
5451    /**
5452     * Register a callback to be invoked when this view is clicked. If this view is not
5453     * clickable, it becomes clickable.
5454     *
5455     * @param l The callback that will run
5456     *
5457     * @see #setClickable(boolean)
5458     */
5459    public void setOnClickListener(@Nullable OnClickListener l) {
5460        if (!isClickable()) {
5461            setClickable(true);
5462        }
5463        getListenerInfo().mOnClickListener = l;
5464    }
5465
5466    /**
5467     * Return whether this view has an attached OnClickListener.  Returns
5468     * true if there is a listener, false if there is none.
5469     */
5470    public boolean hasOnClickListeners() {
5471        ListenerInfo li = mListenerInfo;
5472        return (li != null && li.mOnClickListener != null);
5473    }
5474
5475    /**
5476     * Register a callback to be invoked when this view is clicked and held. If this view is not
5477     * long clickable, it becomes long clickable.
5478     *
5479     * @param l The callback that will run
5480     *
5481     * @see #setLongClickable(boolean)
5482     */
5483    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5484        if (!isLongClickable()) {
5485            setLongClickable(true);
5486        }
5487        getListenerInfo().mOnLongClickListener = l;
5488    }
5489
5490    /**
5491     * Register a callback to be invoked when this view is context clicked. If the view is not
5492     * context clickable, it becomes context clickable.
5493     *
5494     * @param l The callback that will run
5495     * @see #setContextClickable(boolean)
5496     */
5497    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5498        if (!isContextClickable()) {
5499            setContextClickable(true);
5500        }
5501        getListenerInfo().mOnContextClickListener = l;
5502    }
5503
5504    /**
5505     * Register a callback to be invoked when the context menu for this view is
5506     * being built. If this view is not long clickable, it becomes long clickable.
5507     *
5508     * @param l The callback that will run
5509     *
5510     */
5511    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5512        if (!isLongClickable()) {
5513            setLongClickable(true);
5514        }
5515        getListenerInfo().mOnCreateContextMenuListener = l;
5516    }
5517
5518    /**
5519     * Set an observer to collect stats for each frame rendered for this view.
5520     *
5521     * @hide
5522     */
5523    public void addFrameMetricsListener(Window window,
5524            Window.OnFrameMetricsAvailableListener listener,
5525            Handler handler) {
5526        if (mAttachInfo != null) {
5527            if (mAttachInfo.mHardwareRenderer != null) {
5528                if (mFrameMetricsObservers == null) {
5529                    mFrameMetricsObservers = new ArrayList<>();
5530                }
5531
5532                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5533                        handler.getLooper(), listener);
5534                mFrameMetricsObservers.add(fmo);
5535                mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo);
5536            } else {
5537                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5538            }
5539        } else {
5540            if (mFrameMetricsObservers == null) {
5541                mFrameMetricsObservers = new ArrayList<>();
5542            }
5543
5544            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5545                    handler.getLooper(), listener);
5546            mFrameMetricsObservers.add(fmo);
5547        }
5548    }
5549
5550    /**
5551     * Remove observer configured to collect frame stats for this view.
5552     *
5553     * @hide
5554     */
5555    public void removeFrameMetricsListener(
5556            Window.OnFrameMetricsAvailableListener listener) {
5557        ThreadedRenderer renderer = getHardwareRenderer();
5558        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5559        if (fmo == null) {
5560            throw new IllegalArgumentException(
5561                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5562        }
5563
5564        if (mFrameMetricsObservers != null) {
5565            mFrameMetricsObservers.remove(fmo);
5566            if (renderer != null) {
5567                renderer.removeFrameMetricsObserver(fmo);
5568            }
5569        }
5570    }
5571
5572    private void registerPendingFrameMetricsObservers() {
5573        if (mFrameMetricsObservers != null) {
5574            ThreadedRenderer renderer = getHardwareRenderer();
5575            if (renderer != null) {
5576                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5577                    renderer.addFrameMetricsObserver(fmo);
5578                }
5579            } else {
5580                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5581            }
5582        }
5583    }
5584
5585    private FrameMetricsObserver findFrameMetricsObserver(
5586            Window.OnFrameMetricsAvailableListener listener) {
5587        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5588            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5589            if (observer.mListener == listener) {
5590                return observer;
5591            }
5592        }
5593
5594        return null;
5595    }
5596
5597    /**
5598     * Call this view's OnClickListener, if it is defined.  Performs all normal
5599     * actions associated with clicking: reporting accessibility event, playing
5600     * a sound, etc.
5601     *
5602     * @return True there was an assigned OnClickListener that was called, false
5603     *         otherwise is returned.
5604     */
5605    public boolean performClick() {
5606        final boolean result;
5607        final ListenerInfo li = mListenerInfo;
5608        if (li != null && li.mOnClickListener != null) {
5609            playSoundEffect(SoundEffectConstants.CLICK);
5610            li.mOnClickListener.onClick(this);
5611            result = true;
5612        } else {
5613            result = false;
5614        }
5615
5616        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5617        return result;
5618    }
5619
5620    /**
5621     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5622     * this only calls the listener, and does not do any associated clicking
5623     * actions like reporting an accessibility event.
5624     *
5625     * @return True there was an assigned OnClickListener that was called, false
5626     *         otherwise is returned.
5627     */
5628    public boolean callOnClick() {
5629        ListenerInfo li = mListenerInfo;
5630        if (li != null && li.mOnClickListener != null) {
5631            li.mOnClickListener.onClick(this);
5632            return true;
5633        }
5634        return false;
5635    }
5636
5637    /**
5638     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5639     * context menu if the OnLongClickListener did not consume the event.
5640     *
5641     * @return {@code true} if one of the above receivers consumed the event,
5642     *         {@code false} otherwise
5643     */
5644    public boolean performLongClick() {
5645        return performLongClickInternal(mLongClickX, mLongClickY);
5646    }
5647
5648    /**
5649     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5650     * context menu if the OnLongClickListener did not consume the event,
5651     * anchoring it to an (x,y) coordinate.
5652     *
5653     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5654     *          to disable anchoring
5655     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5656     *          to disable anchoring
5657     * @return {@code true} if one of the above receivers consumed the event,
5658     *         {@code false} otherwise
5659     */
5660    public boolean performLongClick(float x, float y) {
5661        mLongClickX = x;
5662        mLongClickY = y;
5663        final boolean handled = performLongClick();
5664        mLongClickX = Float.NaN;
5665        mLongClickY = Float.NaN;
5666        return handled;
5667    }
5668
5669    /**
5670     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5671     * context menu if the OnLongClickListener did not consume the event,
5672     * optionally anchoring it to an (x,y) coordinate.
5673     *
5674     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5675     *          to disable anchoring
5676     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5677     *          to disable anchoring
5678     * @return {@code true} if one of the above receivers consumed the event,
5679     *         {@code false} otherwise
5680     */
5681    private boolean performLongClickInternal(float x, float y) {
5682        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5683
5684        boolean handled = false;
5685        final ListenerInfo li = mListenerInfo;
5686        if (li != null && li.mOnLongClickListener != null) {
5687            handled = li.mOnLongClickListener.onLongClick(View.this);
5688        }
5689        if (!handled) {
5690            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5691            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5692        }
5693        if (handled) {
5694            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5695        }
5696        return handled;
5697    }
5698
5699    /**
5700     * Call this view's OnContextClickListener, if it is defined.
5701     *
5702     * @param x the x coordinate of the context click
5703     * @param y the y coordinate of the context click
5704     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5705     *         otherwise.
5706     */
5707    public boolean performContextClick(float x, float y) {
5708        return performContextClick();
5709    }
5710
5711    /**
5712     * Call this view's OnContextClickListener, if it is defined.
5713     *
5714     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5715     *         otherwise.
5716     */
5717    public boolean performContextClick() {
5718        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5719
5720        boolean handled = false;
5721        ListenerInfo li = mListenerInfo;
5722        if (li != null && li.mOnContextClickListener != null) {
5723            handled = li.mOnContextClickListener.onContextClick(View.this);
5724        }
5725        if (handled) {
5726            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5727        }
5728        return handled;
5729    }
5730
5731    /**
5732     * Performs button-related actions during a touch down event.
5733     *
5734     * @param event The event.
5735     * @return True if the down was consumed.
5736     *
5737     * @hide
5738     */
5739    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5740        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5741            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5742            showContextMenu(event.getX(), event.getY());
5743            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5744            return true;
5745        }
5746        return false;
5747    }
5748
5749    /**
5750     * Shows the context menu for this view.
5751     *
5752     * @return {@code true} if the context menu was shown, {@code false}
5753     *         otherwise
5754     * @see #showContextMenu(float, float)
5755     */
5756    public boolean showContextMenu() {
5757        return getParent().showContextMenuForChild(this);
5758    }
5759
5760    /**
5761     * Shows the context menu for this view anchored to the specified
5762     * view-relative coordinate.
5763     *
5764     * @param x the X coordinate in pixels relative to the view to which the
5765     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5766     * @param y the Y coordinate in pixels relative to the view to which the
5767     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5768     * @return {@code true} if the context menu was shown, {@code false}
5769     *         otherwise
5770     */
5771    public boolean showContextMenu(float x, float y) {
5772        return getParent().showContextMenuForChild(this, x, y);
5773    }
5774
5775    /**
5776     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5777     *
5778     * @param callback Callback that will control the lifecycle of the action mode
5779     * @return The new action mode if it is started, null otherwise
5780     *
5781     * @see ActionMode
5782     * @see #startActionMode(android.view.ActionMode.Callback, int)
5783     */
5784    public ActionMode startActionMode(ActionMode.Callback callback) {
5785        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5786    }
5787
5788    /**
5789     * Start an action mode with the given type.
5790     *
5791     * @param callback Callback that will control the lifecycle of the action mode
5792     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5793     * @return The new action mode if it is started, null otherwise
5794     *
5795     * @see ActionMode
5796     */
5797    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5798        ViewParent parent = getParent();
5799        if (parent == null) return null;
5800        try {
5801            return parent.startActionModeForChild(this, callback, type);
5802        } catch (AbstractMethodError ame) {
5803            // Older implementations of custom views might not implement this.
5804            return parent.startActionModeForChild(this, callback);
5805        }
5806    }
5807
5808    /**
5809     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5810     * Context, creating a unique View identifier to retrieve the result.
5811     *
5812     * @param intent The Intent to be started.
5813     * @param requestCode The request code to use.
5814     * @hide
5815     */
5816    public void startActivityForResult(Intent intent, int requestCode) {
5817        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5818        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5819    }
5820
5821    /**
5822     * If this View corresponds to the calling who, dispatches the activity result.
5823     * @param who The identifier for the targeted View to receive the result.
5824     * @param requestCode The integer request code originally supplied to
5825     *                    startActivityForResult(), allowing you to identify who this
5826     *                    result came from.
5827     * @param resultCode The integer result code returned by the child activity
5828     *                   through its setResult().
5829     * @param data An Intent, which can return result data to the caller
5830     *               (various data can be attached to Intent "extras").
5831     * @return {@code true} if the activity result was dispatched.
5832     * @hide
5833     */
5834    public boolean dispatchActivityResult(
5835            String who, int requestCode, int resultCode, Intent data) {
5836        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5837            onActivityResult(requestCode, resultCode, data);
5838            mStartActivityRequestWho = null;
5839            return true;
5840        }
5841        return false;
5842    }
5843
5844    /**
5845     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5846     *
5847     * @param requestCode The integer request code originally supplied to
5848     *                    startActivityForResult(), allowing you to identify who this
5849     *                    result came from.
5850     * @param resultCode The integer result code returned by the child activity
5851     *                   through its setResult().
5852     * @param data An Intent, which can return result data to the caller
5853     *               (various data can be attached to Intent "extras").
5854     * @hide
5855     */
5856    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5857        // Do nothing.
5858    }
5859
5860    /**
5861     * Register a callback to be invoked when a hardware key is pressed in this view.
5862     * Key presses in software input methods will generally not trigger the methods of
5863     * this listener.
5864     * @param l the key listener to attach to this view
5865     */
5866    public void setOnKeyListener(OnKeyListener l) {
5867        getListenerInfo().mOnKeyListener = l;
5868    }
5869
5870    /**
5871     * Register a callback to be invoked when a touch event is sent to this view.
5872     * @param l the touch listener to attach to this view
5873     */
5874    public void setOnTouchListener(OnTouchListener l) {
5875        getListenerInfo().mOnTouchListener = l;
5876    }
5877
5878    /**
5879     * Register a callback to be invoked when a generic motion event is sent to this view.
5880     * @param l the generic motion listener to attach to this view
5881     */
5882    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5883        getListenerInfo().mOnGenericMotionListener = l;
5884    }
5885
5886    /**
5887     * Register a callback to be invoked when a hover event is sent to this view.
5888     * @param l the hover listener to attach to this view
5889     */
5890    public void setOnHoverListener(OnHoverListener l) {
5891        getListenerInfo().mOnHoverListener = l;
5892    }
5893
5894    /**
5895     * Register a drag event listener callback object for this View. The parameter is
5896     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5897     * View, the system calls the
5898     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5899     * @param l An implementation of {@link android.view.View.OnDragListener}.
5900     */
5901    public void setOnDragListener(OnDragListener l) {
5902        getListenerInfo().mOnDragListener = l;
5903    }
5904
5905    /**
5906     * Give this view focus. This will cause
5907     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5908     *
5909     * Note: this does not check whether this {@link View} should get focus, it just
5910     * gives it focus no matter what.  It should only be called internally by framework
5911     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5912     *
5913     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5914     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5915     *        focus moved when requestFocus() is called. It may not always
5916     *        apply, in which case use the default View.FOCUS_DOWN.
5917     * @param previouslyFocusedRect The rectangle of the view that had focus
5918     *        prior in this View's coordinate system.
5919     */
5920    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5921        if (DBG) {
5922            System.out.println(this + " requestFocus()");
5923        }
5924
5925        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5926            mPrivateFlags |= PFLAG_FOCUSED;
5927
5928            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5929
5930            if (mParent != null) {
5931                mParent.requestChildFocus(this, this);
5932            }
5933
5934            if (mAttachInfo != null) {
5935                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5936            }
5937
5938            onFocusChanged(true, direction, previouslyFocusedRect);
5939            refreshDrawableState();
5940        }
5941    }
5942
5943    /**
5944     * Populates <code>outRect</code> with the hotspot bounds. By default,
5945     * the hotspot bounds are identical to the screen bounds.
5946     *
5947     * @param outRect rect to populate with hotspot bounds
5948     * @hide Only for internal use by views and widgets.
5949     */
5950    public void getHotspotBounds(Rect outRect) {
5951        final Drawable background = getBackground();
5952        if (background != null) {
5953            background.getHotspotBounds(outRect);
5954        } else {
5955            getBoundsOnScreen(outRect);
5956        }
5957    }
5958
5959    /**
5960     * Request that a rectangle of this view be visible on the screen,
5961     * scrolling if necessary just enough.
5962     *
5963     * <p>A View should call this if it maintains some notion of which part
5964     * of its content is interesting.  For example, a text editing view
5965     * should call this when its cursor moves.
5966     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5967     * It should not be affected by which part of the View is currently visible or its scroll
5968     * position.
5969     *
5970     * @param rectangle The rectangle in the View's content coordinate space
5971     * @return Whether any parent scrolled.
5972     */
5973    public boolean requestRectangleOnScreen(Rect rectangle) {
5974        return requestRectangleOnScreen(rectangle, false);
5975    }
5976
5977    /**
5978     * Request that a rectangle of this view be visible on the screen,
5979     * scrolling if necessary just enough.
5980     *
5981     * <p>A View should call this if it maintains some notion of which part
5982     * of its content is interesting.  For example, a text editing view
5983     * should call this when its cursor moves.
5984     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5985     * It should not be affected by which part of the View is currently visible or its scroll
5986     * position.
5987     * <p>When <code>immediate</code> is set to true, scrolling will not be
5988     * animated.
5989     *
5990     * @param rectangle The rectangle in the View's content coordinate space
5991     * @param immediate True to forbid animated scrolling, false otherwise
5992     * @return Whether any parent scrolled.
5993     */
5994    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5995        if (mParent == null) {
5996            return false;
5997        }
5998
5999        View child = this;
6000
6001        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6002        position.set(rectangle);
6003
6004        ViewParent parent = mParent;
6005        boolean scrolled = false;
6006        while (parent != null) {
6007            rectangle.set((int) position.left, (int) position.top,
6008                    (int) position.right, (int) position.bottom);
6009
6010            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6011
6012            if (!(parent instanceof View)) {
6013                break;
6014            }
6015
6016            // move it from child's content coordinate space to parent's content coordinate space
6017            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6018
6019            child = (View) parent;
6020            parent = child.getParent();
6021        }
6022
6023        return scrolled;
6024    }
6025
6026    /**
6027     * Called when this view wants to give up focus. If focus is cleared
6028     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6029     * <p>
6030     * <strong>Note:</strong> When a View clears focus the framework is trying
6031     * to give focus to the first focusable View from the top. Hence, if this
6032     * View is the first from the top that can take focus, then all callbacks
6033     * related to clearing focus will be invoked after which the framework will
6034     * give focus to this view.
6035     * </p>
6036     */
6037    public void clearFocus() {
6038        if (DBG) {
6039            System.out.println(this + " clearFocus()");
6040        }
6041
6042        clearFocusInternal(null, true, true);
6043    }
6044
6045    /**
6046     * Clears focus from the view, optionally propagating the change up through
6047     * the parent hierarchy and requesting that the root view place new focus.
6048     *
6049     * @param propagate whether to propagate the change up through the parent
6050     *            hierarchy
6051     * @param refocus when propagate is true, specifies whether to request the
6052     *            root view place new focus
6053     */
6054    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6055        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6056            mPrivateFlags &= ~PFLAG_FOCUSED;
6057
6058            if (propagate && mParent != null) {
6059                mParent.clearChildFocus(this);
6060            }
6061
6062            onFocusChanged(false, 0, null);
6063            refreshDrawableState();
6064
6065            if (propagate && (!refocus || !rootViewRequestFocus())) {
6066                notifyGlobalFocusCleared(this);
6067            }
6068        }
6069    }
6070
6071    void notifyGlobalFocusCleared(View oldFocus) {
6072        if (oldFocus != null && mAttachInfo != null) {
6073            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6074        }
6075    }
6076
6077    boolean rootViewRequestFocus() {
6078        final View root = getRootView();
6079        return root != null && root.requestFocus();
6080    }
6081
6082    /**
6083     * Called internally by the view system when a new view is getting focus.
6084     * This is what clears the old focus.
6085     * <p>
6086     * <b>NOTE:</b> The parent view's focused child must be updated manually
6087     * after calling this method. Otherwise, the view hierarchy may be left in
6088     * an inconstent state.
6089     */
6090    void unFocus(View focused) {
6091        if (DBG) {
6092            System.out.println(this + " unFocus()");
6093        }
6094
6095        clearFocusInternal(focused, false, false);
6096    }
6097
6098    /**
6099     * Returns true if this view has focus itself, or is the ancestor of the
6100     * view that has focus.
6101     *
6102     * @return True if this view has or contains focus, false otherwise.
6103     */
6104    @ViewDebug.ExportedProperty(category = "focus")
6105    public boolean hasFocus() {
6106        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6107    }
6108
6109    /**
6110     * Returns true if this view is focusable or if it contains a reachable View
6111     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6112     * is a View whose parents do not block descendants focus.
6113     *
6114     * Only {@link #VISIBLE} views are considered focusable.
6115     *
6116     * @return True if the view is focusable or if the view contains a focusable
6117     *         View, false otherwise.
6118     *
6119     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6120     * @see ViewGroup#getTouchscreenBlocksFocus()
6121     */
6122    public boolean hasFocusable() {
6123        if (!isFocusableInTouchMode()) {
6124            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6125                final ViewGroup g = (ViewGroup) p;
6126                if (g.shouldBlockFocusForTouchscreen()) {
6127                    return false;
6128                }
6129            }
6130        }
6131        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6132    }
6133
6134    /**
6135     * Called by the view system when the focus state of this view changes.
6136     * When the focus change event is caused by directional navigation, direction
6137     * and previouslyFocusedRect provide insight into where the focus is coming from.
6138     * When overriding, be sure to call up through to the super class so that
6139     * the standard focus handling will occur.
6140     *
6141     * @param gainFocus True if the View has focus; false otherwise.
6142     * @param direction The direction focus has moved when requestFocus()
6143     *                  is called to give this view focus. Values are
6144     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6145     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6146     *                  It may not always apply, in which case use the default.
6147     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6148     *        system, of the previously focused view.  If applicable, this will be
6149     *        passed in as finer grained information about where the focus is coming
6150     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6151     */
6152    @CallSuper
6153    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6154            @Nullable Rect previouslyFocusedRect) {
6155        if (gainFocus) {
6156            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6157        } else {
6158            notifyViewAccessibilityStateChangedIfNeeded(
6159                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6160        }
6161
6162        InputMethodManager imm = InputMethodManager.peekInstance();
6163        if (!gainFocus) {
6164            if (isPressed()) {
6165                setPressed(false);
6166            }
6167            if (imm != null && mAttachInfo != null
6168                    && mAttachInfo.mHasWindowFocus) {
6169                imm.focusOut(this);
6170            }
6171            onFocusLost();
6172        } else if (imm != null && mAttachInfo != null
6173                && mAttachInfo.mHasWindowFocus) {
6174            imm.focusIn(this);
6175        }
6176
6177        invalidate(true);
6178        ListenerInfo li = mListenerInfo;
6179        if (li != null && li.mOnFocusChangeListener != null) {
6180            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6181        }
6182
6183        if (mAttachInfo != null) {
6184            mAttachInfo.mKeyDispatchState.reset(this);
6185        }
6186    }
6187
6188    /**
6189     * Sends an accessibility event of the given type. If accessibility is
6190     * not enabled this method has no effect. The default implementation calls
6191     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6192     * to populate information about the event source (this View), then calls
6193     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6194     * populate the text content of the event source including its descendants,
6195     * and last calls
6196     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6197     * on its parent to request sending of the event to interested parties.
6198     * <p>
6199     * If an {@link AccessibilityDelegate} has been specified via calling
6200     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6201     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6202     * responsible for handling this call.
6203     * </p>
6204     *
6205     * @param eventType The type of the event to send, as defined by several types from
6206     * {@link android.view.accessibility.AccessibilityEvent}, such as
6207     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6208     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6209     *
6210     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6211     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6212     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6213     * @see AccessibilityDelegate
6214     */
6215    public void sendAccessibilityEvent(int eventType) {
6216        if (mAccessibilityDelegate != null) {
6217            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6218        } else {
6219            sendAccessibilityEventInternal(eventType);
6220        }
6221    }
6222
6223    /**
6224     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6225     * {@link AccessibilityEvent} to make an announcement which is related to some
6226     * sort of a context change for which none of the events representing UI transitions
6227     * is a good fit. For example, announcing a new page in a book. If accessibility
6228     * is not enabled this method does nothing.
6229     *
6230     * @param text The announcement text.
6231     */
6232    public void announceForAccessibility(CharSequence text) {
6233        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6234            AccessibilityEvent event = AccessibilityEvent.obtain(
6235                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6236            onInitializeAccessibilityEvent(event);
6237            event.getText().add(text);
6238            event.setContentDescription(null);
6239            mParent.requestSendAccessibilityEvent(this, event);
6240        }
6241    }
6242
6243    /**
6244     * @see #sendAccessibilityEvent(int)
6245     *
6246     * Note: Called from the default {@link AccessibilityDelegate}.
6247     *
6248     * @hide
6249     */
6250    public void sendAccessibilityEventInternal(int eventType) {
6251        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6252            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6253        }
6254    }
6255
6256    /**
6257     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6258     * takes as an argument an empty {@link AccessibilityEvent} and does not
6259     * perform a check whether accessibility is enabled.
6260     * <p>
6261     * If an {@link AccessibilityDelegate} has been specified via calling
6262     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6263     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6264     * is responsible for handling this call.
6265     * </p>
6266     *
6267     * @param event The event to send.
6268     *
6269     * @see #sendAccessibilityEvent(int)
6270     */
6271    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6272        if (mAccessibilityDelegate != null) {
6273            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6274        } else {
6275            sendAccessibilityEventUncheckedInternal(event);
6276        }
6277    }
6278
6279    /**
6280     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6281     *
6282     * Note: Called from the default {@link AccessibilityDelegate}.
6283     *
6284     * @hide
6285     */
6286    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6287        if (!isShown()) {
6288            return;
6289        }
6290        onInitializeAccessibilityEvent(event);
6291        // Only a subset of accessibility events populates text content.
6292        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6293            dispatchPopulateAccessibilityEvent(event);
6294        }
6295        // In the beginning we called #isShown(), so we know that getParent() is not null.
6296        getParent().requestSendAccessibilityEvent(this, event);
6297    }
6298
6299    /**
6300     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6301     * to its children for adding their text content to the event. Note that the
6302     * event text is populated in a separate dispatch path since we add to the
6303     * event not only the text of the source but also the text of all its descendants.
6304     * A typical implementation will call
6305     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6306     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6307     * on each child. Override this method if custom population of the event text
6308     * content is required.
6309     * <p>
6310     * If an {@link AccessibilityDelegate} has been specified via calling
6311     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6312     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6313     * is responsible for handling this call.
6314     * </p>
6315     * <p>
6316     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6317     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6318     * </p>
6319     *
6320     * @param event The event.
6321     *
6322     * @return True if the event population was completed.
6323     */
6324    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6325        if (mAccessibilityDelegate != null) {
6326            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6327        } else {
6328            return dispatchPopulateAccessibilityEventInternal(event);
6329        }
6330    }
6331
6332    /**
6333     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6334     *
6335     * Note: Called from the default {@link AccessibilityDelegate}.
6336     *
6337     * @hide
6338     */
6339    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6340        onPopulateAccessibilityEvent(event);
6341        return false;
6342    }
6343
6344    /**
6345     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6346     * giving a chance to this View to populate the accessibility event with its
6347     * text content. While this method is free to modify event
6348     * attributes other than text content, doing so should normally be performed in
6349     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6350     * <p>
6351     * Example: Adding formatted date string to an accessibility event in addition
6352     *          to the text added by the super implementation:
6353     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6354     *     super.onPopulateAccessibilityEvent(event);
6355     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6356     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6357     *         mCurrentDate.getTimeInMillis(), flags);
6358     *     event.getText().add(selectedDateUtterance);
6359     * }</pre>
6360     * <p>
6361     * If an {@link AccessibilityDelegate} has been specified via calling
6362     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6363     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6364     * is responsible for handling this call.
6365     * </p>
6366     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6367     * information to the event, in case the default implementation has basic information to add.
6368     * </p>
6369     *
6370     * @param event The accessibility event which to populate.
6371     *
6372     * @see #sendAccessibilityEvent(int)
6373     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6374     */
6375    @CallSuper
6376    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6377        if (mAccessibilityDelegate != null) {
6378            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6379        } else {
6380            onPopulateAccessibilityEventInternal(event);
6381        }
6382    }
6383
6384    /**
6385     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6386     *
6387     * Note: Called from the default {@link AccessibilityDelegate}.
6388     *
6389     * @hide
6390     */
6391    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6392    }
6393
6394    /**
6395     * Initializes an {@link AccessibilityEvent} with information about
6396     * this View which is the event source. In other words, the source of
6397     * an accessibility event is the view whose state change triggered firing
6398     * the event.
6399     * <p>
6400     * Example: Setting the password property of an event in addition
6401     *          to properties set by the super implementation:
6402     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6403     *     super.onInitializeAccessibilityEvent(event);
6404     *     event.setPassword(true);
6405     * }</pre>
6406     * <p>
6407     * If an {@link AccessibilityDelegate} has been specified via calling
6408     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6409     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6410     * is responsible for handling this call.
6411     * </p>
6412     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6413     * information to the event, in case the default implementation has basic information to add.
6414     * </p>
6415     * @param event The event to initialize.
6416     *
6417     * @see #sendAccessibilityEvent(int)
6418     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6419     */
6420    @CallSuper
6421    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6422        if (mAccessibilityDelegate != null) {
6423            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6424        } else {
6425            onInitializeAccessibilityEventInternal(event);
6426        }
6427    }
6428
6429    /**
6430     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6431     *
6432     * Note: Called from the default {@link AccessibilityDelegate}.
6433     *
6434     * @hide
6435     */
6436    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6437        event.setSource(this);
6438        event.setClassName(getAccessibilityClassName());
6439        event.setPackageName(getContext().getPackageName());
6440        event.setEnabled(isEnabled());
6441        event.setContentDescription(mContentDescription);
6442
6443        switch (event.getEventType()) {
6444            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6445                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6446                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6447                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6448                event.setItemCount(focusablesTempList.size());
6449                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6450                if (mAttachInfo != null) {
6451                    focusablesTempList.clear();
6452                }
6453            } break;
6454            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6455                CharSequence text = getIterableTextForAccessibility();
6456                if (text != null && text.length() > 0) {
6457                    event.setFromIndex(getAccessibilitySelectionStart());
6458                    event.setToIndex(getAccessibilitySelectionEnd());
6459                    event.setItemCount(text.length());
6460                }
6461            } break;
6462        }
6463    }
6464
6465    /**
6466     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6467     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6468     * This method is responsible for obtaining an accessibility node info from a
6469     * pool of reusable instances and calling
6470     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6471     * initialize the former.
6472     * <p>
6473     * Note: The client is responsible for recycling the obtained instance by calling
6474     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6475     * </p>
6476     *
6477     * @return A populated {@link AccessibilityNodeInfo}.
6478     *
6479     * @see AccessibilityNodeInfo
6480     */
6481    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6482        if (mAccessibilityDelegate != null) {
6483            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6484        } else {
6485            return createAccessibilityNodeInfoInternal();
6486        }
6487    }
6488
6489    /**
6490     * @see #createAccessibilityNodeInfo()
6491     *
6492     * @hide
6493     */
6494    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6495        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6496        if (provider != null) {
6497            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6498        } else {
6499            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6500            onInitializeAccessibilityNodeInfo(info);
6501            return info;
6502        }
6503    }
6504
6505    /**
6506     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6507     * The base implementation sets:
6508     * <ul>
6509     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6510     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6511     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6512     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6513     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6514     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6515     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6516     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6517     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6518     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6519     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6520     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6521     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6522     * </ul>
6523     * <p>
6524     * Subclasses should override this method, call the super implementation,
6525     * and set additional attributes.
6526     * </p>
6527     * <p>
6528     * If an {@link AccessibilityDelegate} has been specified via calling
6529     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6530     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6531     * is responsible for handling this call.
6532     * </p>
6533     *
6534     * @param info The instance to initialize.
6535     */
6536    @CallSuper
6537    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6538        if (mAccessibilityDelegate != null) {
6539            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6540        } else {
6541            onInitializeAccessibilityNodeInfoInternal(info);
6542        }
6543    }
6544
6545    /**
6546     * Gets the location of this view in screen coordinates.
6547     *
6548     * @param outRect The output location
6549     * @hide
6550     */
6551    public void getBoundsOnScreen(Rect outRect) {
6552        getBoundsOnScreen(outRect, false);
6553    }
6554
6555    /**
6556     * Gets the location of this view in screen coordinates.
6557     *
6558     * @param outRect The output location
6559     * @param clipToParent Whether to clip child bounds to the parent ones.
6560     * @hide
6561     */
6562    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6563        if (mAttachInfo == null) {
6564            return;
6565        }
6566
6567        RectF position = mAttachInfo.mTmpTransformRect;
6568        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6569
6570        if (!hasIdentityMatrix()) {
6571            getMatrix().mapRect(position);
6572        }
6573
6574        position.offset(mLeft, mTop);
6575
6576        ViewParent parent = mParent;
6577        while (parent instanceof View) {
6578            View parentView = (View) parent;
6579
6580            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6581
6582            if (clipToParent) {
6583                position.left = Math.max(position.left, 0);
6584                position.top = Math.max(position.top, 0);
6585                position.right = Math.min(position.right, parentView.getWidth());
6586                position.bottom = Math.min(position.bottom, parentView.getHeight());
6587            }
6588
6589            if (!parentView.hasIdentityMatrix()) {
6590                parentView.getMatrix().mapRect(position);
6591            }
6592
6593            position.offset(parentView.mLeft, parentView.mTop);
6594
6595            parent = parentView.mParent;
6596        }
6597
6598        if (parent instanceof ViewRootImpl) {
6599            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6600            position.offset(0, -viewRootImpl.mCurScrollY);
6601        }
6602
6603        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6604
6605        outRect.set(Math.round(position.left), Math.round(position.top),
6606                Math.round(position.right), Math.round(position.bottom));
6607    }
6608
6609    /**
6610     * Return the class name of this object to be used for accessibility purposes.
6611     * Subclasses should only override this if they are implementing something that
6612     * should be seen as a completely new class of view when used by accessibility,
6613     * unrelated to the class it is deriving from.  This is used to fill in
6614     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6615     */
6616    public CharSequence getAccessibilityClassName() {
6617        return View.class.getName();
6618    }
6619
6620    /**
6621     * Called when assist structure is being retrieved from a view as part of
6622     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6623     * @param structure Fill in with structured view data.  The default implementation
6624     * fills in all data that can be inferred from the view itself.
6625     */
6626    public void onProvideStructure(ViewStructure structure) {
6627        final int id = mID;
6628        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6629                && (id&0x0000ffff) != 0) {
6630            String pkg, type, entry;
6631            try {
6632                final Resources res = getResources();
6633                entry = res.getResourceEntryName(id);
6634                type = res.getResourceTypeName(id);
6635                pkg = res.getResourcePackageName(id);
6636            } catch (Resources.NotFoundException e) {
6637                entry = type = pkg = null;
6638            }
6639            structure.setId(id, pkg, type, entry);
6640        } else {
6641            structure.setId(id, null, null, null);
6642        }
6643        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6644        if (!hasIdentityMatrix()) {
6645            structure.setTransformation(getMatrix());
6646        }
6647        structure.setElevation(getZ());
6648        structure.setVisibility(getVisibility());
6649        structure.setEnabled(isEnabled());
6650        if (isClickable()) {
6651            structure.setClickable(true);
6652        }
6653        if (isFocusable()) {
6654            structure.setFocusable(true);
6655        }
6656        if (isFocused()) {
6657            structure.setFocused(true);
6658        }
6659        if (isAccessibilityFocused()) {
6660            structure.setAccessibilityFocused(true);
6661        }
6662        if (isSelected()) {
6663            structure.setSelected(true);
6664        }
6665        if (isActivated()) {
6666            structure.setActivated(true);
6667        }
6668        if (isLongClickable()) {
6669            structure.setLongClickable(true);
6670        }
6671        if (this instanceof Checkable) {
6672            structure.setCheckable(true);
6673            if (((Checkable)this).isChecked()) {
6674                structure.setChecked(true);
6675            }
6676        }
6677        if (isContextClickable()) {
6678            structure.setContextClickable(true);
6679        }
6680        structure.setClassName(getAccessibilityClassName().toString());
6681        structure.setContentDescription(getContentDescription());
6682    }
6683
6684    /**
6685     * Called when assist structure is being retrieved from a view as part of
6686     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6687     * generate additional virtual structure under this view.  The defaullt implementation
6688     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6689     * view's virtual accessibility nodes, if any.  You can override this for a more
6690     * optimal implementation providing this data.
6691     */
6692    public void onProvideVirtualStructure(ViewStructure structure) {
6693        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6694        if (provider != null) {
6695            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6696            structure.setChildCount(1);
6697            ViewStructure root = structure.newChild(0);
6698            populateVirtualStructure(root, provider, info);
6699            info.recycle();
6700        }
6701    }
6702
6703    private void populateVirtualStructure(ViewStructure structure,
6704            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6705        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6706                null, null, null);
6707        Rect rect = structure.getTempRect();
6708        info.getBoundsInParent(rect);
6709        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6710        structure.setVisibility(VISIBLE);
6711        structure.setEnabled(info.isEnabled());
6712        if (info.isClickable()) {
6713            structure.setClickable(true);
6714        }
6715        if (info.isFocusable()) {
6716            structure.setFocusable(true);
6717        }
6718        if (info.isFocused()) {
6719            structure.setFocused(true);
6720        }
6721        if (info.isAccessibilityFocused()) {
6722            structure.setAccessibilityFocused(true);
6723        }
6724        if (info.isSelected()) {
6725            structure.setSelected(true);
6726        }
6727        if (info.isLongClickable()) {
6728            structure.setLongClickable(true);
6729        }
6730        if (info.isCheckable()) {
6731            structure.setCheckable(true);
6732            if (info.isChecked()) {
6733                structure.setChecked(true);
6734            }
6735        }
6736        if (info.isContextClickable()) {
6737            structure.setContextClickable(true);
6738        }
6739        CharSequence cname = info.getClassName();
6740        structure.setClassName(cname != null ? cname.toString() : null);
6741        structure.setContentDescription(info.getContentDescription());
6742        if (info.getText() != null || info.getError() != null) {
6743            structure.setText(info.getText(), info.getTextSelectionStart(),
6744                    info.getTextSelectionEnd());
6745        }
6746        final int NCHILDREN = info.getChildCount();
6747        if (NCHILDREN > 0) {
6748            structure.setChildCount(NCHILDREN);
6749            for (int i=0; i<NCHILDREN; i++) {
6750                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6751                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6752                ViewStructure child = structure.newChild(i);
6753                populateVirtualStructure(child, provider, cinfo);
6754                cinfo.recycle();
6755            }
6756        }
6757    }
6758
6759    /**
6760     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6761     * implementation calls {@link #onProvideStructure} and
6762     * {@link #onProvideVirtualStructure}.
6763     */
6764    public void dispatchProvideStructure(ViewStructure structure) {
6765        if (!isAssistBlocked()) {
6766            onProvideStructure(structure);
6767            onProvideVirtualStructure(structure);
6768        } else {
6769            structure.setClassName(getAccessibilityClassName().toString());
6770            structure.setAssistBlocked(true);
6771        }
6772    }
6773
6774    /**
6775     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6776     *
6777     * Note: Called from the default {@link AccessibilityDelegate}.
6778     *
6779     * @hide
6780     */
6781    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6782        if (mAttachInfo == null) {
6783            return;
6784        }
6785
6786        Rect bounds = mAttachInfo.mTmpInvalRect;
6787
6788        getDrawingRect(bounds);
6789        info.setBoundsInParent(bounds);
6790
6791        getBoundsOnScreen(bounds, true);
6792        info.setBoundsInScreen(bounds);
6793
6794        ViewParent parent = getParentForAccessibility();
6795        if (parent instanceof View) {
6796            info.setParent((View) parent);
6797        }
6798
6799        if (mID != View.NO_ID) {
6800            View rootView = getRootView();
6801            if (rootView == null) {
6802                rootView = this;
6803            }
6804
6805            View label = rootView.findLabelForView(this, mID);
6806            if (label != null) {
6807                info.setLabeledBy(label);
6808            }
6809
6810            if ((mAttachInfo.mAccessibilityFetchFlags
6811                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6812                    && Resources.resourceHasPackage(mID)) {
6813                try {
6814                    String viewId = getResources().getResourceName(mID);
6815                    info.setViewIdResourceName(viewId);
6816                } catch (Resources.NotFoundException nfe) {
6817                    /* ignore */
6818                }
6819            }
6820        }
6821
6822        if (mLabelForId != View.NO_ID) {
6823            View rootView = getRootView();
6824            if (rootView == null) {
6825                rootView = this;
6826            }
6827            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6828            if (labeled != null) {
6829                info.setLabelFor(labeled);
6830            }
6831        }
6832
6833        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6834            View rootView = getRootView();
6835            if (rootView == null) {
6836                rootView = this;
6837            }
6838            View next = rootView.findViewInsideOutShouldExist(this,
6839                    mAccessibilityTraversalBeforeId);
6840            if (next != null && next.includeForAccessibility()) {
6841                info.setTraversalBefore(next);
6842            }
6843        }
6844
6845        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6846            View rootView = getRootView();
6847            if (rootView == null) {
6848                rootView = this;
6849            }
6850            View next = rootView.findViewInsideOutShouldExist(this,
6851                    mAccessibilityTraversalAfterId);
6852            if (next != null && next.includeForAccessibility()) {
6853                info.setTraversalAfter(next);
6854            }
6855        }
6856
6857        info.setVisibleToUser(isVisibleToUser());
6858
6859        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6860                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6861            info.setImportantForAccessibility(isImportantForAccessibility());
6862        } else {
6863            info.setImportantForAccessibility(true);
6864        }
6865
6866        info.setPackageName(mContext.getPackageName());
6867        info.setClassName(getAccessibilityClassName());
6868        info.setContentDescription(getContentDescription());
6869
6870        info.setEnabled(isEnabled());
6871        info.setClickable(isClickable());
6872        info.setFocusable(isFocusable());
6873        info.setFocused(isFocused());
6874        info.setAccessibilityFocused(isAccessibilityFocused());
6875        info.setSelected(isSelected());
6876        info.setLongClickable(isLongClickable());
6877        info.setContextClickable(isContextClickable());
6878        info.setLiveRegion(getAccessibilityLiveRegion());
6879
6880        // TODO: These make sense only if we are in an AdapterView but all
6881        // views can be selected. Maybe from accessibility perspective
6882        // we should report as selectable view in an AdapterView.
6883        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6884        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6885
6886        if (isFocusable()) {
6887            if (isFocused()) {
6888                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6889            } else {
6890                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6891            }
6892        }
6893
6894        if (!isAccessibilityFocused()) {
6895            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6896        } else {
6897            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6898        }
6899
6900        if (isClickable() && isEnabled()) {
6901            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6902        }
6903
6904        if (isLongClickable() && isEnabled()) {
6905            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6906        }
6907
6908        if (isContextClickable() && isEnabled()) {
6909            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6910        }
6911
6912        CharSequence text = getIterableTextForAccessibility();
6913        if (text != null && text.length() > 0) {
6914            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6915
6916            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6917            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6918            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6919            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6920                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6921                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6922        }
6923
6924        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6925        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6926    }
6927
6928    /**
6929     * Determine the order in which this view will be drawn relative to its siblings for a11y
6930     *
6931     * @param info The info whose drawing order should be populated
6932     */
6933    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6934        /*
6935         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
6936         * drawing order may not be well-defined, and some Views with custom drawing order may
6937         * not be initialized sufficiently to respond properly getChildDrawingOrder.
6938         */
6939        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
6940            info.setDrawingOrder(0);
6941            return;
6942        }
6943        int drawingOrderInParent = 1;
6944        // Iterate up the hierarchy if parents are not important for a11y
6945        View viewAtDrawingLevel = this;
6946        final ViewParent parent = getParentForAccessibility();
6947        while (viewAtDrawingLevel != parent) {
6948            final ViewParent currentParent = viewAtDrawingLevel.getParent();
6949            if (!(currentParent instanceof ViewGroup)) {
6950                // Should only happen for the Decor
6951                drawingOrderInParent = 0;
6952                break;
6953            } else {
6954                final ViewGroup parentGroup = (ViewGroup) currentParent;
6955                final int childCount = parentGroup.getChildCount();
6956                if (childCount > 1) {
6957                    List<View> preorderedList = parentGroup.buildOrderedChildList();
6958                    if (preorderedList != null) {
6959                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
6960                        for (int i = 0; i < childDrawIndex; i++) {
6961                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
6962                        }
6963                    } else {
6964                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
6965                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
6966                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
6967                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
6968                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
6969                        if (childDrawIndex != 0) {
6970                            for (int i = 0; i < numChildrenToIterate; i++) {
6971                                final int otherDrawIndex = (customOrder ?
6972                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
6973                                if (otherDrawIndex < childDrawIndex) {
6974                                    drawingOrderInParent +=
6975                                            numViewsForAccessibility(parentGroup.getChildAt(i));
6976                                }
6977                            }
6978                        }
6979                    }
6980                }
6981            }
6982            viewAtDrawingLevel = (View) currentParent;
6983        }
6984        info.setDrawingOrder(drawingOrderInParent);
6985    }
6986
6987    private static int numViewsForAccessibility(View view) {
6988        if (view != null) {
6989            if (view.includeForAccessibility()) {
6990                return 1;
6991            } else if (view instanceof ViewGroup) {
6992                return ((ViewGroup) view).getNumChildrenForAccessibility();
6993            }
6994        }
6995        return 0;
6996    }
6997
6998    private View findLabelForView(View view, int labeledId) {
6999        if (mMatchLabelForPredicate == null) {
7000            mMatchLabelForPredicate = new MatchLabelForPredicate();
7001        }
7002        mMatchLabelForPredicate.mLabeledId = labeledId;
7003        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7004    }
7005
7006    /**
7007     * Computes whether this view is visible to the user. Such a view is
7008     * attached, visible, all its predecessors are visible, it is not clipped
7009     * entirely by its predecessors, and has an alpha greater than zero.
7010     *
7011     * @return Whether the view is visible on the screen.
7012     *
7013     * @hide
7014     */
7015    protected boolean isVisibleToUser() {
7016        return isVisibleToUser(null);
7017    }
7018
7019    /**
7020     * Computes whether the given portion of this view is visible to the user.
7021     * Such a view is attached, visible, all its predecessors are visible,
7022     * has an alpha greater than zero, and the specified portion is not
7023     * clipped entirely by its predecessors.
7024     *
7025     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7026     *                    <code>null</code>, and the entire view will be tested in this case.
7027     *                    When <code>true</code> is returned by the function, the actual visible
7028     *                    region will be stored in this parameter; that is, if boundInView is fully
7029     *                    contained within the view, no modification will be made, otherwise regions
7030     *                    outside of the visible area of the view will be clipped.
7031     *
7032     * @return Whether the specified portion of the view is visible on the screen.
7033     *
7034     * @hide
7035     */
7036    protected boolean isVisibleToUser(Rect boundInView) {
7037        if (mAttachInfo != null) {
7038            // Attached to invisible window means this view is not visible.
7039            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7040                return false;
7041            }
7042            // An invisible predecessor or one with alpha zero means
7043            // that this view is not visible to the user.
7044            Object current = this;
7045            while (current instanceof View) {
7046                View view = (View) current;
7047                // We have attach info so this view is attached and there is no
7048                // need to check whether we reach to ViewRootImpl on the way up.
7049                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7050                        view.getVisibility() != VISIBLE) {
7051                    return false;
7052                }
7053                current = view.mParent;
7054            }
7055            // Check if the view is entirely covered by its predecessors.
7056            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7057            Point offset = mAttachInfo.mPoint;
7058            if (!getGlobalVisibleRect(visibleRect, offset)) {
7059                return false;
7060            }
7061            // Check if the visible portion intersects the rectangle of interest.
7062            if (boundInView != null) {
7063                visibleRect.offset(-offset.x, -offset.y);
7064                return boundInView.intersect(visibleRect);
7065            }
7066            return true;
7067        }
7068        return false;
7069    }
7070
7071    /**
7072     * Returns the delegate for implementing accessibility support via
7073     * composition. For more details see {@link AccessibilityDelegate}.
7074     *
7075     * @return The delegate, or null if none set.
7076     *
7077     * @hide
7078     */
7079    public AccessibilityDelegate getAccessibilityDelegate() {
7080        return mAccessibilityDelegate;
7081    }
7082
7083    /**
7084     * Sets a delegate for implementing accessibility support via composition
7085     * (as opposed to inheritance). For more details, see
7086     * {@link AccessibilityDelegate}.
7087     * <p>
7088     * <strong>Note:</strong> On platform versions prior to
7089     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7090     * views in the {@code android.widget.*} package are called <i>before</i>
7091     * host methods. This prevents certain properties such as class name from
7092     * being modified by overriding
7093     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7094     * as any changes will be overwritten by the host class.
7095     * <p>
7096     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7097     * methods are called <i>after</i> host methods, which all properties to be
7098     * modified without being overwritten by the host class.
7099     *
7100     * @param delegate the object to which accessibility method calls should be
7101     *                 delegated
7102     * @see AccessibilityDelegate
7103     */
7104    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7105        mAccessibilityDelegate = delegate;
7106    }
7107
7108    /**
7109     * Gets the provider for managing a virtual view hierarchy rooted at this View
7110     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7111     * that explore the window content.
7112     * <p>
7113     * If this method returns an instance, this instance is responsible for managing
7114     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7115     * View including the one representing the View itself. Similarly the returned
7116     * instance is responsible for performing accessibility actions on any virtual
7117     * view or the root view itself.
7118     * </p>
7119     * <p>
7120     * If an {@link AccessibilityDelegate} has been specified via calling
7121     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7122     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7123     * is responsible for handling this call.
7124     * </p>
7125     *
7126     * @return The provider.
7127     *
7128     * @see AccessibilityNodeProvider
7129     */
7130    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7131        if (mAccessibilityDelegate != null) {
7132            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7133        } else {
7134            return null;
7135        }
7136    }
7137
7138    /**
7139     * Gets the unique identifier of this view on the screen for accessibility purposes.
7140     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7141     *
7142     * @return The view accessibility id.
7143     *
7144     * @hide
7145     */
7146    public int getAccessibilityViewId() {
7147        if (mAccessibilityViewId == NO_ID) {
7148            mAccessibilityViewId = sNextAccessibilityViewId++;
7149        }
7150        return mAccessibilityViewId;
7151    }
7152
7153    /**
7154     * Gets the unique identifier of the window in which this View reseides.
7155     *
7156     * @return The window accessibility id.
7157     *
7158     * @hide
7159     */
7160    public int getAccessibilityWindowId() {
7161        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7162                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7163    }
7164
7165    /**
7166     * Returns the {@link View}'s content description.
7167     * <p>
7168     * <strong>Note:</strong> Do not override this method, as it will have no
7169     * effect on the content description presented to accessibility services.
7170     * You must call {@link #setContentDescription(CharSequence)} to modify the
7171     * content description.
7172     *
7173     * @return the content description
7174     * @see #setContentDescription(CharSequence)
7175     * @attr ref android.R.styleable#View_contentDescription
7176     */
7177    @ViewDebug.ExportedProperty(category = "accessibility")
7178    public CharSequence getContentDescription() {
7179        return mContentDescription;
7180    }
7181
7182    /**
7183     * Sets the {@link View}'s content description.
7184     * <p>
7185     * A content description briefly describes the view and is primarily used
7186     * for accessibility support to determine how a view should be presented to
7187     * the user. In the case of a view with no textual representation, such as
7188     * {@link android.widget.ImageButton}, a useful content description
7189     * explains what the view does. For example, an image button with a phone
7190     * icon that is used to place a call may use "Call" as its content
7191     * description. An image of a floppy disk that is used to save a file may
7192     * use "Save".
7193     *
7194     * @param contentDescription The content description.
7195     * @see #getContentDescription()
7196     * @attr ref android.R.styleable#View_contentDescription
7197     */
7198    @RemotableViewMethod
7199    public void setContentDescription(CharSequence contentDescription) {
7200        if (mContentDescription == null) {
7201            if (contentDescription == null) {
7202                return;
7203            }
7204        } else if (mContentDescription.equals(contentDescription)) {
7205            return;
7206        }
7207        mContentDescription = contentDescription;
7208        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7209        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7210            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7211            notifySubtreeAccessibilityStateChangedIfNeeded();
7212        } else {
7213            notifyViewAccessibilityStateChangedIfNeeded(
7214                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7215        }
7216    }
7217
7218    /**
7219     * Sets the id of a view before which this one is visited in accessibility traversal.
7220     * A screen-reader must visit the content of this view before the content of the one
7221     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7222     * will traverse the entire content of B before traversing the entire content of A,
7223     * regardles of what traversal strategy it is using.
7224     * <p>
7225     * Views that do not have specified before/after relationships are traversed in order
7226     * determined by the screen-reader.
7227     * </p>
7228     * <p>
7229     * Setting that this view is before a view that is not important for accessibility
7230     * or if this view is not important for accessibility will have no effect as the
7231     * screen-reader is not aware of unimportant views.
7232     * </p>
7233     *
7234     * @param beforeId The id of a view this one precedes in accessibility traversal.
7235     *
7236     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7237     *
7238     * @see #setImportantForAccessibility(int)
7239     */
7240    @RemotableViewMethod
7241    public void setAccessibilityTraversalBefore(int beforeId) {
7242        if (mAccessibilityTraversalBeforeId == beforeId) {
7243            return;
7244        }
7245        mAccessibilityTraversalBeforeId = beforeId;
7246        notifyViewAccessibilityStateChangedIfNeeded(
7247                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7248    }
7249
7250    /**
7251     * Gets the id of a view before which this one is visited in accessibility traversal.
7252     *
7253     * @return The id of a view this one precedes in accessibility traversal if
7254     *         specified, otherwise {@link #NO_ID}.
7255     *
7256     * @see #setAccessibilityTraversalBefore(int)
7257     */
7258    public int getAccessibilityTraversalBefore() {
7259        return mAccessibilityTraversalBeforeId;
7260    }
7261
7262    /**
7263     * Sets the id of a view after which this one is visited in accessibility traversal.
7264     * A screen-reader must visit the content of the other view before the content of this
7265     * one. For example, if view B is set to be after view A, then a screen-reader
7266     * will traverse the entire content of A before traversing the entire content of B,
7267     * regardles of what traversal strategy it is using.
7268     * <p>
7269     * Views that do not have specified before/after relationships are traversed in order
7270     * determined by the screen-reader.
7271     * </p>
7272     * <p>
7273     * Setting that this view is after a view that is not important for accessibility
7274     * or if this view is not important for accessibility will have no effect as the
7275     * screen-reader is not aware of unimportant views.
7276     * </p>
7277     *
7278     * @param afterId The id of a view this one succedees in accessibility traversal.
7279     *
7280     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7281     *
7282     * @see #setImportantForAccessibility(int)
7283     */
7284    @RemotableViewMethod
7285    public void setAccessibilityTraversalAfter(int afterId) {
7286        if (mAccessibilityTraversalAfterId == afterId) {
7287            return;
7288        }
7289        mAccessibilityTraversalAfterId = afterId;
7290        notifyViewAccessibilityStateChangedIfNeeded(
7291                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7292    }
7293
7294    /**
7295     * Gets the id of a view after which this one is visited in accessibility traversal.
7296     *
7297     * @return The id of a view this one succeedes in accessibility traversal if
7298     *         specified, otherwise {@link #NO_ID}.
7299     *
7300     * @see #setAccessibilityTraversalAfter(int)
7301     */
7302    public int getAccessibilityTraversalAfter() {
7303        return mAccessibilityTraversalAfterId;
7304    }
7305
7306    /**
7307     * Gets the id of a view for which this view serves as a label for
7308     * accessibility purposes.
7309     *
7310     * @return The labeled view id.
7311     */
7312    @ViewDebug.ExportedProperty(category = "accessibility")
7313    public int getLabelFor() {
7314        return mLabelForId;
7315    }
7316
7317    /**
7318     * Sets the id of a view for which this view serves as a label for
7319     * accessibility purposes.
7320     *
7321     * @param id The labeled view id.
7322     */
7323    @RemotableViewMethod
7324    public void setLabelFor(@IdRes int id) {
7325        if (mLabelForId == id) {
7326            return;
7327        }
7328        mLabelForId = id;
7329        if (mLabelForId != View.NO_ID
7330                && mID == View.NO_ID) {
7331            mID = generateViewId();
7332        }
7333        notifyViewAccessibilityStateChangedIfNeeded(
7334                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7335    }
7336
7337    /**
7338     * Invoked whenever this view loses focus, either by losing window focus or by losing
7339     * focus within its window. This method can be used to clear any state tied to the
7340     * focus. For instance, if a button is held pressed with the trackball and the window
7341     * loses focus, this method can be used to cancel the press.
7342     *
7343     * Subclasses of View overriding this method should always call super.onFocusLost().
7344     *
7345     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7346     * @see #onWindowFocusChanged(boolean)
7347     *
7348     * @hide pending API council approval
7349     */
7350    @CallSuper
7351    protected void onFocusLost() {
7352        resetPressedState();
7353    }
7354
7355    private void resetPressedState() {
7356        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7357            return;
7358        }
7359
7360        if (isPressed()) {
7361            setPressed(false);
7362
7363            if (!mHasPerformedLongPress) {
7364                removeLongPressCallback();
7365            }
7366        }
7367    }
7368
7369    /**
7370     * Returns true if this view has focus
7371     *
7372     * @return True if this view has focus, false otherwise.
7373     */
7374    @ViewDebug.ExportedProperty(category = "focus")
7375    public boolean isFocused() {
7376        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7377    }
7378
7379    /**
7380     * Find the view in the hierarchy rooted at this view that currently has
7381     * focus.
7382     *
7383     * @return The view that currently has focus, or null if no focused view can
7384     *         be found.
7385     */
7386    public View findFocus() {
7387        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7388    }
7389
7390    /**
7391     * Indicates whether this view is one of the set of scrollable containers in
7392     * its window.
7393     *
7394     * @return whether this view is one of the set of scrollable containers in
7395     * its window
7396     *
7397     * @attr ref android.R.styleable#View_isScrollContainer
7398     */
7399    public boolean isScrollContainer() {
7400        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7401    }
7402
7403    /**
7404     * Change whether this view is one of the set of scrollable containers in
7405     * its window.  This will be used to determine whether the window can
7406     * resize or must pan when a soft input area is open -- scrollable
7407     * containers allow the window to use resize mode since the container
7408     * will appropriately shrink.
7409     *
7410     * @attr ref android.R.styleable#View_isScrollContainer
7411     */
7412    public void setScrollContainer(boolean isScrollContainer) {
7413        if (isScrollContainer) {
7414            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7415                mAttachInfo.mScrollContainers.add(this);
7416                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7417            }
7418            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7419        } else {
7420            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7421                mAttachInfo.mScrollContainers.remove(this);
7422            }
7423            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7424        }
7425    }
7426
7427    /**
7428     * Returns the quality of the drawing cache.
7429     *
7430     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7431     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7432     *
7433     * @see #setDrawingCacheQuality(int)
7434     * @see #setDrawingCacheEnabled(boolean)
7435     * @see #isDrawingCacheEnabled()
7436     *
7437     * @attr ref android.R.styleable#View_drawingCacheQuality
7438     */
7439    @DrawingCacheQuality
7440    public int getDrawingCacheQuality() {
7441        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7442    }
7443
7444    /**
7445     * Set the drawing cache quality of this view. This value is used only when the
7446     * drawing cache is enabled
7447     *
7448     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7449     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7450     *
7451     * @see #getDrawingCacheQuality()
7452     * @see #setDrawingCacheEnabled(boolean)
7453     * @see #isDrawingCacheEnabled()
7454     *
7455     * @attr ref android.R.styleable#View_drawingCacheQuality
7456     */
7457    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7458        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7459    }
7460
7461    /**
7462     * Returns whether the screen should remain on, corresponding to the current
7463     * value of {@link #KEEP_SCREEN_ON}.
7464     *
7465     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7466     *
7467     * @see #setKeepScreenOn(boolean)
7468     *
7469     * @attr ref android.R.styleable#View_keepScreenOn
7470     */
7471    public boolean getKeepScreenOn() {
7472        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7473    }
7474
7475    /**
7476     * Controls whether the screen should remain on, modifying the
7477     * value of {@link #KEEP_SCREEN_ON}.
7478     *
7479     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7480     *
7481     * @see #getKeepScreenOn()
7482     *
7483     * @attr ref android.R.styleable#View_keepScreenOn
7484     */
7485    public void setKeepScreenOn(boolean keepScreenOn) {
7486        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7487    }
7488
7489    /**
7490     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7491     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7492     *
7493     * @attr ref android.R.styleable#View_nextFocusLeft
7494     */
7495    public int getNextFocusLeftId() {
7496        return mNextFocusLeftId;
7497    }
7498
7499    /**
7500     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7501     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7502     * decide automatically.
7503     *
7504     * @attr ref android.R.styleable#View_nextFocusLeft
7505     */
7506    public void setNextFocusLeftId(int nextFocusLeftId) {
7507        mNextFocusLeftId = nextFocusLeftId;
7508    }
7509
7510    /**
7511     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7512     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7513     *
7514     * @attr ref android.R.styleable#View_nextFocusRight
7515     */
7516    public int getNextFocusRightId() {
7517        return mNextFocusRightId;
7518    }
7519
7520    /**
7521     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7522     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7523     * decide automatically.
7524     *
7525     * @attr ref android.R.styleable#View_nextFocusRight
7526     */
7527    public void setNextFocusRightId(int nextFocusRightId) {
7528        mNextFocusRightId = nextFocusRightId;
7529    }
7530
7531    /**
7532     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7533     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7534     *
7535     * @attr ref android.R.styleable#View_nextFocusUp
7536     */
7537    public int getNextFocusUpId() {
7538        return mNextFocusUpId;
7539    }
7540
7541    /**
7542     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7543     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7544     * decide automatically.
7545     *
7546     * @attr ref android.R.styleable#View_nextFocusUp
7547     */
7548    public void setNextFocusUpId(int nextFocusUpId) {
7549        mNextFocusUpId = nextFocusUpId;
7550    }
7551
7552    /**
7553     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7554     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7555     *
7556     * @attr ref android.R.styleable#View_nextFocusDown
7557     */
7558    public int getNextFocusDownId() {
7559        return mNextFocusDownId;
7560    }
7561
7562    /**
7563     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7564     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7565     * decide automatically.
7566     *
7567     * @attr ref android.R.styleable#View_nextFocusDown
7568     */
7569    public void setNextFocusDownId(int nextFocusDownId) {
7570        mNextFocusDownId = nextFocusDownId;
7571    }
7572
7573    /**
7574     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7575     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7576     *
7577     * @attr ref android.R.styleable#View_nextFocusForward
7578     */
7579    public int getNextFocusForwardId() {
7580        return mNextFocusForwardId;
7581    }
7582
7583    /**
7584     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7585     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7586     * decide automatically.
7587     *
7588     * @attr ref android.R.styleable#View_nextFocusForward
7589     */
7590    public void setNextFocusForwardId(int nextFocusForwardId) {
7591        mNextFocusForwardId = nextFocusForwardId;
7592    }
7593
7594    /**
7595     * Returns the visibility of this view and all of its ancestors
7596     *
7597     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7598     */
7599    public boolean isShown() {
7600        View current = this;
7601        //noinspection ConstantConditions
7602        do {
7603            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7604                return false;
7605            }
7606            ViewParent parent = current.mParent;
7607            if (parent == null) {
7608                return false; // We are not attached to the view root
7609            }
7610            if (!(parent instanceof View)) {
7611                return true;
7612            }
7613            current = (View) parent;
7614        } while (current != null);
7615
7616        return false;
7617    }
7618
7619    /**
7620     * Called by the view hierarchy when the content insets for a window have
7621     * changed, to allow it to adjust its content to fit within those windows.
7622     * The content insets tell you the space that the status bar, input method,
7623     * and other system windows infringe on the application's window.
7624     *
7625     * <p>You do not normally need to deal with this function, since the default
7626     * window decoration given to applications takes care of applying it to the
7627     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7628     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7629     * and your content can be placed under those system elements.  You can then
7630     * use this method within your view hierarchy if you have parts of your UI
7631     * which you would like to ensure are not being covered.
7632     *
7633     * <p>The default implementation of this method simply applies the content
7634     * insets to the view's padding, consuming that content (modifying the
7635     * insets to be 0), and returning true.  This behavior is off by default, but can
7636     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7637     *
7638     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7639     * insets object is propagated down the hierarchy, so any changes made to it will
7640     * be seen by all following views (including potentially ones above in
7641     * the hierarchy since this is a depth-first traversal).  The first view
7642     * that returns true will abort the entire traversal.
7643     *
7644     * <p>The default implementation works well for a situation where it is
7645     * used with a container that covers the entire window, allowing it to
7646     * apply the appropriate insets to its content on all edges.  If you need
7647     * a more complicated layout (such as two different views fitting system
7648     * windows, one on the top of the window, and one on the bottom),
7649     * you can override the method and handle the insets however you would like.
7650     * Note that the insets provided by the framework are always relative to the
7651     * far edges of the window, not accounting for the location of the called view
7652     * within that window.  (In fact when this method is called you do not yet know
7653     * where the layout will place the view, as it is done before layout happens.)
7654     *
7655     * <p>Note: unlike many View methods, there is no dispatch phase to this
7656     * call.  If you are overriding it in a ViewGroup and want to allow the
7657     * call to continue to your children, you must be sure to call the super
7658     * implementation.
7659     *
7660     * <p>Here is a sample layout that makes use of fitting system windows
7661     * to have controls for a video view placed inside of the window decorations
7662     * that it hides and shows.  This can be used with code like the second
7663     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7664     *
7665     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7666     *
7667     * @param insets Current content insets of the window.  Prior to
7668     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7669     * the insets or else you and Android will be unhappy.
7670     *
7671     * @return {@code true} if this view applied the insets and it should not
7672     * continue propagating further down the hierarchy, {@code false} otherwise.
7673     * @see #getFitsSystemWindows()
7674     * @see #setFitsSystemWindows(boolean)
7675     * @see #setSystemUiVisibility(int)
7676     *
7677     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7678     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7679     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7680     * to implement handling their own insets.
7681     */
7682    protected boolean fitSystemWindows(Rect insets) {
7683        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7684            if (insets == null) {
7685                // Null insets by definition have already been consumed.
7686                // This call cannot apply insets since there are none to apply,
7687                // so return false.
7688                return false;
7689            }
7690            // If we're not in the process of dispatching the newer apply insets call,
7691            // that means we're not in the compatibility path. Dispatch into the newer
7692            // apply insets path and take things from there.
7693            try {
7694                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7695                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7696            } finally {
7697                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7698            }
7699        } else {
7700            // We're being called from the newer apply insets path.
7701            // Perform the standard fallback behavior.
7702            return fitSystemWindowsInt(insets);
7703        }
7704    }
7705
7706    private boolean fitSystemWindowsInt(Rect insets) {
7707        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7708            mUserPaddingStart = UNDEFINED_PADDING;
7709            mUserPaddingEnd = UNDEFINED_PADDING;
7710            Rect localInsets = sThreadLocal.get();
7711            if (localInsets == null) {
7712                localInsets = new Rect();
7713                sThreadLocal.set(localInsets);
7714            }
7715            boolean res = computeFitSystemWindows(insets, localInsets);
7716            mUserPaddingLeftInitial = localInsets.left;
7717            mUserPaddingRightInitial = localInsets.right;
7718            internalSetPadding(localInsets.left, localInsets.top,
7719                    localInsets.right, localInsets.bottom);
7720            return res;
7721        }
7722        return false;
7723    }
7724
7725    /**
7726     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7727     *
7728     * <p>This method should be overridden by views that wish to apply a policy different from or
7729     * in addition to the default behavior. Clients that wish to force a view subtree
7730     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7731     *
7732     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7733     * it will be called during dispatch instead of this method. The listener may optionally
7734     * call this method from its own implementation if it wishes to apply the view's default
7735     * insets policy in addition to its own.</p>
7736     *
7737     * <p>Implementations of this method should either return the insets parameter unchanged
7738     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7739     * that this view applied itself. This allows new inset types added in future platform
7740     * versions to pass through existing implementations unchanged without being erroneously
7741     * consumed.</p>
7742     *
7743     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7744     * property is set then the view will consume the system window insets and apply them
7745     * as padding for the view.</p>
7746     *
7747     * @param insets Insets to apply
7748     * @return The supplied insets with any applied insets consumed
7749     */
7750    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7751        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7752            // We weren't called from within a direct call to fitSystemWindows,
7753            // call into it as a fallback in case we're in a class that overrides it
7754            // and has logic to perform.
7755            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7756                return insets.consumeSystemWindowInsets();
7757            }
7758        } else {
7759            // We were called from within a direct call to fitSystemWindows.
7760            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7761                return insets.consumeSystemWindowInsets();
7762            }
7763        }
7764        return insets;
7765    }
7766
7767    /**
7768     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7769     * window insets to this view. The listener's
7770     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7771     * method will be called instead of the view's
7772     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7773     *
7774     * @param listener Listener to set
7775     *
7776     * @see #onApplyWindowInsets(WindowInsets)
7777     */
7778    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7779        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7780    }
7781
7782    /**
7783     * Request to apply the given window insets to this view or another view in its subtree.
7784     *
7785     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7786     * obscured by window decorations or overlays. This can include the status and navigation bars,
7787     * action bars, input methods and more. New inset categories may be added in the future.
7788     * The method returns the insets provided minus any that were applied by this view or its
7789     * children.</p>
7790     *
7791     * <p>Clients wishing to provide custom behavior should override the
7792     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7793     * {@link OnApplyWindowInsetsListener} via the
7794     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7795     * method.</p>
7796     *
7797     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7798     * </p>
7799     *
7800     * @param insets Insets to apply
7801     * @return The provided insets minus the insets that were consumed
7802     */
7803    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7804        try {
7805            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7806            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7807                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7808            } else {
7809                return onApplyWindowInsets(insets);
7810            }
7811        } finally {
7812            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7813        }
7814    }
7815
7816    /**
7817     * Compute the view's coordinate within the surface.
7818     *
7819     * <p>Computes the coordinates of this view in its surface. The argument
7820     * must be an array of two integers. After the method returns, the array
7821     * contains the x and y location in that order.</p>
7822     * @hide
7823     * @param location an array of two integers in which to hold the coordinates
7824     */
7825    public void getLocationInSurface(@Size(2) int[] location) {
7826        getLocationInWindow(location);
7827        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7828            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7829            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7830        }
7831    }
7832
7833    /**
7834     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7835     * only available if the view is attached.
7836     *
7837     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7838     */
7839    public WindowInsets getRootWindowInsets() {
7840        if (mAttachInfo != null) {
7841            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7842        }
7843        return null;
7844    }
7845
7846    /**
7847     * @hide Compute the insets that should be consumed by this view and the ones
7848     * that should propagate to those under it.
7849     */
7850    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7851        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7852                || mAttachInfo == null
7853                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7854                        && !mAttachInfo.mOverscanRequested)) {
7855            outLocalInsets.set(inoutInsets);
7856            inoutInsets.set(0, 0, 0, 0);
7857            return true;
7858        } else {
7859            // The application wants to take care of fitting system window for
7860            // the content...  however we still need to take care of any overscan here.
7861            final Rect overscan = mAttachInfo.mOverscanInsets;
7862            outLocalInsets.set(overscan);
7863            inoutInsets.left -= overscan.left;
7864            inoutInsets.top -= overscan.top;
7865            inoutInsets.right -= overscan.right;
7866            inoutInsets.bottom -= overscan.bottom;
7867            return false;
7868        }
7869    }
7870
7871    /**
7872     * Compute insets that should be consumed by this view and the ones that should propagate
7873     * to those under it.
7874     *
7875     * @param in Insets currently being processed by this View, likely received as a parameter
7876     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7877     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7878     *                       by this view
7879     * @return Insets that should be passed along to views under this one
7880     */
7881    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7882        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7883                || mAttachInfo == null
7884                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7885            outLocalInsets.set(in.getSystemWindowInsets());
7886            return in.consumeSystemWindowInsets();
7887        } else {
7888            outLocalInsets.set(0, 0, 0, 0);
7889            return in;
7890        }
7891    }
7892
7893    /**
7894     * Sets whether or not this view should account for system screen decorations
7895     * such as the status bar and inset its content; that is, controlling whether
7896     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7897     * executed.  See that method for more details.
7898     *
7899     * <p>Note that if you are providing your own implementation of
7900     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7901     * flag to true -- your implementation will be overriding the default
7902     * implementation that checks this flag.
7903     *
7904     * @param fitSystemWindows If true, then the default implementation of
7905     * {@link #fitSystemWindows(Rect)} will be executed.
7906     *
7907     * @attr ref android.R.styleable#View_fitsSystemWindows
7908     * @see #getFitsSystemWindows()
7909     * @see #fitSystemWindows(Rect)
7910     * @see #setSystemUiVisibility(int)
7911     */
7912    public void setFitsSystemWindows(boolean fitSystemWindows) {
7913        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7914    }
7915
7916    /**
7917     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7918     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7919     * will be executed.
7920     *
7921     * @return {@code true} if the default implementation of
7922     * {@link #fitSystemWindows(Rect)} will be executed.
7923     *
7924     * @attr ref android.R.styleable#View_fitsSystemWindows
7925     * @see #setFitsSystemWindows(boolean)
7926     * @see #fitSystemWindows(Rect)
7927     * @see #setSystemUiVisibility(int)
7928     */
7929    @ViewDebug.ExportedProperty
7930    public boolean getFitsSystemWindows() {
7931        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7932    }
7933
7934    /** @hide */
7935    public boolean fitsSystemWindows() {
7936        return getFitsSystemWindows();
7937    }
7938
7939    /**
7940     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7941     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7942     */
7943    public void requestFitSystemWindows() {
7944        if (mParent != null) {
7945            mParent.requestFitSystemWindows();
7946        }
7947    }
7948
7949    /**
7950     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7951     */
7952    public void requestApplyInsets() {
7953        requestFitSystemWindows();
7954    }
7955
7956    /**
7957     * For use by PhoneWindow to make its own system window fitting optional.
7958     * @hide
7959     */
7960    public void makeOptionalFitsSystemWindows() {
7961        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7962    }
7963
7964    /**
7965     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7966     * treat them as such.
7967     * @hide
7968     */
7969    public void getOutsets(Rect outOutsetRect) {
7970        if (mAttachInfo != null) {
7971            outOutsetRect.set(mAttachInfo.mOutsets);
7972        } else {
7973            outOutsetRect.setEmpty();
7974        }
7975    }
7976
7977    /**
7978     * Returns the visibility status for this view.
7979     *
7980     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7981     * @attr ref android.R.styleable#View_visibility
7982     */
7983    @ViewDebug.ExportedProperty(mapping = {
7984        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7985        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7986        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7987    })
7988    @Visibility
7989    public int getVisibility() {
7990        return mViewFlags & VISIBILITY_MASK;
7991    }
7992
7993    /**
7994     * Set the enabled state of this view.
7995     *
7996     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7997     * @attr ref android.R.styleable#View_visibility
7998     */
7999    @RemotableViewMethod
8000    public void setVisibility(@Visibility int visibility) {
8001        setFlags(visibility, VISIBILITY_MASK);
8002    }
8003
8004    /**
8005     * Returns the enabled status for this view. The interpretation of the
8006     * enabled state varies by subclass.
8007     *
8008     * @return True if this view is enabled, false otherwise.
8009     */
8010    @ViewDebug.ExportedProperty
8011    public boolean isEnabled() {
8012        return (mViewFlags & ENABLED_MASK) == ENABLED;
8013    }
8014
8015    /**
8016     * Set the enabled state of this view. The interpretation of the enabled
8017     * state varies by subclass.
8018     *
8019     * @param enabled True if this view is enabled, false otherwise.
8020     */
8021    @RemotableViewMethod
8022    public void setEnabled(boolean enabled) {
8023        if (enabled == isEnabled()) return;
8024
8025        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8026
8027        /*
8028         * The View most likely has to change its appearance, so refresh
8029         * the drawable state.
8030         */
8031        refreshDrawableState();
8032
8033        // Invalidate too, since the default behavior for views is to be
8034        // be drawn at 50% alpha rather than to change the drawable.
8035        invalidate(true);
8036
8037        if (!enabled) {
8038            cancelPendingInputEvents();
8039        }
8040    }
8041
8042    /**
8043     * Set whether this view can receive the focus.
8044     *
8045     * Setting this to false will also ensure that this view is not focusable
8046     * in touch mode.
8047     *
8048     * @param focusable If true, this view can receive the focus.
8049     *
8050     * @see #setFocusableInTouchMode(boolean)
8051     * @attr ref android.R.styleable#View_focusable
8052     */
8053    public void setFocusable(boolean focusable) {
8054        if (!focusable) {
8055            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8056        }
8057        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8058    }
8059
8060    /**
8061     * Set whether this view can receive focus while in touch mode.
8062     *
8063     * Setting this to true will also ensure that this view is focusable.
8064     *
8065     * @param focusableInTouchMode If true, this view can receive the focus while
8066     *   in touch mode.
8067     *
8068     * @see #setFocusable(boolean)
8069     * @attr ref android.R.styleable#View_focusableInTouchMode
8070     */
8071    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8072        // Focusable in touch mode should always be set before the focusable flag
8073        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8074        // which, in touch mode, will not successfully request focus on this view
8075        // because the focusable in touch mode flag is not set
8076        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8077        if (focusableInTouchMode) {
8078            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8079        }
8080    }
8081
8082    /**
8083     * Set whether this view should have sound effects enabled for events such as
8084     * clicking and touching.
8085     *
8086     * <p>You may wish to disable sound effects for a view if you already play sounds,
8087     * for instance, a dial key that plays dtmf tones.
8088     *
8089     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8090     * @see #isSoundEffectsEnabled()
8091     * @see #playSoundEffect(int)
8092     * @attr ref android.R.styleable#View_soundEffectsEnabled
8093     */
8094    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8095        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8096    }
8097
8098    /**
8099     * @return whether this view should have sound effects enabled for events such as
8100     *     clicking and touching.
8101     *
8102     * @see #setSoundEffectsEnabled(boolean)
8103     * @see #playSoundEffect(int)
8104     * @attr ref android.R.styleable#View_soundEffectsEnabled
8105     */
8106    @ViewDebug.ExportedProperty
8107    public boolean isSoundEffectsEnabled() {
8108        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8109    }
8110
8111    /**
8112     * Set whether this view should have haptic feedback for events such as
8113     * long presses.
8114     *
8115     * <p>You may wish to disable haptic feedback if your view already controls
8116     * its own haptic feedback.
8117     *
8118     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8119     * @see #isHapticFeedbackEnabled()
8120     * @see #performHapticFeedback(int)
8121     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8122     */
8123    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8124        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8125    }
8126
8127    /**
8128     * @return whether this view should have haptic feedback enabled for events
8129     * long presses.
8130     *
8131     * @see #setHapticFeedbackEnabled(boolean)
8132     * @see #performHapticFeedback(int)
8133     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8134     */
8135    @ViewDebug.ExportedProperty
8136    public boolean isHapticFeedbackEnabled() {
8137        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8138    }
8139
8140    /**
8141     * Returns the layout direction for this view.
8142     *
8143     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8144     *   {@link #LAYOUT_DIRECTION_RTL},
8145     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8146     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8147     *
8148     * @attr ref android.R.styleable#View_layoutDirection
8149     *
8150     * @hide
8151     */
8152    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8153        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8154        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8155        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8156        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8157    })
8158    @LayoutDir
8159    public int getRawLayoutDirection() {
8160        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8161    }
8162
8163    /**
8164     * Set the layout direction for this view. This will propagate a reset of layout direction
8165     * resolution to the view's children and resolve layout direction for this view.
8166     *
8167     * @param layoutDirection the layout direction to set. Should be one of:
8168     *
8169     * {@link #LAYOUT_DIRECTION_LTR},
8170     * {@link #LAYOUT_DIRECTION_RTL},
8171     * {@link #LAYOUT_DIRECTION_INHERIT},
8172     * {@link #LAYOUT_DIRECTION_LOCALE}.
8173     *
8174     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8175     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8176     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8177     *
8178     * @attr ref android.R.styleable#View_layoutDirection
8179     */
8180    @RemotableViewMethod
8181    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8182        if (getRawLayoutDirection() != layoutDirection) {
8183            // Reset the current layout direction and the resolved one
8184            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8185            resetRtlProperties();
8186            // Set the new layout direction (filtered)
8187            mPrivateFlags2 |=
8188                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8189            // We need to resolve all RTL properties as they all depend on layout direction
8190            resolveRtlPropertiesIfNeeded();
8191            requestLayout();
8192            invalidate(true);
8193        }
8194    }
8195
8196    /**
8197     * Returns the resolved layout direction for this view.
8198     *
8199     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8200     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8201     *
8202     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8203     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8204     *
8205     * @attr ref android.R.styleable#View_layoutDirection
8206     */
8207    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8208        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8209        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8210    })
8211    @ResolvedLayoutDir
8212    public int getLayoutDirection() {
8213        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8214        if (targetSdkVersion < JELLY_BEAN_MR1) {
8215            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8216            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8217        }
8218        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8219                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8220    }
8221
8222    /**
8223     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8224     * layout attribute and/or the inherited value from the parent
8225     *
8226     * @return true if the layout is right-to-left.
8227     *
8228     * @hide
8229     */
8230    @ViewDebug.ExportedProperty(category = "layout")
8231    public boolean isLayoutRtl() {
8232        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8233    }
8234
8235    /**
8236     * Indicates whether the view is currently tracking transient state that the
8237     * app should not need to concern itself with saving and restoring, but that
8238     * the framework should take special note to preserve when possible.
8239     *
8240     * <p>A view with transient state cannot be trivially rebound from an external
8241     * data source, such as an adapter binding item views in a list. This may be
8242     * because the view is performing an animation, tracking user selection
8243     * of content, or similar.</p>
8244     *
8245     * @return true if the view has transient state
8246     */
8247    @ViewDebug.ExportedProperty(category = "layout")
8248    public boolean hasTransientState() {
8249        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8250    }
8251
8252    /**
8253     * Set whether this view is currently tracking transient state that the
8254     * framework should attempt to preserve when possible. This flag is reference counted,
8255     * so every call to setHasTransientState(true) should be paired with a later call
8256     * to setHasTransientState(false).
8257     *
8258     * <p>A view with transient state cannot be trivially rebound from an external
8259     * data source, such as an adapter binding item views in a list. This may be
8260     * because the view is performing an animation, tracking user selection
8261     * of content, or similar.</p>
8262     *
8263     * @param hasTransientState true if this view has transient state
8264     */
8265    public void setHasTransientState(boolean hasTransientState) {
8266        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8267                mTransientStateCount - 1;
8268        if (mTransientStateCount < 0) {
8269            mTransientStateCount = 0;
8270            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8271                    "unmatched pair of setHasTransientState calls");
8272        } else if ((hasTransientState && mTransientStateCount == 1) ||
8273                (!hasTransientState && mTransientStateCount == 0)) {
8274            // update flag if we've just incremented up from 0 or decremented down to 0
8275            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8276                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8277            if (mParent != null) {
8278                try {
8279                    mParent.childHasTransientStateChanged(this, hasTransientState);
8280                } catch (AbstractMethodError e) {
8281                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8282                            " does not fully implement ViewParent", e);
8283                }
8284            }
8285        }
8286    }
8287
8288    /**
8289     * Returns true if this view is currently attached to a window.
8290     */
8291    public boolean isAttachedToWindow() {
8292        return mAttachInfo != null;
8293    }
8294
8295    /**
8296     * Returns true if this view has been through at least one layout since it
8297     * was last attached to or detached from a window.
8298     */
8299    public boolean isLaidOut() {
8300        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8301    }
8302
8303    /**
8304     * If this view doesn't do any drawing on its own, set this flag to
8305     * allow further optimizations. By default, this flag is not set on
8306     * View, but could be set on some View subclasses such as ViewGroup.
8307     *
8308     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8309     * you should clear this flag.
8310     *
8311     * @param willNotDraw whether or not this View draw on its own
8312     */
8313    public void setWillNotDraw(boolean willNotDraw) {
8314        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8315    }
8316
8317    /**
8318     * Returns whether or not this View draws on its own.
8319     *
8320     * @return true if this view has nothing to draw, false otherwise
8321     */
8322    @ViewDebug.ExportedProperty(category = "drawing")
8323    public boolean willNotDraw() {
8324        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8325    }
8326
8327    /**
8328     * When a View's drawing cache is enabled, drawing is redirected to an
8329     * offscreen bitmap. Some views, like an ImageView, must be able to
8330     * bypass this mechanism if they already draw a single bitmap, to avoid
8331     * unnecessary usage of the memory.
8332     *
8333     * @param willNotCacheDrawing true if this view does not cache its
8334     *        drawing, false otherwise
8335     */
8336    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8337        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8338    }
8339
8340    /**
8341     * Returns whether or not this View can cache its drawing or not.
8342     *
8343     * @return true if this view does not cache its drawing, false otherwise
8344     */
8345    @ViewDebug.ExportedProperty(category = "drawing")
8346    public boolean willNotCacheDrawing() {
8347        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8348    }
8349
8350    /**
8351     * Indicates whether this view reacts to click events or not.
8352     *
8353     * @return true if the view is clickable, false otherwise
8354     *
8355     * @see #setClickable(boolean)
8356     * @attr ref android.R.styleable#View_clickable
8357     */
8358    @ViewDebug.ExportedProperty
8359    public boolean isClickable() {
8360        return (mViewFlags & CLICKABLE) == CLICKABLE;
8361    }
8362
8363    /**
8364     * Enables or disables click events for this view. When a view
8365     * is clickable it will change its state to "pressed" on every click.
8366     * Subclasses should set the view clickable to visually react to
8367     * user's clicks.
8368     *
8369     * @param clickable true to make the view clickable, false otherwise
8370     *
8371     * @see #isClickable()
8372     * @attr ref android.R.styleable#View_clickable
8373     */
8374    public void setClickable(boolean clickable) {
8375        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8376    }
8377
8378    /**
8379     * Indicates whether this view reacts to long click events or not.
8380     *
8381     * @return true if the view is long clickable, false otherwise
8382     *
8383     * @see #setLongClickable(boolean)
8384     * @attr ref android.R.styleable#View_longClickable
8385     */
8386    public boolean isLongClickable() {
8387        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8388    }
8389
8390    /**
8391     * Enables or disables long click events for this view. When a view is long
8392     * clickable it reacts to the user holding down the button for a longer
8393     * duration than a tap. This event can either launch the listener or a
8394     * context menu.
8395     *
8396     * @param longClickable true to make the view long clickable, false otherwise
8397     * @see #isLongClickable()
8398     * @attr ref android.R.styleable#View_longClickable
8399     */
8400    public void setLongClickable(boolean longClickable) {
8401        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8402    }
8403
8404    /**
8405     * Indicates whether this view reacts to context clicks or not.
8406     *
8407     * @return true if the view is context clickable, false otherwise
8408     * @see #setContextClickable(boolean)
8409     * @attr ref android.R.styleable#View_contextClickable
8410     */
8411    public boolean isContextClickable() {
8412        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8413    }
8414
8415    /**
8416     * Enables or disables context clicking for this view. This event can launch the listener.
8417     *
8418     * @param contextClickable true to make the view react to a context click, false otherwise
8419     * @see #isContextClickable()
8420     * @attr ref android.R.styleable#View_contextClickable
8421     */
8422    public void setContextClickable(boolean contextClickable) {
8423        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8424    }
8425
8426    /**
8427     * Sets the pressed state for this view and provides a touch coordinate for
8428     * animation hinting.
8429     *
8430     * @param pressed Pass true to set the View's internal state to "pressed",
8431     *            or false to reverts the View's internal state from a
8432     *            previously set "pressed" state.
8433     * @param x The x coordinate of the touch that caused the press
8434     * @param y The y coordinate of the touch that caused the press
8435     */
8436    private void setPressed(boolean pressed, float x, float y) {
8437        if (pressed) {
8438            drawableHotspotChanged(x, y);
8439        }
8440
8441        setPressed(pressed);
8442    }
8443
8444    /**
8445     * Sets the pressed state for this view.
8446     *
8447     * @see #isClickable()
8448     * @see #setClickable(boolean)
8449     *
8450     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8451     *        the View's internal state from a previously set "pressed" state.
8452     */
8453    public void setPressed(boolean pressed) {
8454        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8455
8456        if (pressed) {
8457            mPrivateFlags |= PFLAG_PRESSED;
8458        } else {
8459            mPrivateFlags &= ~PFLAG_PRESSED;
8460        }
8461
8462        if (needsRefresh) {
8463            refreshDrawableState();
8464        }
8465        dispatchSetPressed(pressed);
8466    }
8467
8468    /**
8469     * Dispatch setPressed to all of this View's children.
8470     *
8471     * @see #setPressed(boolean)
8472     *
8473     * @param pressed The new pressed state
8474     */
8475    protected void dispatchSetPressed(boolean pressed) {
8476    }
8477
8478    /**
8479     * Indicates whether the view is currently in pressed state. Unless
8480     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8481     * the pressed state.
8482     *
8483     * @see #setPressed(boolean)
8484     * @see #isClickable()
8485     * @see #setClickable(boolean)
8486     *
8487     * @return true if the view is currently pressed, false otherwise
8488     */
8489    @ViewDebug.ExportedProperty
8490    public boolean isPressed() {
8491        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8492    }
8493
8494    /**
8495     * @hide
8496     * Indicates whether this view will participate in data collection through
8497     * {@link ViewStructure}.  If true, it will not provide any data
8498     * for itself or its children.  If false, the normal data collection will be allowed.
8499     *
8500     * @return Returns false if assist data collection is not blocked, else true.
8501     *
8502     * @see #setAssistBlocked(boolean)
8503     * @attr ref android.R.styleable#View_assistBlocked
8504     */
8505    public boolean isAssistBlocked() {
8506        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8507    }
8508
8509    /**
8510     * @hide
8511     * Controls whether assist data collection from this view and its children is enabled
8512     * (that is, whether {@link #onProvideStructure} and
8513     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8514     * allowing normal assist collection.  Setting this to false will disable assist collection.
8515     *
8516     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8517     * (the default) to allow it.
8518     *
8519     * @see #isAssistBlocked()
8520     * @see #onProvideStructure
8521     * @see #onProvideVirtualStructure
8522     * @attr ref android.R.styleable#View_assistBlocked
8523     */
8524    public void setAssistBlocked(boolean enabled) {
8525        if (enabled) {
8526            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8527        } else {
8528            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8529        }
8530    }
8531
8532    /**
8533     * Indicates whether this view will save its state (that is,
8534     * whether its {@link #onSaveInstanceState} method will be called).
8535     *
8536     * @return Returns true if the view state saving is enabled, else false.
8537     *
8538     * @see #setSaveEnabled(boolean)
8539     * @attr ref android.R.styleable#View_saveEnabled
8540     */
8541    public boolean isSaveEnabled() {
8542        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8543    }
8544
8545    /**
8546     * Controls whether the saving of this view's state is
8547     * enabled (that is, whether its {@link #onSaveInstanceState} method
8548     * will be called).  Note that even if freezing is enabled, the
8549     * view still must have an id assigned to it (via {@link #setId(int)})
8550     * for its state to be saved.  This flag can only disable the
8551     * saving of this view; any child views may still have their state saved.
8552     *
8553     * @param enabled Set to false to <em>disable</em> state saving, or true
8554     * (the default) to allow it.
8555     *
8556     * @see #isSaveEnabled()
8557     * @see #setId(int)
8558     * @see #onSaveInstanceState()
8559     * @attr ref android.R.styleable#View_saveEnabled
8560     */
8561    public void setSaveEnabled(boolean enabled) {
8562        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8563    }
8564
8565    /**
8566     * Gets whether the framework should discard touches when the view's
8567     * window is obscured by another visible window.
8568     * Refer to the {@link View} security documentation for more details.
8569     *
8570     * @return True if touch filtering is enabled.
8571     *
8572     * @see #setFilterTouchesWhenObscured(boolean)
8573     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8574     */
8575    @ViewDebug.ExportedProperty
8576    public boolean getFilterTouchesWhenObscured() {
8577        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8578    }
8579
8580    /**
8581     * Sets whether the framework should discard touches when the view's
8582     * window is obscured by another visible window.
8583     * Refer to the {@link View} security documentation for more details.
8584     *
8585     * @param enabled True if touch filtering should be enabled.
8586     *
8587     * @see #getFilterTouchesWhenObscured
8588     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8589     */
8590    public void setFilterTouchesWhenObscured(boolean enabled) {
8591        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8592                FILTER_TOUCHES_WHEN_OBSCURED);
8593    }
8594
8595    /**
8596     * Indicates whether the entire hierarchy under this view will save its
8597     * state when a state saving traversal occurs from its parent.  The default
8598     * is true; if false, these views will not be saved unless
8599     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8600     *
8601     * @return Returns true if the view state saving from parent is enabled, else false.
8602     *
8603     * @see #setSaveFromParentEnabled(boolean)
8604     */
8605    public boolean isSaveFromParentEnabled() {
8606        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8607    }
8608
8609    /**
8610     * Controls whether the entire hierarchy under this view will save its
8611     * state when a state saving traversal occurs from its parent.  The default
8612     * is true; if false, these views will not be saved unless
8613     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8614     *
8615     * @param enabled Set to false to <em>disable</em> state saving, or true
8616     * (the default) to allow it.
8617     *
8618     * @see #isSaveFromParentEnabled()
8619     * @see #setId(int)
8620     * @see #onSaveInstanceState()
8621     */
8622    public void setSaveFromParentEnabled(boolean enabled) {
8623        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8624    }
8625
8626
8627    /**
8628     * Returns whether this View is able to take focus.
8629     *
8630     * @return True if this view can take focus, or false otherwise.
8631     * @attr ref android.R.styleable#View_focusable
8632     */
8633    @ViewDebug.ExportedProperty(category = "focus")
8634    public final boolean isFocusable() {
8635        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8636    }
8637
8638    /**
8639     * When a view is focusable, it may not want to take focus when in touch mode.
8640     * For example, a button would like focus when the user is navigating via a D-pad
8641     * so that the user can click on it, but once the user starts touching the screen,
8642     * the button shouldn't take focus
8643     * @return Whether the view is focusable in touch mode.
8644     * @attr ref android.R.styleable#View_focusableInTouchMode
8645     */
8646    @ViewDebug.ExportedProperty
8647    public final boolean isFocusableInTouchMode() {
8648        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8649    }
8650
8651    /**
8652     * Find the nearest view in the specified direction that can take focus.
8653     * This does not actually give focus to that view.
8654     *
8655     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8656     *
8657     * @return The nearest focusable in the specified direction, or null if none
8658     *         can be found.
8659     */
8660    public View focusSearch(@FocusRealDirection int direction) {
8661        if (mParent != null) {
8662            return mParent.focusSearch(this, direction);
8663        } else {
8664            return null;
8665        }
8666    }
8667
8668    /**
8669     * This method is the last chance for the focused view and its ancestors to
8670     * respond to an arrow key. This is called when the focused view did not
8671     * consume the key internally, nor could the view system find a new view in
8672     * the requested direction to give focus to.
8673     *
8674     * @param focused The currently focused view.
8675     * @param direction The direction focus wants to move. One of FOCUS_UP,
8676     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8677     * @return True if the this view consumed this unhandled move.
8678     */
8679    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8680        return false;
8681    }
8682
8683    /**
8684     * If a user manually specified the next view id for a particular direction,
8685     * use the root to look up the view.
8686     * @param root The root view of the hierarchy containing this view.
8687     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8688     * or FOCUS_BACKWARD.
8689     * @return The user specified next view, or null if there is none.
8690     */
8691    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8692        switch (direction) {
8693            case FOCUS_LEFT:
8694                if (mNextFocusLeftId == View.NO_ID) return null;
8695                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8696            case FOCUS_RIGHT:
8697                if (mNextFocusRightId == View.NO_ID) return null;
8698                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8699            case FOCUS_UP:
8700                if (mNextFocusUpId == View.NO_ID) return null;
8701                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8702            case FOCUS_DOWN:
8703                if (mNextFocusDownId == View.NO_ID) return null;
8704                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8705            case FOCUS_FORWARD:
8706                if (mNextFocusForwardId == View.NO_ID) return null;
8707                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8708            case FOCUS_BACKWARD: {
8709                if (mID == View.NO_ID) return null;
8710                final int id = mID;
8711                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8712                    @Override
8713                    public boolean apply(View t) {
8714                        return t.mNextFocusForwardId == id;
8715                    }
8716                });
8717            }
8718        }
8719        return null;
8720    }
8721
8722    private View findViewInsideOutShouldExist(View root, int id) {
8723        if (mMatchIdPredicate == null) {
8724            mMatchIdPredicate = new MatchIdPredicate();
8725        }
8726        mMatchIdPredicate.mId = id;
8727        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8728        if (result == null) {
8729            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8730        }
8731        return result;
8732    }
8733
8734    /**
8735     * Find and return all focusable views that are descendants of this view,
8736     * possibly including this view if it is focusable itself.
8737     *
8738     * @param direction The direction of the focus
8739     * @return A list of focusable views
8740     */
8741    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8742        ArrayList<View> result = new ArrayList<View>(24);
8743        addFocusables(result, direction);
8744        return result;
8745    }
8746
8747    /**
8748     * Add any focusable views that are descendants of this view (possibly
8749     * including this view if it is focusable itself) to views.  If we are in touch mode,
8750     * only add views that are also focusable in touch mode.
8751     *
8752     * @param views Focusable views found so far
8753     * @param direction The direction of the focus
8754     */
8755    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8756        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
8757    }
8758
8759    /**
8760     * Adds any focusable views that are descendants of this view (possibly
8761     * including this view if it is focusable itself) to views. This method
8762     * adds all focusable views regardless if we are in touch mode or
8763     * only views focusable in touch mode if we are in touch mode or
8764     * only views that can take accessibility focus if accessibility is enabled
8765     * depending on the focusable mode parameter.
8766     *
8767     * @param views Focusable views found so far or null if all we are interested is
8768     *        the number of focusables.
8769     * @param direction The direction of the focus.
8770     * @param focusableMode The type of focusables to be added.
8771     *
8772     * @see #FOCUSABLES_ALL
8773     * @see #FOCUSABLES_TOUCH_MODE
8774     */
8775    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8776            @FocusableMode int focusableMode) {
8777        if (views == null) {
8778            return;
8779        }
8780        if (!isFocusable()) {
8781            return;
8782        }
8783        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8784                && !isFocusableInTouchMode()) {
8785            return;
8786        }
8787        views.add(this);
8788    }
8789
8790    /**
8791     * Finds the Views that contain given text. The containment is case insensitive.
8792     * The search is performed by either the text that the View renders or the content
8793     * description that describes the view for accessibility purposes and the view does
8794     * not render or both. Clients can specify how the search is to be performed via
8795     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8796     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8797     *
8798     * @param outViews The output list of matching Views.
8799     * @param searched The text to match against.
8800     *
8801     * @see #FIND_VIEWS_WITH_TEXT
8802     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8803     * @see #setContentDescription(CharSequence)
8804     */
8805    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8806            @FindViewFlags int flags) {
8807        if (getAccessibilityNodeProvider() != null) {
8808            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8809                outViews.add(this);
8810            }
8811        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8812                && (searched != null && searched.length() > 0)
8813                && (mContentDescription != null && mContentDescription.length() > 0)) {
8814            String searchedLowerCase = searched.toString().toLowerCase();
8815            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8816            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8817                outViews.add(this);
8818            }
8819        }
8820    }
8821
8822    /**
8823     * Find and return all touchable views that are descendants of this view,
8824     * possibly including this view if it is touchable itself.
8825     *
8826     * @return A list of touchable views
8827     */
8828    public ArrayList<View> getTouchables() {
8829        ArrayList<View> result = new ArrayList<View>();
8830        addTouchables(result);
8831        return result;
8832    }
8833
8834    /**
8835     * Add any touchable views that are descendants of this view (possibly
8836     * including this view if it is touchable itself) to views.
8837     *
8838     * @param views Touchable views found so far
8839     */
8840    public void addTouchables(ArrayList<View> views) {
8841        final int viewFlags = mViewFlags;
8842
8843        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8844                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8845                && (viewFlags & ENABLED_MASK) == ENABLED) {
8846            views.add(this);
8847        }
8848    }
8849
8850    /**
8851     * Returns whether this View is accessibility focused.
8852     *
8853     * @return True if this View is accessibility focused.
8854     */
8855    public boolean isAccessibilityFocused() {
8856        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8857    }
8858
8859    /**
8860     * Call this to try to give accessibility focus to this view.
8861     *
8862     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8863     * returns false or the view is no visible or the view already has accessibility
8864     * focus.
8865     *
8866     * See also {@link #focusSearch(int)}, which is what you call to say that you
8867     * have focus, and you want your parent to look for the next one.
8868     *
8869     * @return Whether this view actually took accessibility focus.
8870     *
8871     * @hide
8872     */
8873    public boolean requestAccessibilityFocus() {
8874        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8875        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8876            return false;
8877        }
8878        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8879            return false;
8880        }
8881        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8882            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8883            ViewRootImpl viewRootImpl = getViewRootImpl();
8884            if (viewRootImpl != null) {
8885                viewRootImpl.setAccessibilityFocus(this, null);
8886            }
8887            invalidate();
8888            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8889            return true;
8890        }
8891        return false;
8892    }
8893
8894    /**
8895     * Call this to try to clear accessibility focus of this view.
8896     *
8897     * See also {@link #focusSearch(int)}, which is what you call to say that you
8898     * have focus, and you want your parent to look for the next one.
8899     *
8900     * @hide
8901     */
8902    public void clearAccessibilityFocus() {
8903        clearAccessibilityFocusNoCallbacks(0);
8904
8905        // Clear the global reference of accessibility focus if this view or
8906        // any of its descendants had accessibility focus. This will NOT send
8907        // an event or update internal state if focus is cleared from a
8908        // descendant view, which may leave views in inconsistent states.
8909        final ViewRootImpl viewRootImpl = getViewRootImpl();
8910        if (viewRootImpl != null) {
8911            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8912            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8913                viewRootImpl.setAccessibilityFocus(null, null);
8914            }
8915        }
8916    }
8917
8918    private void sendAccessibilityHoverEvent(int eventType) {
8919        // Since we are not delivering to a client accessibility events from not
8920        // important views (unless the clinet request that) we need to fire the
8921        // event from the deepest view exposed to the client. As a consequence if
8922        // the user crosses a not exposed view the client will see enter and exit
8923        // of the exposed predecessor followed by and enter and exit of that same
8924        // predecessor when entering and exiting the not exposed descendant. This
8925        // is fine since the client has a clear idea which view is hovered at the
8926        // price of a couple more events being sent. This is a simple and
8927        // working solution.
8928        View source = this;
8929        while (true) {
8930            if (source.includeForAccessibility()) {
8931                source.sendAccessibilityEvent(eventType);
8932                return;
8933            }
8934            ViewParent parent = source.getParent();
8935            if (parent instanceof View) {
8936                source = (View) parent;
8937            } else {
8938                return;
8939            }
8940        }
8941    }
8942
8943    /**
8944     * Clears accessibility focus without calling any callback methods
8945     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8946     * is used separately from that one for clearing accessibility focus when
8947     * giving this focus to another view.
8948     *
8949     * @param action The action, if any, that led to focus being cleared. Set to
8950     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
8951     * the window.
8952     */
8953    void clearAccessibilityFocusNoCallbacks(int action) {
8954        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8955            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8956            invalidate();
8957            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8958                AccessibilityEvent event = AccessibilityEvent.obtain(
8959                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8960                event.setAction(action);
8961                if (mAccessibilityDelegate != null) {
8962                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
8963                } else {
8964                    sendAccessibilityEventUnchecked(event);
8965                }
8966            }
8967        }
8968    }
8969
8970    /**
8971     * Call this to try to give focus to a specific view or to one of its
8972     * descendants.
8973     *
8974     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8975     * false), or if it is focusable and it is not focusable in touch mode
8976     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8977     *
8978     * See also {@link #focusSearch(int)}, which is what you call to say that you
8979     * have focus, and you want your parent to look for the next one.
8980     *
8981     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8982     * {@link #FOCUS_DOWN} and <code>null</code>.
8983     *
8984     * @return Whether this view or one of its descendants actually took focus.
8985     */
8986    public final boolean requestFocus() {
8987        return requestFocus(View.FOCUS_DOWN);
8988    }
8989
8990    /**
8991     * Call this to try to give focus to a specific view or to one of its
8992     * descendants and give it a hint about what direction focus is heading.
8993     *
8994     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8995     * false), or if it is focusable and it is not focusable in touch mode
8996     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8997     *
8998     * See also {@link #focusSearch(int)}, which is what you call to say that you
8999     * have focus, and you want your parent to look for the next one.
9000     *
9001     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9002     * <code>null</code> set for the previously focused rectangle.
9003     *
9004     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9005     * @return Whether this view or one of its descendants actually took focus.
9006     */
9007    public final boolean requestFocus(int direction) {
9008        return requestFocus(direction, null);
9009    }
9010
9011    /**
9012     * Call this to try to give focus to a specific view or to one of its descendants
9013     * and give it hints about the direction and a specific rectangle that the focus
9014     * is coming from.  The rectangle can help give larger views a finer grained hint
9015     * about where focus is coming from, and therefore, where to show selection, or
9016     * forward focus change internally.
9017     *
9018     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9019     * false), or if it is focusable and it is not focusable in touch mode
9020     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9021     *
9022     * A View will not take focus if it is not visible.
9023     *
9024     * A View will not take focus if one of its parents has
9025     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9026     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9027     *
9028     * See also {@link #focusSearch(int)}, which is what you call to say that you
9029     * have focus, and you want your parent to look for the next one.
9030     *
9031     * You may wish to override this method if your custom {@link View} has an internal
9032     * {@link View} that it wishes to forward the request to.
9033     *
9034     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9035     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9036     *        to give a finer grained hint about where focus is coming from.  May be null
9037     *        if there is no hint.
9038     * @return Whether this view or one of its descendants actually took focus.
9039     */
9040    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9041        return requestFocusNoSearch(direction, previouslyFocusedRect);
9042    }
9043
9044    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9045        // need to be focusable
9046        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9047                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9048            return false;
9049        }
9050
9051        // need to be focusable in touch mode if in touch mode
9052        if (isInTouchMode() &&
9053            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9054               return false;
9055        }
9056
9057        // need to not have any parents blocking us
9058        if (hasAncestorThatBlocksDescendantFocus()) {
9059            return false;
9060        }
9061
9062        handleFocusGainInternal(direction, previouslyFocusedRect);
9063        return true;
9064    }
9065
9066    /**
9067     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9068     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9069     * touch mode to request focus when they are touched.
9070     *
9071     * @return Whether this view or one of its descendants actually took focus.
9072     *
9073     * @see #isInTouchMode()
9074     *
9075     */
9076    public final boolean requestFocusFromTouch() {
9077        // Leave touch mode if we need to
9078        if (isInTouchMode()) {
9079            ViewRootImpl viewRoot = getViewRootImpl();
9080            if (viewRoot != null) {
9081                viewRoot.ensureTouchMode(false);
9082            }
9083        }
9084        return requestFocus(View.FOCUS_DOWN);
9085    }
9086
9087    /**
9088     * @return Whether any ancestor of this view blocks descendant focus.
9089     */
9090    private boolean hasAncestorThatBlocksDescendantFocus() {
9091        final boolean focusableInTouchMode = isFocusableInTouchMode();
9092        ViewParent ancestor = mParent;
9093        while (ancestor instanceof ViewGroup) {
9094            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9095            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9096                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9097                return true;
9098            } else {
9099                ancestor = vgAncestor.getParent();
9100            }
9101        }
9102        return false;
9103    }
9104
9105    /**
9106     * Gets the mode for determining whether this View is important for accessibility
9107     * which is if it fires accessibility events and if it is reported to
9108     * accessibility services that query the screen.
9109     *
9110     * @return The mode for determining whether a View is important for accessibility.
9111     *
9112     * @attr ref android.R.styleable#View_importantForAccessibility
9113     *
9114     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9115     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9116     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9117     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9118     */
9119    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9120            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9121            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9122            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9123            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9124                    to = "noHideDescendants")
9125        })
9126    public int getImportantForAccessibility() {
9127        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9128                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9129    }
9130
9131    /**
9132     * Sets the live region mode for this view. This indicates to accessibility
9133     * services whether they should automatically notify the user about changes
9134     * to the view's content description or text, or to the content descriptions
9135     * or text of the view's children (where applicable).
9136     * <p>
9137     * For example, in a login screen with a TextView that displays an "incorrect
9138     * password" notification, that view should be marked as a live region with
9139     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9140     * <p>
9141     * To disable change notifications for this view, use
9142     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9143     * mode for most views.
9144     * <p>
9145     * To indicate that the user should be notified of changes, use
9146     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9147     * <p>
9148     * If the view's changes should interrupt ongoing speech and notify the user
9149     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9150     *
9151     * @param mode The live region mode for this view, one of:
9152     *        <ul>
9153     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9154     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9155     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9156     *        </ul>
9157     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9158     */
9159    public void setAccessibilityLiveRegion(int mode) {
9160        if (mode != getAccessibilityLiveRegion()) {
9161            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9162            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9163                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9164            notifyViewAccessibilityStateChangedIfNeeded(
9165                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9166        }
9167    }
9168
9169    /**
9170     * Gets the live region mode for this View.
9171     *
9172     * @return The live region mode for the view.
9173     *
9174     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9175     *
9176     * @see #setAccessibilityLiveRegion(int)
9177     */
9178    public int getAccessibilityLiveRegion() {
9179        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9180                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9181    }
9182
9183    /**
9184     * Sets how to determine whether this view is important for accessibility
9185     * which is if it fires accessibility events and if it is reported to
9186     * accessibility services that query the screen.
9187     *
9188     * @param mode How to determine whether this view is important for accessibility.
9189     *
9190     * @attr ref android.R.styleable#View_importantForAccessibility
9191     *
9192     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9193     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9194     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9195     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9196     */
9197    public void setImportantForAccessibility(int mode) {
9198        final int oldMode = getImportantForAccessibility();
9199        if (mode != oldMode) {
9200            final boolean hideDescendants =
9201                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9202
9203            // If this node or its descendants are no longer important, try to
9204            // clear accessibility focus.
9205            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9206                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9207                if (focusHost != null) {
9208                    focusHost.clearAccessibilityFocus();
9209                }
9210            }
9211
9212            // If we're moving between AUTO and another state, we might not need
9213            // to send a subtree changed notification. We'll store the computed
9214            // importance, since we'll need to check it later to make sure.
9215            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9216                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9217            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9218            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9219            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9220                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9221            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9222                notifySubtreeAccessibilityStateChangedIfNeeded();
9223            } else {
9224                notifyViewAccessibilityStateChangedIfNeeded(
9225                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9226            }
9227        }
9228    }
9229
9230    /**
9231     * Returns the view within this view's hierarchy that is hosting
9232     * accessibility focus.
9233     *
9234     * @param searchDescendants whether to search for focus in descendant views
9235     * @return the view hosting accessibility focus, or {@code null}
9236     */
9237    private View findAccessibilityFocusHost(boolean searchDescendants) {
9238        if (isAccessibilityFocusedViewOrHost()) {
9239            return this;
9240        }
9241
9242        if (searchDescendants) {
9243            final ViewRootImpl viewRoot = getViewRootImpl();
9244            if (viewRoot != null) {
9245                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9246                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9247                    return focusHost;
9248                }
9249            }
9250        }
9251
9252        return null;
9253    }
9254
9255    /**
9256     * Computes whether this view should be exposed for accessibility. In
9257     * general, views that are interactive or provide information are exposed
9258     * while views that serve only as containers are hidden.
9259     * <p>
9260     * If an ancestor of this view has importance
9261     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9262     * returns <code>false</code>.
9263     * <p>
9264     * Otherwise, the value is computed according to the view's
9265     * {@link #getImportantForAccessibility()} value:
9266     * <ol>
9267     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9268     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9269     * </code>
9270     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9271     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9272     * view satisfies any of the following:
9273     * <ul>
9274     * <li>Is actionable, e.g. {@link #isClickable()},
9275     * {@link #isLongClickable()}, or {@link #isFocusable()}
9276     * <li>Has an {@link AccessibilityDelegate}
9277     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9278     * {@link OnKeyListener}, etc.
9279     * <li>Is an accessibility live region, e.g.
9280     * {@link #getAccessibilityLiveRegion()} is not
9281     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9282     * </ul>
9283     * </ol>
9284     *
9285     * @return Whether the view is exposed for accessibility.
9286     * @see #setImportantForAccessibility(int)
9287     * @see #getImportantForAccessibility()
9288     */
9289    public boolean isImportantForAccessibility() {
9290        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9291                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9292        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9293                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9294            return false;
9295        }
9296
9297        // Check parent mode to ensure we're not hidden.
9298        ViewParent parent = mParent;
9299        while (parent instanceof View) {
9300            if (((View) parent).getImportantForAccessibility()
9301                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9302                return false;
9303            }
9304            parent = parent.getParent();
9305        }
9306
9307        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9308                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9309                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9310    }
9311
9312    /**
9313     * Gets the parent for accessibility purposes. Note that the parent for
9314     * accessibility is not necessary the immediate parent. It is the first
9315     * predecessor that is important for accessibility.
9316     *
9317     * @return The parent for accessibility purposes.
9318     */
9319    public ViewParent getParentForAccessibility() {
9320        if (mParent instanceof View) {
9321            View parentView = (View) mParent;
9322            if (parentView.includeForAccessibility()) {
9323                return mParent;
9324            } else {
9325                return mParent.getParentForAccessibility();
9326            }
9327        }
9328        return null;
9329    }
9330
9331    /**
9332     * Adds the children of this View relevant for accessibility to the given list
9333     * as output. Since some Views are not important for accessibility the added
9334     * child views are not necessarily direct children of this view, rather they are
9335     * the first level of descendants important for accessibility.
9336     *
9337     * @param outChildren The output list that will receive children for accessibility.
9338     */
9339    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9340
9341    }
9342
9343    /**
9344     * Whether to regard this view for accessibility. A view is regarded for
9345     * accessibility if it is important for accessibility or the querying
9346     * accessibility service has explicitly requested that view not
9347     * important for accessibility are regarded.
9348     *
9349     * @return Whether to regard the view for accessibility.
9350     *
9351     * @hide
9352     */
9353    public boolean includeForAccessibility() {
9354        if (mAttachInfo != null) {
9355            return (mAttachInfo.mAccessibilityFetchFlags
9356                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9357                    || isImportantForAccessibility();
9358        }
9359        return false;
9360    }
9361
9362    /**
9363     * Returns whether the View is considered actionable from
9364     * accessibility perspective. Such view are important for
9365     * accessibility.
9366     *
9367     * @return True if the view is actionable for accessibility.
9368     *
9369     * @hide
9370     */
9371    public boolean isActionableForAccessibility() {
9372        return (isClickable() || isLongClickable() || isFocusable());
9373    }
9374
9375    /**
9376     * Returns whether the View has registered callbacks which makes it
9377     * important for accessibility.
9378     *
9379     * @return True if the view is actionable for accessibility.
9380     */
9381    private boolean hasListenersForAccessibility() {
9382        ListenerInfo info = getListenerInfo();
9383        return mTouchDelegate != null || info.mOnKeyListener != null
9384                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9385                || info.mOnHoverListener != null || info.mOnDragListener != null;
9386    }
9387
9388    /**
9389     * Notifies that the accessibility state of this view changed. The change
9390     * is local to this view and does not represent structural changes such
9391     * as children and parent. For example, the view became focusable. The
9392     * notification is at at most once every
9393     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9394     * to avoid unnecessary load to the system. Also once a view has a pending
9395     * notification this method is a NOP until the notification has been sent.
9396     *
9397     * @hide
9398     */
9399    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9400        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9401            return;
9402        }
9403        if (mSendViewStateChangedAccessibilityEvent == null) {
9404            mSendViewStateChangedAccessibilityEvent =
9405                    new SendViewStateChangedAccessibilityEvent();
9406        }
9407        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9408    }
9409
9410    /**
9411     * Notifies that the accessibility state of this view changed. The change
9412     * is *not* local to this view and does represent structural changes such
9413     * as children and parent. For example, the view size changed. The
9414     * notification is at at most once every
9415     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9416     * to avoid unnecessary load to the system. Also once a view has a pending
9417     * notification this method is a NOP until the notification has been sent.
9418     *
9419     * @hide
9420     */
9421    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9422        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9423            return;
9424        }
9425        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9426            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9427            if (mParent != null) {
9428                try {
9429                    mParent.notifySubtreeAccessibilityStateChanged(
9430                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9431                } catch (AbstractMethodError e) {
9432                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9433                            " does not fully implement ViewParent", e);
9434                }
9435            }
9436        }
9437    }
9438
9439    /**
9440     * Change the visibility of the View without triggering any other changes. This is
9441     * important for transitions, where visibility changes should not adjust focus or
9442     * trigger a new layout. This is only used when the visibility has already been changed
9443     * and we need a transient value during an animation. When the animation completes,
9444     * the original visibility value is always restored.
9445     *
9446     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9447     * @hide
9448     */
9449    public void setTransitionVisibility(@Visibility int visibility) {
9450        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9451    }
9452
9453    /**
9454     * Reset the flag indicating the accessibility state of the subtree rooted
9455     * at this view changed.
9456     */
9457    void resetSubtreeAccessibilityStateChanged() {
9458        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9459    }
9460
9461    /**
9462     * Report an accessibility action to this view's parents for delegated processing.
9463     *
9464     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9465     * call this method to delegate an accessibility action to a supporting parent. If the parent
9466     * returns true from its
9467     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9468     * method this method will return true to signify that the action was consumed.</p>
9469     *
9470     * <p>This method is useful for implementing nested scrolling child views. If
9471     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9472     * a custom view implementation may invoke this method to allow a parent to consume the
9473     * scroll first. If this method returns true the custom view should skip its own scrolling
9474     * behavior.</p>
9475     *
9476     * @param action Accessibility action to delegate
9477     * @param arguments Optional action arguments
9478     * @return true if the action was consumed by a parent
9479     */
9480    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9481        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9482            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9483                return true;
9484            }
9485        }
9486        return false;
9487    }
9488
9489    /**
9490     * Performs the specified accessibility action on the view. For
9491     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9492     * <p>
9493     * If an {@link AccessibilityDelegate} has been specified via calling
9494     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9495     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9496     * is responsible for handling this call.
9497     * </p>
9498     *
9499     * <p>The default implementation will delegate
9500     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9501     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9502     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9503     *
9504     * @param action The action to perform.
9505     * @param arguments Optional action arguments.
9506     * @return Whether the action was performed.
9507     */
9508    public boolean performAccessibilityAction(int action, Bundle arguments) {
9509      if (mAccessibilityDelegate != null) {
9510          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9511      } else {
9512          return performAccessibilityActionInternal(action, arguments);
9513      }
9514    }
9515
9516   /**
9517    * @see #performAccessibilityAction(int, Bundle)
9518    *
9519    * Note: Called from the default {@link AccessibilityDelegate}.
9520    *
9521    * @hide
9522    */
9523    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9524        if (isNestedScrollingEnabled()
9525                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9526                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9527                || action == R.id.accessibilityActionScrollUp
9528                || action == R.id.accessibilityActionScrollLeft
9529                || action == R.id.accessibilityActionScrollDown
9530                || action == R.id.accessibilityActionScrollRight)) {
9531            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9532                return true;
9533            }
9534        }
9535
9536        switch (action) {
9537            case AccessibilityNodeInfo.ACTION_CLICK: {
9538                if (isClickable()) {
9539                    performClick();
9540                    return true;
9541                }
9542            } break;
9543            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9544                if (isLongClickable()) {
9545                    performLongClick();
9546                    return true;
9547                }
9548            } break;
9549            case AccessibilityNodeInfo.ACTION_FOCUS: {
9550                if (!hasFocus()) {
9551                    // Get out of touch mode since accessibility
9552                    // wants to move focus around.
9553                    getViewRootImpl().ensureTouchMode(false);
9554                    return requestFocus();
9555                }
9556            } break;
9557            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9558                if (hasFocus()) {
9559                    clearFocus();
9560                    return !isFocused();
9561                }
9562            } break;
9563            case AccessibilityNodeInfo.ACTION_SELECT: {
9564                if (!isSelected()) {
9565                    setSelected(true);
9566                    return isSelected();
9567                }
9568            } break;
9569            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9570                if (isSelected()) {
9571                    setSelected(false);
9572                    return !isSelected();
9573                }
9574            } break;
9575            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9576                if (!isAccessibilityFocused()) {
9577                    return requestAccessibilityFocus();
9578                }
9579            } break;
9580            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9581                if (isAccessibilityFocused()) {
9582                    clearAccessibilityFocus();
9583                    return true;
9584                }
9585            } break;
9586            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9587                if (arguments != null) {
9588                    final int granularity = arguments.getInt(
9589                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9590                    final boolean extendSelection = arguments.getBoolean(
9591                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9592                    return traverseAtGranularity(granularity, true, extendSelection);
9593                }
9594            } break;
9595            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9596                if (arguments != null) {
9597                    final int granularity = arguments.getInt(
9598                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9599                    final boolean extendSelection = arguments.getBoolean(
9600                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9601                    return traverseAtGranularity(granularity, false, extendSelection);
9602                }
9603            } break;
9604            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9605                CharSequence text = getIterableTextForAccessibility();
9606                if (text == null) {
9607                    return false;
9608                }
9609                final int start = (arguments != null) ? arguments.getInt(
9610                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9611                final int end = (arguments != null) ? arguments.getInt(
9612                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9613                // Only cursor position can be specified (selection length == 0)
9614                if ((getAccessibilitySelectionStart() != start
9615                        || getAccessibilitySelectionEnd() != end)
9616                        && (start == end)) {
9617                    setAccessibilitySelection(start, end);
9618                    notifyViewAccessibilityStateChangedIfNeeded(
9619                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9620                    return true;
9621                }
9622            } break;
9623            case R.id.accessibilityActionShowOnScreen: {
9624                if (mAttachInfo != null) {
9625                    final Rect r = mAttachInfo.mTmpInvalRect;
9626                    getDrawingRect(r);
9627                    return requestRectangleOnScreen(r, true);
9628                }
9629            } break;
9630            case R.id.accessibilityActionContextClick: {
9631                if (isContextClickable()) {
9632                    performContextClick();
9633                    return true;
9634                }
9635            } break;
9636        }
9637        return false;
9638    }
9639
9640    private boolean traverseAtGranularity(int granularity, boolean forward,
9641            boolean extendSelection) {
9642        CharSequence text = getIterableTextForAccessibility();
9643        if (text == null || text.length() == 0) {
9644            return false;
9645        }
9646        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9647        if (iterator == null) {
9648            return false;
9649        }
9650        int current = getAccessibilitySelectionEnd();
9651        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9652            current = forward ? 0 : text.length();
9653        }
9654        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9655        if (range == null) {
9656            return false;
9657        }
9658        final int segmentStart = range[0];
9659        final int segmentEnd = range[1];
9660        int selectionStart;
9661        int selectionEnd;
9662        if (extendSelection && isAccessibilitySelectionExtendable()) {
9663            selectionStart = getAccessibilitySelectionStart();
9664            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9665                selectionStart = forward ? segmentStart : segmentEnd;
9666            }
9667            selectionEnd = forward ? segmentEnd : segmentStart;
9668        } else {
9669            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9670        }
9671        setAccessibilitySelection(selectionStart, selectionEnd);
9672        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9673                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9674        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9675        return true;
9676    }
9677
9678    /**
9679     * Gets the text reported for accessibility purposes.
9680     *
9681     * @return The accessibility text.
9682     *
9683     * @hide
9684     */
9685    public CharSequence getIterableTextForAccessibility() {
9686        return getContentDescription();
9687    }
9688
9689    /**
9690     * Gets whether accessibility selection can be extended.
9691     *
9692     * @return If selection is extensible.
9693     *
9694     * @hide
9695     */
9696    public boolean isAccessibilitySelectionExtendable() {
9697        return false;
9698    }
9699
9700    /**
9701     * @hide
9702     */
9703    public int getAccessibilitySelectionStart() {
9704        return mAccessibilityCursorPosition;
9705    }
9706
9707    /**
9708     * @hide
9709     */
9710    public int getAccessibilitySelectionEnd() {
9711        return getAccessibilitySelectionStart();
9712    }
9713
9714    /**
9715     * @hide
9716     */
9717    public void setAccessibilitySelection(int start, int end) {
9718        if (start ==  end && end == mAccessibilityCursorPosition) {
9719            return;
9720        }
9721        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9722            mAccessibilityCursorPosition = start;
9723        } else {
9724            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9725        }
9726        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9727    }
9728
9729    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9730            int fromIndex, int toIndex) {
9731        if (mParent == null) {
9732            return;
9733        }
9734        AccessibilityEvent event = AccessibilityEvent.obtain(
9735                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9736        onInitializeAccessibilityEvent(event);
9737        onPopulateAccessibilityEvent(event);
9738        event.setFromIndex(fromIndex);
9739        event.setToIndex(toIndex);
9740        event.setAction(action);
9741        event.setMovementGranularity(granularity);
9742        mParent.requestSendAccessibilityEvent(this, event);
9743    }
9744
9745    /**
9746     * @hide
9747     */
9748    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9749        switch (granularity) {
9750            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9751                CharSequence text = getIterableTextForAccessibility();
9752                if (text != null && text.length() > 0) {
9753                    CharacterTextSegmentIterator iterator =
9754                        CharacterTextSegmentIterator.getInstance(
9755                                mContext.getResources().getConfiguration().locale);
9756                    iterator.initialize(text.toString());
9757                    return iterator;
9758                }
9759            } break;
9760            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9761                CharSequence text = getIterableTextForAccessibility();
9762                if (text != null && text.length() > 0) {
9763                    WordTextSegmentIterator iterator =
9764                        WordTextSegmentIterator.getInstance(
9765                                mContext.getResources().getConfiguration().locale);
9766                    iterator.initialize(text.toString());
9767                    return iterator;
9768                }
9769            } break;
9770            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9771                CharSequence text = getIterableTextForAccessibility();
9772                if (text != null && text.length() > 0) {
9773                    ParagraphTextSegmentIterator iterator =
9774                        ParagraphTextSegmentIterator.getInstance();
9775                    iterator.initialize(text.toString());
9776                    return iterator;
9777                }
9778            } break;
9779        }
9780        return null;
9781    }
9782
9783    /**
9784     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9785     * and {@link #onFinishTemporaryDetach()}.
9786     */
9787    public final boolean isTemporarilyDetached() {
9788        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9789    }
9790
9791    /**
9792     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9793     * a container View.
9794     */
9795    @CallSuper
9796    public void dispatchStartTemporaryDetach() {
9797        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9798        onStartTemporaryDetach();
9799    }
9800
9801    /**
9802     * This is called when a container is going to temporarily detach a child, with
9803     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9804     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9805     * {@link #onDetachedFromWindow()} when the container is done.
9806     */
9807    public void onStartTemporaryDetach() {
9808        removeUnsetPressCallback();
9809        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9810    }
9811
9812    /**
9813     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9814     * a container View.
9815     */
9816    @CallSuper
9817    public void dispatchFinishTemporaryDetach() {
9818        onFinishTemporaryDetach();
9819        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9820        if (hasWindowFocus() && hasFocus()) {
9821            InputMethodManager.getInstance().focusIn(this);
9822        }
9823    }
9824
9825    /**
9826     * Called after {@link #onStartTemporaryDetach} when the container is done
9827     * changing the view.
9828     */
9829    public void onFinishTemporaryDetach() {
9830    }
9831
9832    /**
9833     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9834     * for this view's window.  Returns null if the view is not currently attached
9835     * to the window.  Normally you will not need to use this directly, but
9836     * just use the standard high-level event callbacks like
9837     * {@link #onKeyDown(int, KeyEvent)}.
9838     */
9839    public KeyEvent.DispatcherState getKeyDispatcherState() {
9840        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9841    }
9842
9843    /**
9844     * Dispatch a key event before it is processed by any input method
9845     * associated with the view hierarchy.  This can be used to intercept
9846     * key events in special situations before the IME consumes them; a
9847     * typical example would be handling the BACK key to update the application's
9848     * UI instead of allowing the IME to see it and close itself.
9849     *
9850     * @param event The key event to be dispatched.
9851     * @return True if the event was handled, false otherwise.
9852     */
9853    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9854        return onKeyPreIme(event.getKeyCode(), event);
9855    }
9856
9857    /**
9858     * Dispatch a key event to the next view on the focus path. This path runs
9859     * from the top of the view tree down to the currently focused view. If this
9860     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9861     * the next node down the focus path. This method also fires any key
9862     * listeners.
9863     *
9864     * @param event The key event to be dispatched.
9865     * @return True if the event was handled, false otherwise.
9866     */
9867    public boolean dispatchKeyEvent(KeyEvent event) {
9868        if (mInputEventConsistencyVerifier != null) {
9869            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9870        }
9871
9872        // Give any attached key listener a first crack at the event.
9873        //noinspection SimplifiableIfStatement
9874        ListenerInfo li = mListenerInfo;
9875        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9876                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9877            return true;
9878        }
9879
9880        if (event.dispatch(this, mAttachInfo != null
9881                ? mAttachInfo.mKeyDispatchState : null, this)) {
9882            return true;
9883        }
9884
9885        if (mInputEventConsistencyVerifier != null) {
9886            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9887        }
9888        return false;
9889    }
9890
9891    /**
9892     * Dispatches a key shortcut event.
9893     *
9894     * @param event The key event to be dispatched.
9895     * @return True if the event was handled by the view, false otherwise.
9896     */
9897    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9898        return onKeyShortcut(event.getKeyCode(), event);
9899    }
9900
9901    /**
9902     * Pass the touch screen motion event down to the target view, or this
9903     * view if it is the target.
9904     *
9905     * @param event The motion event to be dispatched.
9906     * @return True if the event was handled by the view, false otherwise.
9907     */
9908    public boolean dispatchTouchEvent(MotionEvent event) {
9909        // If the event should be handled by accessibility focus first.
9910        if (event.isTargetAccessibilityFocus()) {
9911            // We don't have focus or no virtual descendant has it, do not handle the event.
9912            if (!isAccessibilityFocusedViewOrHost()) {
9913                return false;
9914            }
9915            // We have focus and got the event, then use normal event dispatch.
9916            event.setTargetAccessibilityFocus(false);
9917        }
9918
9919        boolean result = false;
9920
9921        if (mInputEventConsistencyVerifier != null) {
9922            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9923        }
9924
9925        final int actionMasked = event.getActionMasked();
9926        if (actionMasked == MotionEvent.ACTION_DOWN) {
9927            // Defensive cleanup for new gesture
9928            stopNestedScroll();
9929        }
9930
9931        if (onFilterTouchEventForSecurity(event)) {
9932            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
9933                result = true;
9934            }
9935            //noinspection SimplifiableIfStatement
9936            ListenerInfo li = mListenerInfo;
9937            if (li != null && li.mOnTouchListener != null
9938                    && (mViewFlags & ENABLED_MASK) == ENABLED
9939                    && li.mOnTouchListener.onTouch(this, event)) {
9940                result = true;
9941            }
9942
9943            if (!result && onTouchEvent(event)) {
9944                result = true;
9945            }
9946        }
9947
9948        if (!result && mInputEventConsistencyVerifier != null) {
9949            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9950        }
9951
9952        // Clean up after nested scrolls if this is the end of a gesture;
9953        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9954        // of the gesture.
9955        if (actionMasked == MotionEvent.ACTION_UP ||
9956                actionMasked == MotionEvent.ACTION_CANCEL ||
9957                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9958            stopNestedScroll();
9959        }
9960
9961        return result;
9962    }
9963
9964    boolean isAccessibilityFocusedViewOrHost() {
9965        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9966                .getAccessibilityFocusedHost() == this);
9967    }
9968
9969    /**
9970     * Filter the touch event to apply security policies.
9971     *
9972     * @param event The motion event to be filtered.
9973     * @return True if the event should be dispatched, false if the event should be dropped.
9974     *
9975     * @see #getFilterTouchesWhenObscured
9976     */
9977    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9978        //noinspection RedundantIfStatement
9979        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9980                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9981            // Window is obscured, drop this touch.
9982            return false;
9983        }
9984        return true;
9985    }
9986
9987    /**
9988     * Pass a trackball motion event down to the focused view.
9989     *
9990     * @param event The motion event to be dispatched.
9991     * @return True if the event was handled by the view, false otherwise.
9992     */
9993    public boolean dispatchTrackballEvent(MotionEvent event) {
9994        if (mInputEventConsistencyVerifier != null) {
9995            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9996        }
9997
9998        return onTrackballEvent(event);
9999    }
10000
10001    /**
10002     * Dispatch a generic motion event.
10003     * <p>
10004     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10005     * are delivered to the view under the pointer.  All other generic motion events are
10006     * delivered to the focused view.  Hover events are handled specially and are delivered
10007     * to {@link #onHoverEvent(MotionEvent)}.
10008     * </p>
10009     *
10010     * @param event The motion event to be dispatched.
10011     * @return True if the event was handled by the view, false otherwise.
10012     */
10013    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10014        if (mInputEventConsistencyVerifier != null) {
10015            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10016        }
10017
10018        final int source = event.getSource();
10019        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10020            final int action = event.getAction();
10021            if (action == MotionEvent.ACTION_HOVER_ENTER
10022                    || action == MotionEvent.ACTION_HOVER_MOVE
10023                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10024                if (dispatchHoverEvent(event)) {
10025                    return true;
10026                }
10027            } else if (dispatchGenericPointerEvent(event)) {
10028                return true;
10029            }
10030        } else if (dispatchGenericFocusedEvent(event)) {
10031            return true;
10032        }
10033
10034        if (dispatchGenericMotionEventInternal(event)) {
10035            return true;
10036        }
10037
10038        if (mInputEventConsistencyVerifier != null) {
10039            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10040        }
10041        return false;
10042    }
10043
10044    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10045        //noinspection SimplifiableIfStatement
10046        ListenerInfo li = mListenerInfo;
10047        if (li != null && li.mOnGenericMotionListener != null
10048                && (mViewFlags & ENABLED_MASK) == ENABLED
10049                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10050            return true;
10051        }
10052
10053        if (onGenericMotionEvent(event)) {
10054            return true;
10055        }
10056
10057        final int actionButton = event.getActionButton();
10058        switch (event.getActionMasked()) {
10059            case MotionEvent.ACTION_BUTTON_PRESS:
10060                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10061                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10062                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10063                    if (performContextClick(event.getX(), event.getY())) {
10064                        mInContextButtonPress = true;
10065                        setPressed(true, event.getX(), event.getY());
10066                        removeTapCallback();
10067                        removeLongPressCallback();
10068                        return true;
10069                    }
10070                }
10071                break;
10072
10073            case MotionEvent.ACTION_BUTTON_RELEASE:
10074                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10075                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10076                    mInContextButtonPress = false;
10077                    mIgnoreNextUpEvent = true;
10078                }
10079                break;
10080        }
10081
10082        if (mInputEventConsistencyVerifier != null) {
10083            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10084        }
10085        return false;
10086    }
10087
10088    /**
10089     * Dispatch a hover event.
10090     * <p>
10091     * Do not call this method directly.
10092     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10093     * </p>
10094     *
10095     * @param event The motion event to be dispatched.
10096     * @return True if the event was handled by the view, false otherwise.
10097     */
10098    protected boolean dispatchHoverEvent(MotionEvent event) {
10099        ListenerInfo li = mListenerInfo;
10100        //noinspection SimplifiableIfStatement
10101        if (li != null && li.mOnHoverListener != null
10102                && (mViewFlags & ENABLED_MASK) == ENABLED
10103                && li.mOnHoverListener.onHover(this, event)) {
10104            return true;
10105        }
10106
10107        return onHoverEvent(event);
10108    }
10109
10110    /**
10111     * Returns true if the view has a child to which it has recently sent
10112     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10113     * it does not have a hovered child, then it must be the innermost hovered view.
10114     * @hide
10115     */
10116    protected boolean hasHoveredChild() {
10117        return false;
10118    }
10119
10120    /**
10121     * Dispatch a generic motion event to the view under the first pointer.
10122     * <p>
10123     * Do not call this method directly.
10124     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10125     * </p>
10126     *
10127     * @param event The motion event to be dispatched.
10128     * @return True if the event was handled by the view, false otherwise.
10129     */
10130    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10131        return false;
10132    }
10133
10134    /**
10135     * Dispatch a generic motion event to the currently focused view.
10136     * <p>
10137     * Do not call this method directly.
10138     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
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     */
10144    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10145        return false;
10146    }
10147
10148    /**
10149     * Dispatch a pointer event.
10150     * <p>
10151     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10152     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10153     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10154     * and should not be expected to handle other pointing device features.
10155     * </p>
10156     *
10157     * @param event The motion event to be dispatched.
10158     * @return True if the event was handled by the view, false otherwise.
10159     * @hide
10160     */
10161    public final boolean dispatchPointerEvent(MotionEvent event) {
10162        if (event.isTouchEvent()) {
10163            return dispatchTouchEvent(event);
10164        } else {
10165            return dispatchGenericMotionEvent(event);
10166        }
10167    }
10168
10169    /**
10170     * Called when the window containing this view gains or loses window focus.
10171     * ViewGroups should override to route to their children.
10172     *
10173     * @param hasFocus True if the window containing this view now has focus,
10174     *        false otherwise.
10175     */
10176    public void dispatchWindowFocusChanged(boolean hasFocus) {
10177        onWindowFocusChanged(hasFocus);
10178    }
10179
10180    /**
10181     * Called when the window containing this view gains or loses focus.  Note
10182     * that this is separate from view focus: to receive key events, both
10183     * your view and its window must have focus.  If a window is displayed
10184     * on top of yours that takes input focus, then your own window will lose
10185     * focus but the view focus will remain unchanged.
10186     *
10187     * @param hasWindowFocus True if the window containing this view now has
10188     *        focus, false otherwise.
10189     */
10190    public void onWindowFocusChanged(boolean hasWindowFocus) {
10191        InputMethodManager imm = InputMethodManager.peekInstance();
10192        if (!hasWindowFocus) {
10193            if (isPressed()) {
10194                setPressed(false);
10195            }
10196            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10197                imm.focusOut(this);
10198            }
10199            removeLongPressCallback();
10200            removeTapCallback();
10201            onFocusLost();
10202        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10203            imm.focusIn(this);
10204        }
10205        refreshDrawableState();
10206    }
10207
10208    /**
10209     * Returns true if this view is in a window that currently has window focus.
10210     * Note that this is not the same as the view itself having focus.
10211     *
10212     * @return True if this view is in a window that currently has window focus.
10213     */
10214    public boolean hasWindowFocus() {
10215        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10216    }
10217
10218    /**
10219     * Dispatch a view visibility change down the view hierarchy.
10220     * ViewGroups should override to route to their children.
10221     * @param changedView The view whose visibility changed. Could be 'this' or
10222     * an ancestor view.
10223     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10224     * {@link #INVISIBLE} or {@link #GONE}.
10225     */
10226    protected void dispatchVisibilityChanged(@NonNull View changedView,
10227            @Visibility int visibility) {
10228        onVisibilityChanged(changedView, visibility);
10229    }
10230
10231    /**
10232     * Called when the visibility of the view or an ancestor of the view has
10233     * changed.
10234     *
10235     * @param changedView The view whose visibility changed. May be
10236     *                    {@code this} or an ancestor view.
10237     * @param visibility The new visibility, one of {@link #VISIBLE},
10238     *                   {@link #INVISIBLE} or {@link #GONE}.
10239     */
10240    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10241    }
10242
10243    /**
10244     * Dispatch a hint about whether this view is displayed. For instance, when
10245     * a View moves out of the screen, it might receives a display hint indicating
10246     * the view is not displayed. Applications should not <em>rely</em> on this hint
10247     * as there is no guarantee that they will receive one.
10248     *
10249     * @param hint A hint about whether or not this view is displayed:
10250     * {@link #VISIBLE} or {@link #INVISIBLE}.
10251     */
10252    public void dispatchDisplayHint(@Visibility int hint) {
10253        onDisplayHint(hint);
10254    }
10255
10256    /**
10257     * Gives this view a hint about whether is displayed or not. For instance, when
10258     * a View moves out of the screen, it might receives a display hint indicating
10259     * the view is not displayed. Applications should not <em>rely</em> on this hint
10260     * as there is no guarantee that they will receive one.
10261     *
10262     * @param hint A hint about whether or not this view is displayed:
10263     * {@link #VISIBLE} or {@link #INVISIBLE}.
10264     */
10265    protected void onDisplayHint(@Visibility int hint) {
10266    }
10267
10268    /**
10269     * Dispatch a window visibility change down the view hierarchy.
10270     * ViewGroups should override to route to their children.
10271     *
10272     * @param visibility The new visibility of the window.
10273     *
10274     * @see #onWindowVisibilityChanged(int)
10275     */
10276    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10277        onWindowVisibilityChanged(visibility);
10278    }
10279
10280    /**
10281     * Called when the window containing has change its visibility
10282     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10283     * that this tells you whether or not your window is being made visible
10284     * to the window manager; this does <em>not</em> tell you whether or not
10285     * your window is obscured by other windows on the screen, even if it
10286     * is itself visible.
10287     *
10288     * @param visibility The new visibility of the window.
10289     */
10290    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10291        if (visibility == VISIBLE) {
10292            initialAwakenScrollBars();
10293        }
10294    }
10295
10296    /**
10297     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10298     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10299     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10300     *
10301     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10302     *                  ancestors or by window visibility
10303     * @return true if this view is visible to the user, not counting clipping or overlapping
10304     */
10305    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10306        final boolean thisVisible = getVisibility() == VISIBLE;
10307        // If we're not visible but something is telling us we are, ignore it.
10308        if (thisVisible || !isVisible) {
10309            onVisibilityAggregated(isVisible);
10310        }
10311        return thisVisible && isVisible;
10312    }
10313
10314    /**
10315     * Called when the user-visibility of this View is potentially affected by a change
10316     * to this view itself, an ancestor view or the window this view is attached to.
10317     *
10318     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10319     *                  and this view's window is also visible
10320     */
10321    @CallSuper
10322    public void onVisibilityAggregated(boolean isVisible) {
10323        if (isVisible && mAttachInfo != null) {
10324            initialAwakenScrollBars();
10325        }
10326
10327        final Drawable dr = mBackground;
10328        if (dr != null && isVisible != dr.isVisible()) {
10329            dr.setVisible(isVisible, false);
10330        }
10331        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10332        if (fg != null && isVisible != fg.isVisible()) {
10333            fg.setVisible(isVisible, false);
10334        }
10335    }
10336
10337    /**
10338     * Returns the current visibility of the window this view is attached to
10339     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10340     *
10341     * @return Returns the current visibility of the view's window.
10342     */
10343    @Visibility
10344    public int getWindowVisibility() {
10345        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10346    }
10347
10348    /**
10349     * Retrieve the overall visible display size in which the window this view is
10350     * attached to has been positioned in.  This takes into account screen
10351     * decorations above the window, for both cases where the window itself
10352     * is being position inside of them or the window is being placed under
10353     * then and covered insets are used for the window to position its content
10354     * inside.  In effect, this tells you the available area where content can
10355     * be placed and remain visible to users.
10356     *
10357     * <p>This function requires an IPC back to the window manager to retrieve
10358     * the requested information, so should not be used in performance critical
10359     * code like drawing.
10360     *
10361     * @param outRect Filled in with the visible display frame.  If the view
10362     * is not attached to a window, this is simply the raw display size.
10363     */
10364    public void getWindowVisibleDisplayFrame(Rect outRect) {
10365        if (mAttachInfo != null) {
10366            try {
10367                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10368            } catch (RemoteException e) {
10369                return;
10370            }
10371            // XXX This is really broken, and probably all needs to be done
10372            // in the window manager, and we need to know more about whether
10373            // we want the area behind or in front of the IME.
10374            final Rect insets = mAttachInfo.mVisibleInsets;
10375            outRect.left += insets.left;
10376            outRect.top += insets.top;
10377            outRect.right -= insets.right;
10378            outRect.bottom -= insets.bottom;
10379            return;
10380        }
10381        // The view is not attached to a display so we don't have a context.
10382        // Make a best guess about the display size.
10383        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10384        d.getRectSize(outRect);
10385    }
10386
10387    /**
10388     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10389     * is currently in without any insets.
10390     *
10391     * @hide
10392     */
10393    public void getWindowDisplayFrame(Rect outRect) {
10394        if (mAttachInfo != null) {
10395            try {
10396                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10397            } catch (RemoteException e) {
10398                return;
10399            }
10400            return;
10401        }
10402        // The view is not attached to a display so we don't have a context.
10403        // Make a best guess about the display size.
10404        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10405        d.getRectSize(outRect);
10406    }
10407
10408    /**
10409     * Dispatch a notification about a resource configuration change down
10410     * the view hierarchy.
10411     * ViewGroups should override to route to their children.
10412     *
10413     * @param newConfig The new resource configuration.
10414     *
10415     * @see #onConfigurationChanged(android.content.res.Configuration)
10416     */
10417    public void dispatchConfigurationChanged(Configuration newConfig) {
10418        onConfigurationChanged(newConfig);
10419    }
10420
10421    /**
10422     * Called when the current configuration of the resources being used
10423     * by the application have changed.  You can use this to decide when
10424     * to reload resources that can changed based on orientation and other
10425     * configuration characteristics.  You only need to use this if you are
10426     * not relying on the normal {@link android.app.Activity} mechanism of
10427     * recreating the activity instance upon a configuration change.
10428     *
10429     * @param newConfig The new resource configuration.
10430     */
10431    protected void onConfigurationChanged(Configuration newConfig) {
10432    }
10433
10434    /**
10435     * Private function to aggregate all per-view attributes in to the view
10436     * root.
10437     */
10438    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10439        performCollectViewAttributes(attachInfo, visibility);
10440    }
10441
10442    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10443        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10444            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10445                attachInfo.mKeepScreenOn = true;
10446            }
10447            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10448            ListenerInfo li = mListenerInfo;
10449            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10450                attachInfo.mHasSystemUiListeners = true;
10451            }
10452        }
10453    }
10454
10455    void needGlobalAttributesUpdate(boolean force) {
10456        final AttachInfo ai = mAttachInfo;
10457        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10458            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10459                    || ai.mHasSystemUiListeners) {
10460                ai.mRecomputeGlobalAttributes = true;
10461            }
10462        }
10463    }
10464
10465    /**
10466     * Returns whether the device is currently in touch mode.  Touch mode is entered
10467     * once the user begins interacting with the device by touch, and affects various
10468     * things like whether focus is always visible to the user.
10469     *
10470     * @return Whether the device is in touch mode.
10471     */
10472    @ViewDebug.ExportedProperty
10473    public boolean isInTouchMode() {
10474        if (mAttachInfo != null) {
10475            return mAttachInfo.mInTouchMode;
10476        } else {
10477            return ViewRootImpl.isInTouchMode();
10478        }
10479    }
10480
10481    /**
10482     * Returns the context the view is running in, through which it can
10483     * access the current theme, resources, etc.
10484     *
10485     * @return The view's Context.
10486     */
10487    @ViewDebug.CapturedViewProperty
10488    public final Context getContext() {
10489        return mContext;
10490    }
10491
10492    /**
10493     * Handle a key event before it is processed by any input method
10494     * associated with the view hierarchy.  This can be used to intercept
10495     * key events in special situations before the IME consumes them; a
10496     * typical example would be handling the BACK key to update the application's
10497     * UI instead of allowing the IME to see it and close itself.
10498     *
10499     * @param keyCode The value in event.getKeyCode().
10500     * @param event Description of the key event.
10501     * @return If you handled the event, return true. If you want to allow the
10502     *         event to be handled by the next receiver, return false.
10503     */
10504    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10505        return false;
10506    }
10507
10508    /**
10509     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10510     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10511     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10512     * is released, if the view is enabled and clickable.
10513     * <p>
10514     * Key presses in software keyboards will generally NOT trigger this
10515     * listener, although some may elect to do so in some situations. Do not
10516     * rely on this to catch software key presses.
10517     *
10518     * @param keyCode a key code that represents the button pressed, from
10519     *                {@link android.view.KeyEvent}
10520     * @param event the KeyEvent object that defines the button action
10521     */
10522    public boolean onKeyDown(int keyCode, KeyEvent event) {
10523        if (KeyEvent.isConfirmKey(keyCode)) {
10524            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10525                return true;
10526            }
10527
10528            // Long clickable items don't necessarily have to be clickable.
10529            if (((mViewFlags & CLICKABLE) == CLICKABLE
10530                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10531                    && (event.getRepeatCount() == 0)) {
10532                // For the purposes of menu anchoring and drawable hotspots,
10533                // key events are considered to be at the center of the view.
10534                final float x = getWidth() / 2f;
10535                final float y = getHeight() / 2f;
10536                setPressed(true, x, y);
10537                checkForLongClick(0, x, y);
10538                return true;
10539            }
10540        }
10541
10542        return false;
10543    }
10544
10545    /**
10546     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10547     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10548     * the event).
10549     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10550     * although some may elect to do so in some situations. Do not rely on this to
10551     * catch software key presses.
10552     */
10553    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10554        return false;
10555    }
10556
10557    /**
10558     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10559     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10560     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10561     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10562     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10563     * although some may elect to do so in some situations. Do not rely on this to
10564     * catch software key presses.
10565     *
10566     * @param keyCode A key code that represents the button pressed, from
10567     *                {@link android.view.KeyEvent}.
10568     * @param event   The KeyEvent object that defines the button action.
10569     */
10570    public boolean onKeyUp(int keyCode, KeyEvent event) {
10571        if (KeyEvent.isConfirmKey(keyCode)) {
10572            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10573                return true;
10574            }
10575            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10576                setPressed(false);
10577
10578                if (!mHasPerformedLongPress) {
10579                    // This is a tap, so remove the longpress check
10580                    removeLongPressCallback();
10581                    return performClick();
10582                }
10583            }
10584        }
10585        return false;
10586    }
10587
10588    /**
10589     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10590     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10591     * the event).
10592     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10593     * although some may elect to do so in some situations. Do not rely on this to
10594     * catch software key presses.
10595     *
10596     * @param keyCode     A key code that represents the button pressed, from
10597     *                    {@link android.view.KeyEvent}.
10598     * @param repeatCount The number of times the action was made.
10599     * @param event       The KeyEvent object that defines the button action.
10600     */
10601    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10602        return false;
10603    }
10604
10605    /**
10606     * Called on the focused view when a key shortcut event is not handled.
10607     * Override this method to implement local key shortcuts for the View.
10608     * Key shortcuts can also be implemented by setting the
10609     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10610     *
10611     * @param keyCode The value in event.getKeyCode().
10612     * @param event Description of the key event.
10613     * @return If you handled the event, return true. If you want to allow the
10614     *         event to be handled by the next receiver, return false.
10615     */
10616    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10617        return false;
10618    }
10619
10620    /**
10621     * Check whether the called view is a text editor, in which case it
10622     * would make sense to automatically display a soft input window for
10623     * it.  Subclasses should override this if they implement
10624     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10625     * a call on that method would return a non-null InputConnection, and
10626     * they are really a first-class editor that the user would normally
10627     * start typing on when the go into a window containing your view.
10628     *
10629     * <p>The default implementation always returns false.  This does
10630     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10631     * will not be called or the user can not otherwise perform edits on your
10632     * view; it is just a hint to the system that this is not the primary
10633     * purpose of this view.
10634     *
10635     * @return Returns true if this view is a text editor, else false.
10636     */
10637    public boolean onCheckIsTextEditor() {
10638        return false;
10639    }
10640
10641    /**
10642     * Create a new InputConnection for an InputMethod to interact
10643     * with the view.  The default implementation returns null, since it doesn't
10644     * support input methods.  You can override this to implement such support.
10645     * This is only needed for views that take focus and text input.
10646     *
10647     * <p>When implementing this, you probably also want to implement
10648     * {@link #onCheckIsTextEditor()} to indicate you will return a
10649     * non-null InputConnection.</p>
10650     *
10651     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10652     * object correctly and in its entirety, so that the connected IME can rely
10653     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10654     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10655     * must be filled in with the correct cursor position for IMEs to work correctly
10656     * with your application.</p>
10657     *
10658     * @param outAttrs Fill in with attribute information about the connection.
10659     */
10660    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10661        return null;
10662    }
10663
10664    /**
10665     * Called by the {@link android.view.inputmethod.InputMethodManager}
10666     * when a view who is not the current
10667     * input connection target is trying to make a call on the manager.  The
10668     * default implementation returns false; you can override this to return
10669     * true for certain views if you are performing InputConnection proxying
10670     * to them.
10671     * @param view The View that is making the InputMethodManager call.
10672     * @return Return true to allow the call, false to reject.
10673     */
10674    public boolean checkInputConnectionProxy(View view) {
10675        return false;
10676    }
10677
10678    /**
10679     * Show the context menu for this view. It is not safe to hold on to the
10680     * menu after returning from this method.
10681     *
10682     * You should normally not overload this method. Overload
10683     * {@link #onCreateContextMenu(ContextMenu)} or define an
10684     * {@link OnCreateContextMenuListener} to add items to the context menu.
10685     *
10686     * @param menu The context menu to populate
10687     */
10688    public void createContextMenu(ContextMenu menu) {
10689        ContextMenuInfo menuInfo = getContextMenuInfo();
10690
10691        // Sets the current menu info so all items added to menu will have
10692        // my extra info set.
10693        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10694
10695        onCreateContextMenu(menu);
10696        ListenerInfo li = mListenerInfo;
10697        if (li != null && li.mOnCreateContextMenuListener != null) {
10698            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10699        }
10700
10701        // Clear the extra information so subsequent items that aren't mine don't
10702        // have my extra info.
10703        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10704
10705        if (mParent != null) {
10706            mParent.createContextMenu(menu);
10707        }
10708    }
10709
10710    /**
10711     * Views should implement this if they have extra information to associate
10712     * with the context menu. The return result is supplied as a parameter to
10713     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10714     * callback.
10715     *
10716     * @return Extra information about the item for which the context menu
10717     *         should be shown. This information will vary across different
10718     *         subclasses of View.
10719     */
10720    protected ContextMenuInfo getContextMenuInfo() {
10721        return null;
10722    }
10723
10724    /**
10725     * Views should implement this if the view itself is going to add items to
10726     * the context menu.
10727     *
10728     * @param menu the context menu to populate
10729     */
10730    protected void onCreateContextMenu(ContextMenu menu) {
10731    }
10732
10733    /**
10734     * Implement this method to handle trackball motion events.  The
10735     * <em>relative</em> movement of the trackball since the last event
10736     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10737     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10738     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10739     * they will often be fractional values, representing the more fine-grained
10740     * movement information available from a trackball).
10741     *
10742     * @param event The motion event.
10743     * @return True if the event was handled, false otherwise.
10744     */
10745    public boolean onTrackballEvent(MotionEvent event) {
10746        return false;
10747    }
10748
10749    /**
10750     * Implement this method to handle generic motion events.
10751     * <p>
10752     * Generic motion events describe joystick movements, mouse hovers, track pad
10753     * touches, scroll wheel movements and other input events.  The
10754     * {@link MotionEvent#getSource() source} of the motion event specifies
10755     * the class of input that was received.  Implementations of this method
10756     * must examine the bits in the source before processing the event.
10757     * The following code example shows how this is done.
10758     * </p><p>
10759     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10760     * are delivered to the view under the pointer.  All other generic motion events are
10761     * delivered to the focused view.
10762     * </p>
10763     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10764     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10765     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10766     *             // process the joystick movement...
10767     *             return true;
10768     *         }
10769     *     }
10770     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10771     *         switch (event.getAction()) {
10772     *             case MotionEvent.ACTION_HOVER_MOVE:
10773     *                 // process the mouse hover movement...
10774     *                 return true;
10775     *             case MotionEvent.ACTION_SCROLL:
10776     *                 // process the scroll wheel movement...
10777     *                 return true;
10778     *         }
10779     *     }
10780     *     return super.onGenericMotionEvent(event);
10781     * }</pre>
10782     *
10783     * @param event The generic motion event being processed.
10784     * @return True if the event was handled, false otherwise.
10785     */
10786    public boolean onGenericMotionEvent(MotionEvent event) {
10787        return false;
10788    }
10789
10790    /**
10791     * Implement this method to handle hover events.
10792     * <p>
10793     * This method is called whenever a pointer is hovering into, over, or out of the
10794     * bounds of a view and the view is not currently being touched.
10795     * Hover events are represented as pointer events with action
10796     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10797     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10798     * </p>
10799     * <ul>
10800     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10801     * when the pointer enters the bounds of the view.</li>
10802     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10803     * when the pointer has already entered the bounds of the view and has moved.</li>
10804     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10805     * when the pointer has exited the bounds of the view or when the pointer is
10806     * about to go down due to a button click, tap, or similar user action that
10807     * causes the view to be touched.</li>
10808     * </ul>
10809     * <p>
10810     * The view should implement this method to return true to indicate that it is
10811     * handling the hover event, such as by changing its drawable state.
10812     * </p><p>
10813     * The default implementation calls {@link #setHovered} to update the hovered state
10814     * of the view when a hover enter or hover exit event is received, if the view
10815     * is enabled and is clickable.  The default implementation also sends hover
10816     * accessibility events.
10817     * </p>
10818     *
10819     * @param event The motion event that describes the hover.
10820     * @return True if the view handled the hover event.
10821     *
10822     * @see #isHovered
10823     * @see #setHovered
10824     * @see #onHoverChanged
10825     */
10826    public boolean onHoverEvent(MotionEvent event) {
10827        // The root view may receive hover (or touch) events that are outside the bounds of
10828        // the window.  This code ensures that we only send accessibility events for
10829        // hovers that are actually within the bounds of the root view.
10830        final int action = event.getActionMasked();
10831        if (!mSendingHoverAccessibilityEvents) {
10832            if ((action == MotionEvent.ACTION_HOVER_ENTER
10833                    || action == MotionEvent.ACTION_HOVER_MOVE)
10834                    && !hasHoveredChild()
10835                    && pointInView(event.getX(), event.getY())) {
10836                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10837                mSendingHoverAccessibilityEvents = true;
10838            }
10839        } else {
10840            if (action == MotionEvent.ACTION_HOVER_EXIT
10841                    || (action == MotionEvent.ACTION_MOVE
10842                            && !pointInView(event.getX(), event.getY()))) {
10843                mSendingHoverAccessibilityEvents = false;
10844                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10845            }
10846        }
10847
10848        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10849                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10850                && isOnScrollbar(event.getX(), event.getY())) {
10851            awakenScrollBars();
10852        }
10853        if (isHoverable()) {
10854            switch (action) {
10855                case MotionEvent.ACTION_HOVER_ENTER:
10856                    setHovered(true);
10857                    break;
10858                case MotionEvent.ACTION_HOVER_EXIT:
10859                    setHovered(false);
10860                    break;
10861            }
10862
10863            // Dispatch the event to onGenericMotionEvent before returning true.
10864            // This is to provide compatibility with existing applications that
10865            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10866            // break because of the new default handling for hoverable views
10867            // in onHoverEvent.
10868            // Note that onGenericMotionEvent will be called by default when
10869            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10870            dispatchGenericMotionEventInternal(event);
10871            // The event was already handled by calling setHovered(), so always
10872            // return true.
10873            return true;
10874        }
10875
10876        return false;
10877    }
10878
10879    /**
10880     * Returns true if the view should handle {@link #onHoverEvent}
10881     * by calling {@link #setHovered} to change its hovered state.
10882     *
10883     * @return True if the view is hoverable.
10884     */
10885    private boolean isHoverable() {
10886        final int viewFlags = mViewFlags;
10887        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10888            return false;
10889        }
10890
10891        return (viewFlags & CLICKABLE) == CLICKABLE
10892                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10893                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10894    }
10895
10896    /**
10897     * Returns true if the view is currently hovered.
10898     *
10899     * @return True if the view is currently hovered.
10900     *
10901     * @see #setHovered
10902     * @see #onHoverChanged
10903     */
10904    @ViewDebug.ExportedProperty
10905    public boolean isHovered() {
10906        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10907    }
10908
10909    /**
10910     * Sets whether the view is currently hovered.
10911     * <p>
10912     * Calling this method also changes the drawable state of the view.  This
10913     * enables the view to react to hover by using different drawable resources
10914     * to change its appearance.
10915     * </p><p>
10916     * The {@link #onHoverChanged} method is called when the hovered state changes.
10917     * </p>
10918     *
10919     * @param hovered True if the view is hovered.
10920     *
10921     * @see #isHovered
10922     * @see #onHoverChanged
10923     */
10924    public void setHovered(boolean hovered) {
10925        if (hovered) {
10926            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10927                mPrivateFlags |= PFLAG_HOVERED;
10928                refreshDrawableState();
10929                onHoverChanged(true);
10930            }
10931        } else {
10932            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10933                mPrivateFlags &= ~PFLAG_HOVERED;
10934                refreshDrawableState();
10935                onHoverChanged(false);
10936            }
10937        }
10938    }
10939
10940    /**
10941     * Implement this method to handle hover state changes.
10942     * <p>
10943     * This method is called whenever the hover state changes as a result of a
10944     * call to {@link #setHovered}.
10945     * </p>
10946     *
10947     * @param hovered The current hover state, as returned by {@link #isHovered}.
10948     *
10949     * @see #isHovered
10950     * @see #setHovered
10951     */
10952    public void onHoverChanged(boolean hovered) {
10953    }
10954
10955    /**
10956     * Handles scroll bar dragging by mouse input.
10957     *
10958     * @hide
10959     * @param event The motion event.
10960     *
10961     * @return true if the event was handled as a scroll bar dragging, false otherwise.
10962     */
10963    protected boolean handleScrollBarDragging(MotionEvent event) {
10964        if (mScrollCache == null) {
10965            return false;
10966        }
10967        final float x = event.getX();
10968        final float y = event.getY();
10969        final int action = event.getAction();
10970        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
10971                && action != MotionEvent.ACTION_DOWN)
10972                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
10973                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
10974            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10975            return false;
10976        }
10977
10978        switch (action) {
10979            case MotionEvent.ACTION_MOVE:
10980                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
10981                    return false;
10982                }
10983                if (mScrollCache.mScrollBarDraggingState
10984                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
10985                    final Rect bounds = mScrollCache.mScrollBarBounds;
10986                    getVerticalScrollBarBounds(bounds);
10987                    final int range = computeVerticalScrollRange();
10988                    final int offset = computeVerticalScrollOffset();
10989                    final int extent = computeVerticalScrollExtent();
10990
10991                    final int thumbLength = ScrollBarUtils.getThumbLength(
10992                            bounds.height(), bounds.width(), extent, range);
10993                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10994                            bounds.height(), thumbLength, extent, range, offset);
10995
10996                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
10997                    final float maxThumbOffset = bounds.height() - thumbLength;
10998                    final float newThumbOffset =
10999                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11000                    final int height = getHeight();
11001                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11002                            && height > 0 && extent > 0) {
11003                        final int newY = Math.round((range - extent)
11004                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11005                        if (newY != getScrollY()) {
11006                            mScrollCache.mScrollBarDraggingPos = y;
11007                            setScrollY(newY);
11008                        }
11009                    }
11010                    return true;
11011                }
11012                if (mScrollCache.mScrollBarDraggingState
11013                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11014                    final Rect bounds = mScrollCache.mScrollBarBounds;
11015                    getHorizontalScrollBarBounds(bounds);
11016                    final int range = computeHorizontalScrollRange();
11017                    final int offset = computeHorizontalScrollOffset();
11018                    final int extent = computeHorizontalScrollExtent();
11019
11020                    final int thumbLength = ScrollBarUtils.getThumbLength(
11021                            bounds.width(), bounds.height(), extent, range);
11022                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11023                            bounds.width(), thumbLength, extent, range, offset);
11024
11025                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11026                    final float maxThumbOffset = bounds.width() - thumbLength;
11027                    final float newThumbOffset =
11028                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11029                    final int width = getWidth();
11030                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11031                            && width > 0 && extent > 0) {
11032                        final int newX = Math.round((range - extent)
11033                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11034                        if (newX != getScrollX()) {
11035                            mScrollCache.mScrollBarDraggingPos = x;
11036                            setScrollX(newX);
11037                        }
11038                    }
11039                    return true;
11040                }
11041            case MotionEvent.ACTION_DOWN:
11042                if (mScrollCache.state == ScrollabilityCache.OFF) {
11043                    return false;
11044                }
11045                if (isOnVerticalScrollbarThumb(x, y)) {
11046                    mScrollCache.mScrollBarDraggingState =
11047                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11048                    mScrollCache.mScrollBarDraggingPos = y;
11049                    return true;
11050                }
11051                if (isOnHorizontalScrollbarThumb(x, y)) {
11052                    mScrollCache.mScrollBarDraggingState =
11053                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11054                    mScrollCache.mScrollBarDraggingPos = x;
11055                    return true;
11056                }
11057        }
11058        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11059        return false;
11060    }
11061
11062    /**
11063     * Implement this method to handle touch screen motion events.
11064     * <p>
11065     * If this method is used to detect click actions, it is recommended that
11066     * the actions be performed by implementing and calling
11067     * {@link #performClick()}. This will ensure consistent system behavior,
11068     * including:
11069     * <ul>
11070     * <li>obeying click sound preferences
11071     * <li>dispatching OnClickListener calls
11072     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11073     * accessibility features are enabled
11074     * </ul>
11075     *
11076     * @param event The motion event.
11077     * @return True if the event was handled, false otherwise.
11078     */
11079    public boolean onTouchEvent(MotionEvent event) {
11080        final float x = event.getX();
11081        final float y = event.getY();
11082        final int viewFlags = mViewFlags;
11083        final int action = event.getAction();
11084
11085        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11086            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11087                setPressed(false);
11088            }
11089            // A disabled view that is clickable still consumes the touch
11090            // events, it just doesn't respond to them.
11091            return (((viewFlags & CLICKABLE) == CLICKABLE
11092                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11093                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11094        }
11095        if (mTouchDelegate != null) {
11096            if (mTouchDelegate.onTouchEvent(event)) {
11097                return true;
11098            }
11099        }
11100
11101        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11102                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11103                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11104            switch (action) {
11105                case MotionEvent.ACTION_UP:
11106                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11107                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11108                        // take focus if we don't have it already and we should in
11109                        // touch mode.
11110                        boolean focusTaken = false;
11111                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11112                            focusTaken = requestFocus();
11113                        }
11114
11115                        if (prepressed) {
11116                            // The button is being released before we actually
11117                            // showed it as pressed.  Make it show the pressed
11118                            // state now (before scheduling the click) to ensure
11119                            // the user sees it.
11120                            setPressed(true, x, y);
11121                       }
11122
11123                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11124                            // This is a tap, so remove the longpress check
11125                            removeLongPressCallback();
11126
11127                            // Only perform take click actions if we were in the pressed state
11128                            if (!focusTaken) {
11129                                // Use a Runnable and post this rather than calling
11130                                // performClick directly. This lets other visual state
11131                                // of the view update before click actions start.
11132                                if (mPerformClick == null) {
11133                                    mPerformClick = new PerformClick();
11134                                }
11135                                if (!post(mPerformClick)) {
11136                                    performClick();
11137                                }
11138                            }
11139                        }
11140
11141                        if (mUnsetPressedState == null) {
11142                            mUnsetPressedState = new UnsetPressedState();
11143                        }
11144
11145                        if (prepressed) {
11146                            postDelayed(mUnsetPressedState,
11147                                    ViewConfiguration.getPressedStateDuration());
11148                        } else if (!post(mUnsetPressedState)) {
11149                            // If the post failed, unpress right now
11150                            mUnsetPressedState.run();
11151                        }
11152
11153                        removeTapCallback();
11154                    }
11155                    mIgnoreNextUpEvent = false;
11156                    break;
11157
11158                case MotionEvent.ACTION_DOWN:
11159                    mHasPerformedLongPress = false;
11160
11161                    if (performButtonActionOnTouchDown(event)) {
11162                        break;
11163                    }
11164
11165                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11166                    boolean isInScrollingContainer = isInScrollingContainer();
11167
11168                    // For views inside a scrolling container, delay the pressed feedback for
11169                    // a short period in case this is a scroll.
11170                    if (isInScrollingContainer) {
11171                        mPrivateFlags |= PFLAG_PREPRESSED;
11172                        if (mPendingCheckForTap == null) {
11173                            mPendingCheckForTap = new CheckForTap();
11174                        }
11175                        mPendingCheckForTap.x = event.getX();
11176                        mPendingCheckForTap.y = event.getY();
11177                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11178                    } else {
11179                        // Not inside a scrolling container, so show the feedback right away
11180                        setPressed(true, x, y);
11181                        checkForLongClick(0, x, y);
11182                    }
11183                    break;
11184
11185                case MotionEvent.ACTION_CANCEL:
11186                    setPressed(false);
11187                    removeTapCallback();
11188                    removeLongPressCallback();
11189                    mInContextButtonPress = false;
11190                    mHasPerformedLongPress = false;
11191                    mIgnoreNextUpEvent = false;
11192                    break;
11193
11194                case MotionEvent.ACTION_MOVE:
11195                    drawableHotspotChanged(x, y);
11196
11197                    // Be lenient about moving outside of buttons
11198                    if (!pointInView(x, y, mTouchSlop)) {
11199                        // Outside button
11200                        removeTapCallback();
11201                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11202                            // Remove any future long press/tap checks
11203                            removeLongPressCallback();
11204
11205                            setPressed(false);
11206                        }
11207                    }
11208                    break;
11209            }
11210
11211            return true;
11212        }
11213
11214        return false;
11215    }
11216
11217    /**
11218     * @hide
11219     */
11220    public boolean isInScrollingContainer() {
11221        ViewParent p = getParent();
11222        while (p != null && p instanceof ViewGroup) {
11223            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11224                return true;
11225            }
11226            p = p.getParent();
11227        }
11228        return false;
11229    }
11230
11231    /**
11232     * Remove the longpress detection timer.
11233     */
11234    private void removeLongPressCallback() {
11235        if (mPendingCheckForLongPress != null) {
11236          removeCallbacks(mPendingCheckForLongPress);
11237        }
11238    }
11239
11240    /**
11241     * Remove the pending click action
11242     */
11243    private void removePerformClickCallback() {
11244        if (mPerformClick != null) {
11245            removeCallbacks(mPerformClick);
11246        }
11247    }
11248
11249    /**
11250     * Remove the prepress detection timer.
11251     */
11252    private void removeUnsetPressCallback() {
11253        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11254            setPressed(false);
11255            removeCallbacks(mUnsetPressedState);
11256        }
11257    }
11258
11259    /**
11260     * Remove the tap detection timer.
11261     */
11262    private void removeTapCallback() {
11263        if (mPendingCheckForTap != null) {
11264            mPrivateFlags &= ~PFLAG_PREPRESSED;
11265            removeCallbacks(mPendingCheckForTap);
11266        }
11267    }
11268
11269    /**
11270     * Cancels a pending long press.  Your subclass can use this if you
11271     * want the context menu to come up if the user presses and holds
11272     * at the same place, but you don't want it to come up if they press
11273     * and then move around enough to cause scrolling.
11274     */
11275    public void cancelLongPress() {
11276        removeLongPressCallback();
11277
11278        /*
11279         * The prepressed state handled by the tap callback is a display
11280         * construct, but the tap callback will post a long press callback
11281         * less its own timeout. Remove it here.
11282         */
11283        removeTapCallback();
11284    }
11285
11286    /**
11287     * Remove the pending callback for sending a
11288     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11289     */
11290    private void removeSendViewScrolledAccessibilityEventCallback() {
11291        if (mSendViewScrolledAccessibilityEvent != null) {
11292            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11293            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11294        }
11295    }
11296
11297    /**
11298     * Sets the TouchDelegate for this View.
11299     */
11300    public void setTouchDelegate(TouchDelegate delegate) {
11301        mTouchDelegate = delegate;
11302    }
11303
11304    /**
11305     * Gets the TouchDelegate for this View.
11306     */
11307    public TouchDelegate getTouchDelegate() {
11308        return mTouchDelegate;
11309    }
11310
11311    /**
11312     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11313     *
11314     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11315     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11316     * available. This method should only be called for touch events.
11317     *
11318     * <p class="note">This api is not intended for most applications. Buffered dispatch
11319     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11320     * streams will not improve your input latency. Side effects include: increased latency,
11321     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11322     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11323     * you.</p>
11324     */
11325    public final void requestUnbufferedDispatch(MotionEvent event) {
11326        final int action = event.getAction();
11327        if (mAttachInfo == null
11328                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11329                || !event.isTouchEvent()) {
11330            return;
11331        }
11332        mAttachInfo.mUnbufferedDispatchRequested = true;
11333    }
11334
11335    /**
11336     * Set flags controlling behavior of this view.
11337     *
11338     * @param flags Constant indicating the value which should be set
11339     * @param mask Constant indicating the bit range that should be changed
11340     */
11341    void setFlags(int flags, int mask) {
11342        final boolean accessibilityEnabled =
11343                AccessibilityManager.getInstance(mContext).isEnabled();
11344        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11345
11346        int old = mViewFlags;
11347        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11348
11349        int changed = mViewFlags ^ old;
11350        if (changed == 0) {
11351            return;
11352        }
11353        int privateFlags = mPrivateFlags;
11354
11355        /* Check if the FOCUSABLE bit has changed */
11356        if (((changed & FOCUSABLE_MASK) != 0) &&
11357                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11358            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11359                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11360                /* Give up focus if we are no longer focusable */
11361                clearFocus();
11362            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11363                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11364                /*
11365                 * Tell the view system that we are now available to take focus
11366                 * if no one else already has it.
11367                 */
11368                if (mParent != null) mParent.focusableViewAvailable(this);
11369            }
11370        }
11371
11372        final int newVisibility = flags & VISIBILITY_MASK;
11373        if (newVisibility == VISIBLE) {
11374            if ((changed & VISIBILITY_MASK) != 0) {
11375                /*
11376                 * If this view is becoming visible, invalidate it in case it changed while
11377                 * it was not visible. Marking it drawn ensures that the invalidation will
11378                 * go through.
11379                 */
11380                mPrivateFlags |= PFLAG_DRAWN;
11381                invalidate(true);
11382
11383                needGlobalAttributesUpdate(true);
11384
11385                // a view becoming visible is worth notifying the parent
11386                // about in case nothing has focus.  even if this specific view
11387                // isn't focusable, it may contain something that is, so let
11388                // the root view try to give this focus if nothing else does.
11389                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11390                    mParent.focusableViewAvailable(this);
11391                }
11392            }
11393        }
11394
11395        /* Check if the GONE bit has changed */
11396        if ((changed & GONE) != 0) {
11397            needGlobalAttributesUpdate(false);
11398            requestLayout();
11399
11400            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11401                if (hasFocus()) clearFocus();
11402                clearAccessibilityFocus();
11403                destroyDrawingCache();
11404                if (mParent instanceof View) {
11405                    // GONE views noop invalidation, so invalidate the parent
11406                    ((View) mParent).invalidate(true);
11407                }
11408                // Mark the view drawn to ensure that it gets invalidated properly the next
11409                // time it is visible and gets invalidated
11410                mPrivateFlags |= PFLAG_DRAWN;
11411            }
11412            if (mAttachInfo != null) {
11413                mAttachInfo.mViewVisibilityChanged = true;
11414            }
11415        }
11416
11417        /* Check if the VISIBLE bit has changed */
11418        if ((changed & INVISIBLE) != 0) {
11419            needGlobalAttributesUpdate(false);
11420            /*
11421             * If this view is becoming invisible, set the DRAWN flag so that
11422             * the next invalidate() will not be skipped.
11423             */
11424            mPrivateFlags |= PFLAG_DRAWN;
11425
11426            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11427                // root view becoming invisible shouldn't clear focus and accessibility focus
11428                if (getRootView() != this) {
11429                    if (hasFocus()) clearFocus();
11430                    clearAccessibilityFocus();
11431                }
11432            }
11433            if (mAttachInfo != null) {
11434                mAttachInfo.mViewVisibilityChanged = true;
11435            }
11436        }
11437
11438        if ((changed & VISIBILITY_MASK) != 0) {
11439            // If the view is invisible, cleanup its display list to free up resources
11440            if (newVisibility != VISIBLE && mAttachInfo != null) {
11441                cleanupDraw();
11442            }
11443
11444            if (mParent instanceof ViewGroup) {
11445                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11446                        (changed & VISIBILITY_MASK), newVisibility);
11447                ((View) mParent).invalidate(true);
11448            } else if (mParent != null) {
11449                mParent.invalidateChild(this, null);
11450            }
11451
11452            if (mAttachInfo != null) {
11453                dispatchVisibilityChanged(this, newVisibility);
11454
11455                // Aggregated visibility changes are dispatched to attached views
11456                // in visible windows where the parent is currently shown/drawn
11457                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11458                // discounting clipping or overlapping. This makes it a good place
11459                // to change animation states.
11460                if (mParent != null && getWindowVisibility() == VISIBLE &&
11461                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11462                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11463                }
11464                notifySubtreeAccessibilityStateChangedIfNeeded();
11465            }
11466        }
11467
11468        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11469            destroyDrawingCache();
11470        }
11471
11472        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11473            destroyDrawingCache();
11474            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11475            invalidateParentCaches();
11476        }
11477
11478        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11479            destroyDrawingCache();
11480            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11481        }
11482
11483        if ((changed & DRAW_MASK) != 0) {
11484            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11485                if (mBackground != null
11486                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11487                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11488                } else {
11489                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11490                }
11491            } else {
11492                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11493            }
11494            requestLayout();
11495            invalidate(true);
11496        }
11497
11498        if ((changed & KEEP_SCREEN_ON) != 0) {
11499            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11500                mParent.recomputeViewAttributes(this);
11501            }
11502        }
11503
11504        if (accessibilityEnabled) {
11505            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11506                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11507                    || (changed & CONTEXT_CLICKABLE) != 0) {
11508                if (oldIncludeForAccessibility != includeForAccessibility()) {
11509                    notifySubtreeAccessibilityStateChangedIfNeeded();
11510                } else {
11511                    notifyViewAccessibilityStateChangedIfNeeded(
11512                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11513                }
11514            } else if ((changed & ENABLED_MASK) != 0) {
11515                notifyViewAccessibilityStateChangedIfNeeded(
11516                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11517            }
11518        }
11519    }
11520
11521    /**
11522     * Change the view's z order in the tree, so it's on top of other sibling
11523     * views. This ordering change may affect layout, if the parent container
11524     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11525     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11526     * method should be followed by calls to {@link #requestLayout()} and
11527     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11528     * with the new child ordering.
11529     *
11530     * @see ViewGroup#bringChildToFront(View)
11531     */
11532    public void bringToFront() {
11533        if (mParent != null) {
11534            mParent.bringChildToFront(this);
11535        }
11536    }
11537
11538    /**
11539     * This is called in response to an internal scroll in this view (i.e., the
11540     * view scrolled its own contents). This is typically as a result of
11541     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11542     * called.
11543     *
11544     * @param l Current horizontal scroll origin.
11545     * @param t Current vertical scroll origin.
11546     * @param oldl Previous horizontal scroll origin.
11547     * @param oldt Previous vertical scroll origin.
11548     */
11549    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11550        notifySubtreeAccessibilityStateChangedIfNeeded();
11551
11552        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11553            postSendViewScrolledAccessibilityEventCallback();
11554        }
11555
11556        mBackgroundSizeChanged = true;
11557        if (mForegroundInfo != null) {
11558            mForegroundInfo.mBoundsChanged = true;
11559        }
11560
11561        final AttachInfo ai = mAttachInfo;
11562        if (ai != null) {
11563            ai.mViewScrollChanged = true;
11564        }
11565
11566        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11567            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11568        }
11569    }
11570
11571    /**
11572     * Interface definition for a callback to be invoked when the scroll
11573     * X or Y positions of a view change.
11574     * <p>
11575     * <b>Note:</b> Some views handle scrolling independently from View and may
11576     * have their own separate listeners for scroll-type events. For example,
11577     * {@link android.widget.ListView ListView} allows clients to register an
11578     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11579     * to listen for changes in list scroll position.
11580     *
11581     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11582     */
11583    public interface OnScrollChangeListener {
11584        /**
11585         * Called when the scroll position of a view changes.
11586         *
11587         * @param v The view whose scroll position has changed.
11588         * @param scrollX Current horizontal scroll origin.
11589         * @param scrollY Current vertical scroll origin.
11590         * @param oldScrollX Previous horizontal scroll origin.
11591         * @param oldScrollY Previous vertical scroll origin.
11592         */
11593        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11594    }
11595
11596    /**
11597     * Interface definition for a callback to be invoked when the layout bounds of a view
11598     * changes due to layout processing.
11599     */
11600    public interface OnLayoutChangeListener {
11601        /**
11602         * Called when the layout bounds of a view changes due to layout processing.
11603         *
11604         * @param v The view whose bounds have changed.
11605         * @param left The new value of the view's left property.
11606         * @param top The new value of the view's top property.
11607         * @param right The new value of the view's right property.
11608         * @param bottom The new value of the view's bottom property.
11609         * @param oldLeft The previous value of the view's left property.
11610         * @param oldTop The previous value of the view's top property.
11611         * @param oldRight The previous value of the view's right property.
11612         * @param oldBottom The previous value of the view's bottom property.
11613         */
11614        void onLayoutChange(View v, int left, int top, int right, int bottom,
11615            int oldLeft, int oldTop, int oldRight, int oldBottom);
11616    }
11617
11618    /**
11619     * This is called during layout when the size of this view has changed. If
11620     * you were just added to the view hierarchy, you're called with the old
11621     * values of 0.
11622     *
11623     * @param w Current width of this view.
11624     * @param h Current height of this view.
11625     * @param oldw Old width of this view.
11626     * @param oldh Old height of this view.
11627     */
11628    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11629    }
11630
11631    /**
11632     * Called by draw to draw the child views. This may be overridden
11633     * by derived classes to gain control just before its children are drawn
11634     * (but after its own view has been drawn).
11635     * @param canvas the canvas on which to draw the view
11636     */
11637    protected void dispatchDraw(Canvas canvas) {
11638
11639    }
11640
11641    /**
11642     * Gets the parent of this view. Note that the parent is a
11643     * ViewParent and not necessarily a View.
11644     *
11645     * @return Parent of this view.
11646     */
11647    public final ViewParent getParent() {
11648        return mParent;
11649    }
11650
11651    /**
11652     * Set the horizontal scrolled position of your view. This will cause a call to
11653     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11654     * invalidated.
11655     * @param value the x position to scroll to
11656     */
11657    public void setScrollX(int value) {
11658        scrollTo(value, mScrollY);
11659    }
11660
11661    /**
11662     * Set the vertical scrolled position of your view. This will cause a call to
11663     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11664     * invalidated.
11665     * @param value the y position to scroll to
11666     */
11667    public void setScrollY(int value) {
11668        scrollTo(mScrollX, value);
11669    }
11670
11671    /**
11672     * Return the scrolled left position of this view. This is the left edge of
11673     * the displayed part of your view. You do not need to draw any pixels
11674     * farther left, since those are outside of the frame of your view on
11675     * screen.
11676     *
11677     * @return The left edge of the displayed part of your view, in pixels.
11678     */
11679    public final int getScrollX() {
11680        return mScrollX;
11681    }
11682
11683    /**
11684     * Return the scrolled top position of this view. This is the top edge of
11685     * the displayed part of your view. You do not need to draw any pixels above
11686     * it, since those are outside of the frame of your view on screen.
11687     *
11688     * @return The top edge of the displayed part of your view, in pixels.
11689     */
11690    public final int getScrollY() {
11691        return mScrollY;
11692    }
11693
11694    /**
11695     * Return the width of the your view.
11696     *
11697     * @return The width of your view, in pixels.
11698     */
11699    @ViewDebug.ExportedProperty(category = "layout")
11700    public final int getWidth() {
11701        return mRight - mLeft;
11702    }
11703
11704    /**
11705     * Return the height of your view.
11706     *
11707     * @return The height of your view, in pixels.
11708     */
11709    @ViewDebug.ExportedProperty(category = "layout")
11710    public final int getHeight() {
11711        return mBottom - mTop;
11712    }
11713
11714    /**
11715     * Return the visible drawing bounds of your view. Fills in the output
11716     * rectangle with the values from getScrollX(), getScrollY(),
11717     * getWidth(), and getHeight(). These bounds do not account for any
11718     * transformation properties currently set on the view, such as
11719     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11720     *
11721     * @param outRect The (scrolled) drawing bounds of the view.
11722     */
11723    public void getDrawingRect(Rect outRect) {
11724        outRect.left = mScrollX;
11725        outRect.top = mScrollY;
11726        outRect.right = mScrollX + (mRight - mLeft);
11727        outRect.bottom = mScrollY + (mBottom - mTop);
11728    }
11729
11730    /**
11731     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11732     * raw width component (that is the result is masked by
11733     * {@link #MEASURED_SIZE_MASK}).
11734     *
11735     * @return The raw measured width of this view.
11736     */
11737    public final int getMeasuredWidth() {
11738        return mMeasuredWidth & MEASURED_SIZE_MASK;
11739    }
11740
11741    /**
11742     * Return the full width measurement information for this view as computed
11743     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11744     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11745     * This should be used during measurement and layout calculations only. Use
11746     * {@link #getWidth()} to see how wide a view is after layout.
11747     *
11748     * @return The measured width of this view as a bit mask.
11749     */
11750    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11751            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11752                    name = "MEASURED_STATE_TOO_SMALL"),
11753    })
11754    public final int getMeasuredWidthAndState() {
11755        return mMeasuredWidth;
11756    }
11757
11758    /**
11759     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11760     * raw height component (that is the result is masked by
11761     * {@link #MEASURED_SIZE_MASK}).
11762     *
11763     * @return The raw measured height of this view.
11764     */
11765    public final int getMeasuredHeight() {
11766        return mMeasuredHeight & MEASURED_SIZE_MASK;
11767    }
11768
11769    /**
11770     * Return the full height measurement information for this view as computed
11771     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11772     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11773     * This should be used during measurement and layout calculations only. Use
11774     * {@link #getHeight()} to see how wide a view is after layout.
11775     *
11776     * @return The measured height of this view as a bit mask.
11777     */
11778    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11779            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11780                    name = "MEASURED_STATE_TOO_SMALL"),
11781    })
11782    public final int getMeasuredHeightAndState() {
11783        return mMeasuredHeight;
11784    }
11785
11786    /**
11787     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11788     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11789     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11790     * and the height component is at the shifted bits
11791     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11792     */
11793    public final int getMeasuredState() {
11794        return (mMeasuredWidth&MEASURED_STATE_MASK)
11795                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11796                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11797    }
11798
11799    /**
11800     * The transform matrix of this view, which is calculated based on the current
11801     * rotation, scale, and pivot properties.
11802     *
11803     * @see #getRotation()
11804     * @see #getScaleX()
11805     * @see #getScaleY()
11806     * @see #getPivotX()
11807     * @see #getPivotY()
11808     * @return The current transform matrix for the view
11809     */
11810    public Matrix getMatrix() {
11811        ensureTransformationInfo();
11812        final Matrix matrix = mTransformationInfo.mMatrix;
11813        mRenderNode.getMatrix(matrix);
11814        return matrix;
11815    }
11816
11817    /**
11818     * Returns true if the transform matrix is the identity matrix.
11819     * Recomputes the matrix if necessary.
11820     *
11821     * @return True if the transform matrix is the identity matrix, false otherwise.
11822     */
11823    final boolean hasIdentityMatrix() {
11824        return mRenderNode.hasIdentityMatrix();
11825    }
11826
11827    void ensureTransformationInfo() {
11828        if (mTransformationInfo == null) {
11829            mTransformationInfo = new TransformationInfo();
11830        }
11831    }
11832
11833    /**
11834     * Utility method to retrieve the inverse of the current mMatrix property.
11835     * We cache the matrix to avoid recalculating it when transform properties
11836     * have not changed.
11837     *
11838     * @return The inverse of the current matrix of this view.
11839     * @hide
11840     */
11841    public final Matrix getInverseMatrix() {
11842        ensureTransformationInfo();
11843        if (mTransformationInfo.mInverseMatrix == null) {
11844            mTransformationInfo.mInverseMatrix = new Matrix();
11845        }
11846        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11847        mRenderNode.getInverseMatrix(matrix);
11848        return matrix;
11849    }
11850
11851    /**
11852     * Gets the distance along the Z axis from the camera to this view.
11853     *
11854     * @see #setCameraDistance(float)
11855     *
11856     * @return The distance along the Z axis.
11857     */
11858    public float getCameraDistance() {
11859        final float dpi = mResources.getDisplayMetrics().densityDpi;
11860        return -(mRenderNode.getCameraDistance() * dpi);
11861    }
11862
11863    /**
11864     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11865     * views are drawn) from the camera to this view. The camera's distance
11866     * affects 3D transformations, for instance rotations around the X and Y
11867     * axis. If the rotationX or rotationY properties are changed and this view is
11868     * large (more than half the size of the screen), it is recommended to always
11869     * use a camera distance that's greater than the height (X axis rotation) or
11870     * the width (Y axis rotation) of this view.</p>
11871     *
11872     * <p>The distance of the camera from the view plane can have an affect on the
11873     * perspective distortion of the view when it is rotated around the x or y axis.
11874     * For example, a large distance will result in a large viewing angle, and there
11875     * will not be much perspective distortion of the view as it rotates. A short
11876     * distance may cause much more perspective distortion upon rotation, and can
11877     * also result in some drawing artifacts if the rotated view ends up partially
11878     * behind the camera (which is why the recommendation is to use a distance at
11879     * least as far as the size of the view, if the view is to be rotated.)</p>
11880     *
11881     * <p>The distance is expressed in "depth pixels." The default distance depends
11882     * on the screen density. For instance, on a medium density display, the
11883     * default distance is 1280. On a high density display, the default distance
11884     * is 1920.</p>
11885     *
11886     * <p>If you want to specify a distance that leads to visually consistent
11887     * results across various densities, use the following formula:</p>
11888     * <pre>
11889     * float scale = context.getResources().getDisplayMetrics().density;
11890     * view.setCameraDistance(distance * scale);
11891     * </pre>
11892     *
11893     * <p>The density scale factor of a high density display is 1.5,
11894     * and 1920 = 1280 * 1.5.</p>
11895     *
11896     * @param distance The distance in "depth pixels", if negative the opposite
11897     *        value is used
11898     *
11899     * @see #setRotationX(float)
11900     * @see #setRotationY(float)
11901     */
11902    public void setCameraDistance(float distance) {
11903        final float dpi = mResources.getDisplayMetrics().densityDpi;
11904
11905        invalidateViewProperty(true, false);
11906        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11907        invalidateViewProperty(false, false);
11908
11909        invalidateParentIfNeededAndWasQuickRejected();
11910    }
11911
11912    /**
11913     * The degrees that the view is rotated around the pivot point.
11914     *
11915     * @see #setRotation(float)
11916     * @see #getPivotX()
11917     * @see #getPivotY()
11918     *
11919     * @return The degrees of rotation.
11920     */
11921    @ViewDebug.ExportedProperty(category = "drawing")
11922    public float getRotation() {
11923        return mRenderNode.getRotation();
11924    }
11925
11926    /**
11927     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11928     * result in clockwise rotation.
11929     *
11930     * @param rotation The degrees of rotation.
11931     *
11932     * @see #getRotation()
11933     * @see #getPivotX()
11934     * @see #getPivotY()
11935     * @see #setRotationX(float)
11936     * @see #setRotationY(float)
11937     *
11938     * @attr ref android.R.styleable#View_rotation
11939     */
11940    public void setRotation(float rotation) {
11941        if (rotation != getRotation()) {
11942            // Double-invalidation is necessary to capture view's old and new areas
11943            invalidateViewProperty(true, false);
11944            mRenderNode.setRotation(rotation);
11945            invalidateViewProperty(false, true);
11946
11947            invalidateParentIfNeededAndWasQuickRejected();
11948            notifySubtreeAccessibilityStateChangedIfNeeded();
11949        }
11950    }
11951
11952    /**
11953     * The degrees that the view is rotated around the vertical axis through the pivot point.
11954     *
11955     * @see #getPivotX()
11956     * @see #getPivotY()
11957     * @see #setRotationY(float)
11958     *
11959     * @return The degrees of Y rotation.
11960     */
11961    @ViewDebug.ExportedProperty(category = "drawing")
11962    public float getRotationY() {
11963        return mRenderNode.getRotationY();
11964    }
11965
11966    /**
11967     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11968     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11969     * down the y axis.
11970     *
11971     * When rotating large views, it is recommended to adjust the camera distance
11972     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11973     *
11974     * @param rotationY The degrees of Y rotation.
11975     *
11976     * @see #getRotationY()
11977     * @see #getPivotX()
11978     * @see #getPivotY()
11979     * @see #setRotation(float)
11980     * @see #setRotationX(float)
11981     * @see #setCameraDistance(float)
11982     *
11983     * @attr ref android.R.styleable#View_rotationY
11984     */
11985    public void setRotationY(float rotationY) {
11986        if (rotationY != getRotationY()) {
11987            invalidateViewProperty(true, false);
11988            mRenderNode.setRotationY(rotationY);
11989            invalidateViewProperty(false, true);
11990
11991            invalidateParentIfNeededAndWasQuickRejected();
11992            notifySubtreeAccessibilityStateChangedIfNeeded();
11993        }
11994    }
11995
11996    /**
11997     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11998     *
11999     * @see #getPivotX()
12000     * @see #getPivotY()
12001     * @see #setRotationX(float)
12002     *
12003     * @return The degrees of X rotation.
12004     */
12005    @ViewDebug.ExportedProperty(category = "drawing")
12006    public float getRotationX() {
12007        return mRenderNode.getRotationX();
12008    }
12009
12010    /**
12011     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12012     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12013     * x axis.
12014     *
12015     * When rotating large views, it is recommended to adjust the camera distance
12016     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12017     *
12018     * @param rotationX The degrees of X rotation.
12019     *
12020     * @see #getRotationX()
12021     * @see #getPivotX()
12022     * @see #getPivotY()
12023     * @see #setRotation(float)
12024     * @see #setRotationY(float)
12025     * @see #setCameraDistance(float)
12026     *
12027     * @attr ref android.R.styleable#View_rotationX
12028     */
12029    public void setRotationX(float rotationX) {
12030        if (rotationX != getRotationX()) {
12031            invalidateViewProperty(true, false);
12032            mRenderNode.setRotationX(rotationX);
12033            invalidateViewProperty(false, true);
12034
12035            invalidateParentIfNeededAndWasQuickRejected();
12036            notifySubtreeAccessibilityStateChangedIfNeeded();
12037        }
12038    }
12039
12040    /**
12041     * The amount that the view is scaled in x around the pivot point, as a proportion of
12042     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12043     *
12044     * <p>By default, this is 1.0f.
12045     *
12046     * @see #getPivotX()
12047     * @see #getPivotY()
12048     * @return The scaling factor.
12049     */
12050    @ViewDebug.ExportedProperty(category = "drawing")
12051    public float getScaleX() {
12052        return mRenderNode.getScaleX();
12053    }
12054
12055    /**
12056     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12057     * the view's unscaled width. A value of 1 means that no scaling is applied.
12058     *
12059     * @param scaleX The scaling factor.
12060     * @see #getPivotX()
12061     * @see #getPivotY()
12062     *
12063     * @attr ref android.R.styleable#View_scaleX
12064     */
12065    public void setScaleX(float scaleX) {
12066        if (scaleX != getScaleX()) {
12067            invalidateViewProperty(true, false);
12068            mRenderNode.setScaleX(scaleX);
12069            invalidateViewProperty(false, true);
12070
12071            invalidateParentIfNeededAndWasQuickRejected();
12072            notifySubtreeAccessibilityStateChangedIfNeeded();
12073        }
12074    }
12075
12076    /**
12077     * The amount that the view is scaled in y around the pivot point, as a proportion of
12078     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12079     *
12080     * <p>By default, this is 1.0f.
12081     *
12082     * @see #getPivotX()
12083     * @see #getPivotY()
12084     * @return The scaling factor.
12085     */
12086    @ViewDebug.ExportedProperty(category = "drawing")
12087    public float getScaleY() {
12088        return mRenderNode.getScaleY();
12089    }
12090
12091    /**
12092     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12093     * the view's unscaled width. A value of 1 means that no scaling is applied.
12094     *
12095     * @param scaleY The scaling factor.
12096     * @see #getPivotX()
12097     * @see #getPivotY()
12098     *
12099     * @attr ref android.R.styleable#View_scaleY
12100     */
12101    public void setScaleY(float scaleY) {
12102        if (scaleY != getScaleY()) {
12103            invalidateViewProperty(true, false);
12104            mRenderNode.setScaleY(scaleY);
12105            invalidateViewProperty(false, true);
12106
12107            invalidateParentIfNeededAndWasQuickRejected();
12108            notifySubtreeAccessibilityStateChangedIfNeeded();
12109        }
12110    }
12111
12112    /**
12113     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12114     * and {@link #setScaleX(float) scaled}.
12115     *
12116     * @see #getRotation()
12117     * @see #getScaleX()
12118     * @see #getScaleY()
12119     * @see #getPivotY()
12120     * @return The x location of the pivot point.
12121     *
12122     * @attr ref android.R.styleable#View_transformPivotX
12123     */
12124    @ViewDebug.ExportedProperty(category = "drawing")
12125    public float getPivotX() {
12126        return mRenderNode.getPivotX();
12127    }
12128
12129    /**
12130     * Sets the x location of the point around which the view is
12131     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12132     * By default, the pivot point is centered on the object.
12133     * Setting this property disables this behavior and causes the view to use only the
12134     * explicitly set pivotX and pivotY values.
12135     *
12136     * @param pivotX The x location of the pivot point.
12137     * @see #getRotation()
12138     * @see #getScaleX()
12139     * @see #getScaleY()
12140     * @see #getPivotY()
12141     *
12142     * @attr ref android.R.styleable#View_transformPivotX
12143     */
12144    public void setPivotX(float pivotX) {
12145        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12146            invalidateViewProperty(true, false);
12147            mRenderNode.setPivotX(pivotX);
12148            invalidateViewProperty(false, true);
12149
12150            invalidateParentIfNeededAndWasQuickRejected();
12151        }
12152    }
12153
12154    /**
12155     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12156     * and {@link #setScaleY(float) scaled}.
12157     *
12158     * @see #getRotation()
12159     * @see #getScaleX()
12160     * @see #getScaleY()
12161     * @see #getPivotY()
12162     * @return The y location of the pivot point.
12163     *
12164     * @attr ref android.R.styleable#View_transformPivotY
12165     */
12166    @ViewDebug.ExportedProperty(category = "drawing")
12167    public float getPivotY() {
12168        return mRenderNode.getPivotY();
12169    }
12170
12171    /**
12172     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12173     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12174     * Setting this property disables this behavior and causes the view to use only the
12175     * explicitly set pivotX and pivotY values.
12176     *
12177     * @param pivotY The y location of the pivot point.
12178     * @see #getRotation()
12179     * @see #getScaleX()
12180     * @see #getScaleY()
12181     * @see #getPivotY()
12182     *
12183     * @attr ref android.R.styleable#View_transformPivotY
12184     */
12185    public void setPivotY(float pivotY) {
12186        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12187            invalidateViewProperty(true, false);
12188            mRenderNode.setPivotY(pivotY);
12189            invalidateViewProperty(false, true);
12190
12191            invalidateParentIfNeededAndWasQuickRejected();
12192        }
12193    }
12194
12195    /**
12196     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12197     * completely transparent and 1 means the view is completely opaque.
12198     *
12199     * <p>By default this is 1.0f.
12200     * @return The opacity of the view.
12201     */
12202    @ViewDebug.ExportedProperty(category = "drawing")
12203    public float getAlpha() {
12204        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12205    }
12206
12207    /**
12208     * Sets the behavior for overlapping rendering for this view (see {@link
12209     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12210     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12211     * providing the value which is then used internally. That is, when {@link
12212     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12213     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12214     * instead.
12215     *
12216     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12217     * instead of that returned by {@link #hasOverlappingRendering()}.
12218     *
12219     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12220     */
12221    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12222        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12223        if (hasOverlappingRendering) {
12224            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12225        } else {
12226            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12227        }
12228    }
12229
12230    /**
12231     * Returns the value for overlapping rendering that is used internally. This is either
12232     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12233     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12234     *
12235     * @return The value for overlapping rendering being used internally.
12236     */
12237    public final boolean getHasOverlappingRendering() {
12238        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12239                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12240                hasOverlappingRendering();
12241    }
12242
12243    /**
12244     * Returns whether this View has content which overlaps.
12245     *
12246     * <p>This function, intended to be overridden by specific View types, is an optimization when
12247     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12248     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12249     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12250     * directly. An example of overlapping rendering is a TextView with a background image, such as
12251     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12252     * ImageView with only the foreground image. The default implementation returns true; subclasses
12253     * should override if they have cases which can be optimized.</p>
12254     *
12255     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12256     * necessitates that a View return true if it uses the methods internally without passing the
12257     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12258     *
12259     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12260     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12261     *
12262     * @return true if the content in this view might overlap, false otherwise.
12263     */
12264    @ViewDebug.ExportedProperty(category = "drawing")
12265    public boolean hasOverlappingRendering() {
12266        return true;
12267    }
12268
12269    /**
12270     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12271     * completely transparent and 1 means the view is completely opaque.
12272     *
12273     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12274     * can have significant performance implications, especially for large views. It is best to use
12275     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12276     *
12277     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12278     * strongly recommended for performance reasons to either override
12279     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12280     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12281     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12282     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12283     * of rendering cost, even for simple or small views. Starting with
12284     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12285     * applied to the view at the rendering level.</p>
12286     *
12287     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12288     * responsible for applying the opacity itself.</p>
12289     *
12290     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12291     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12292     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12293     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12294     *
12295     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12296     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12297     * {@link #hasOverlappingRendering}.</p>
12298     *
12299     * @param alpha The opacity of the view.
12300     *
12301     * @see #hasOverlappingRendering()
12302     * @see #setLayerType(int, android.graphics.Paint)
12303     *
12304     * @attr ref android.R.styleable#View_alpha
12305     */
12306    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12307        ensureTransformationInfo();
12308        if (mTransformationInfo.mAlpha != alpha) {
12309            mTransformationInfo.mAlpha = alpha;
12310            if (onSetAlpha((int) (alpha * 255))) {
12311                mPrivateFlags |= PFLAG_ALPHA_SET;
12312                // subclass is handling alpha - don't optimize rendering cache invalidation
12313                invalidateParentCaches();
12314                invalidate(true);
12315            } else {
12316                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12317                invalidateViewProperty(true, false);
12318                mRenderNode.setAlpha(getFinalAlpha());
12319                notifyViewAccessibilityStateChangedIfNeeded(
12320                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12321            }
12322        }
12323    }
12324
12325    /**
12326     * Faster version of setAlpha() which performs the same steps except there are
12327     * no calls to invalidate(). The caller of this function should perform proper invalidation
12328     * on the parent and this object. The return value indicates whether the subclass handles
12329     * alpha (the return value for onSetAlpha()).
12330     *
12331     * @param alpha The new value for the alpha property
12332     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12333     *         the new value for the alpha property is different from the old value
12334     */
12335    boolean setAlphaNoInvalidation(float alpha) {
12336        ensureTransformationInfo();
12337        if (mTransformationInfo.mAlpha != alpha) {
12338            mTransformationInfo.mAlpha = alpha;
12339            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12340            if (subclassHandlesAlpha) {
12341                mPrivateFlags |= PFLAG_ALPHA_SET;
12342                return true;
12343            } else {
12344                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12345                mRenderNode.setAlpha(getFinalAlpha());
12346            }
12347        }
12348        return false;
12349    }
12350
12351    /**
12352     * This property is hidden and intended only for use by the Fade transition, which
12353     * animates it to produce a visual translucency that does not side-effect (or get
12354     * affected by) the real alpha property. This value is composited with the other
12355     * alpha value (and the AlphaAnimation value, when that is present) to produce
12356     * a final visual translucency result, which is what is passed into the DisplayList.
12357     *
12358     * @hide
12359     */
12360    public void setTransitionAlpha(float alpha) {
12361        ensureTransformationInfo();
12362        if (mTransformationInfo.mTransitionAlpha != alpha) {
12363            mTransformationInfo.mTransitionAlpha = alpha;
12364            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12365            invalidateViewProperty(true, false);
12366            mRenderNode.setAlpha(getFinalAlpha());
12367        }
12368    }
12369
12370    /**
12371     * Calculates the visual alpha of this view, which is a combination of the actual
12372     * alpha value and the transitionAlpha value (if set).
12373     */
12374    private float getFinalAlpha() {
12375        if (mTransformationInfo != null) {
12376            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12377        }
12378        return 1;
12379    }
12380
12381    /**
12382     * This property is hidden and intended only for use by the Fade transition, which
12383     * animates it to produce a visual translucency that does not side-effect (or get
12384     * affected by) the real alpha property. This value is composited with the other
12385     * alpha value (and the AlphaAnimation value, when that is present) to produce
12386     * a final visual translucency result, which is what is passed into the DisplayList.
12387     *
12388     * @hide
12389     */
12390    @ViewDebug.ExportedProperty(category = "drawing")
12391    public float getTransitionAlpha() {
12392        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12393    }
12394
12395    /**
12396     * Top position of this view relative to its parent.
12397     *
12398     * @return The top of this view, in pixels.
12399     */
12400    @ViewDebug.CapturedViewProperty
12401    public final int getTop() {
12402        return mTop;
12403    }
12404
12405    /**
12406     * Sets the top position of this view relative to its parent. This method is meant to be called
12407     * by the layout system and should not generally be called otherwise, because the property
12408     * may be changed at any time by the layout.
12409     *
12410     * @param top The top of this view, in pixels.
12411     */
12412    public final void setTop(int top) {
12413        if (top != mTop) {
12414            final boolean matrixIsIdentity = hasIdentityMatrix();
12415            if (matrixIsIdentity) {
12416                if (mAttachInfo != null) {
12417                    int minTop;
12418                    int yLoc;
12419                    if (top < mTop) {
12420                        minTop = top;
12421                        yLoc = top - mTop;
12422                    } else {
12423                        minTop = mTop;
12424                        yLoc = 0;
12425                    }
12426                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12427                }
12428            } else {
12429                // Double-invalidation is necessary to capture view's old and new areas
12430                invalidate(true);
12431            }
12432
12433            int width = mRight - mLeft;
12434            int oldHeight = mBottom - mTop;
12435
12436            mTop = top;
12437            mRenderNode.setTop(mTop);
12438
12439            sizeChange(width, mBottom - mTop, width, oldHeight);
12440
12441            if (!matrixIsIdentity) {
12442                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12443                invalidate(true);
12444            }
12445            mBackgroundSizeChanged = true;
12446            if (mForegroundInfo != null) {
12447                mForegroundInfo.mBoundsChanged = true;
12448            }
12449            invalidateParentIfNeeded();
12450            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12451                // View was rejected last time it was drawn by its parent; this may have changed
12452                invalidateParentIfNeeded();
12453            }
12454        }
12455    }
12456
12457    /**
12458     * Bottom position of this view relative to its parent.
12459     *
12460     * @return The bottom of this view, in pixels.
12461     */
12462    @ViewDebug.CapturedViewProperty
12463    public final int getBottom() {
12464        return mBottom;
12465    }
12466
12467    /**
12468     * True if this view has changed since the last time being drawn.
12469     *
12470     * @return The dirty state of this view.
12471     */
12472    public boolean isDirty() {
12473        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12474    }
12475
12476    /**
12477     * Sets the bottom position of this view relative to its parent. This method is meant to be
12478     * called by the layout system and should not generally be called otherwise, because the
12479     * property may be changed at any time by the layout.
12480     *
12481     * @param bottom The bottom of this view, in pixels.
12482     */
12483    public final void setBottom(int bottom) {
12484        if (bottom != mBottom) {
12485            final boolean matrixIsIdentity = hasIdentityMatrix();
12486            if (matrixIsIdentity) {
12487                if (mAttachInfo != null) {
12488                    int maxBottom;
12489                    if (bottom < mBottom) {
12490                        maxBottom = mBottom;
12491                    } else {
12492                        maxBottom = bottom;
12493                    }
12494                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12495                }
12496            } else {
12497                // Double-invalidation is necessary to capture view's old and new areas
12498                invalidate(true);
12499            }
12500
12501            int width = mRight - mLeft;
12502            int oldHeight = mBottom - mTop;
12503
12504            mBottom = bottom;
12505            mRenderNode.setBottom(mBottom);
12506
12507            sizeChange(width, mBottom - mTop, width, oldHeight);
12508
12509            if (!matrixIsIdentity) {
12510                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12511                invalidate(true);
12512            }
12513            mBackgroundSizeChanged = true;
12514            if (mForegroundInfo != null) {
12515                mForegroundInfo.mBoundsChanged = true;
12516            }
12517            invalidateParentIfNeeded();
12518            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12519                // View was rejected last time it was drawn by its parent; this may have changed
12520                invalidateParentIfNeeded();
12521            }
12522        }
12523    }
12524
12525    /**
12526     * Left position of this view relative to its parent.
12527     *
12528     * @return The left edge of this view, in pixels.
12529     */
12530    @ViewDebug.CapturedViewProperty
12531    public final int getLeft() {
12532        return mLeft;
12533    }
12534
12535    /**
12536     * Sets the left position of this view relative to its parent. This method is meant to be called
12537     * by the layout system and should not generally be called otherwise, because the property
12538     * may be changed at any time by the layout.
12539     *
12540     * @param left The left of this view, in pixels.
12541     */
12542    public final void setLeft(int left) {
12543        if (left != mLeft) {
12544            final boolean matrixIsIdentity = hasIdentityMatrix();
12545            if (matrixIsIdentity) {
12546                if (mAttachInfo != null) {
12547                    int minLeft;
12548                    int xLoc;
12549                    if (left < mLeft) {
12550                        minLeft = left;
12551                        xLoc = left - mLeft;
12552                    } else {
12553                        minLeft = mLeft;
12554                        xLoc = 0;
12555                    }
12556                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12557                }
12558            } else {
12559                // Double-invalidation is necessary to capture view's old and new areas
12560                invalidate(true);
12561            }
12562
12563            int oldWidth = mRight - mLeft;
12564            int height = mBottom - mTop;
12565
12566            mLeft = left;
12567            mRenderNode.setLeft(left);
12568
12569            sizeChange(mRight - mLeft, height, oldWidth, height);
12570
12571            if (!matrixIsIdentity) {
12572                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12573                invalidate(true);
12574            }
12575            mBackgroundSizeChanged = true;
12576            if (mForegroundInfo != null) {
12577                mForegroundInfo.mBoundsChanged = true;
12578            }
12579            invalidateParentIfNeeded();
12580            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12581                // View was rejected last time it was drawn by its parent; this may have changed
12582                invalidateParentIfNeeded();
12583            }
12584        }
12585    }
12586
12587    /**
12588     * Right position of this view relative to its parent.
12589     *
12590     * @return The right edge of this view, in pixels.
12591     */
12592    @ViewDebug.CapturedViewProperty
12593    public final int getRight() {
12594        return mRight;
12595    }
12596
12597    /**
12598     * Sets the right position of this view relative to its parent. This method is meant to be called
12599     * by the layout system and should not generally be called otherwise, because the property
12600     * may be changed at any time by the layout.
12601     *
12602     * @param right The right of this view, in pixels.
12603     */
12604    public final void setRight(int right) {
12605        if (right != mRight) {
12606            final boolean matrixIsIdentity = hasIdentityMatrix();
12607            if (matrixIsIdentity) {
12608                if (mAttachInfo != null) {
12609                    int maxRight;
12610                    if (right < mRight) {
12611                        maxRight = mRight;
12612                    } else {
12613                        maxRight = right;
12614                    }
12615                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12616                }
12617            } else {
12618                // Double-invalidation is necessary to capture view's old and new areas
12619                invalidate(true);
12620            }
12621
12622            int oldWidth = mRight - mLeft;
12623            int height = mBottom - mTop;
12624
12625            mRight = right;
12626            mRenderNode.setRight(mRight);
12627
12628            sizeChange(mRight - mLeft, height, oldWidth, height);
12629
12630            if (!matrixIsIdentity) {
12631                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12632                invalidate(true);
12633            }
12634            mBackgroundSizeChanged = true;
12635            if (mForegroundInfo != null) {
12636                mForegroundInfo.mBoundsChanged = true;
12637            }
12638            invalidateParentIfNeeded();
12639            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12640                // View was rejected last time it was drawn by its parent; this may have changed
12641                invalidateParentIfNeeded();
12642            }
12643        }
12644    }
12645
12646    /**
12647     * The visual x position of this view, in pixels. This is equivalent to the
12648     * {@link #setTranslationX(float) translationX} property plus the current
12649     * {@link #getLeft() left} property.
12650     *
12651     * @return The visual x position of this view, in pixels.
12652     */
12653    @ViewDebug.ExportedProperty(category = "drawing")
12654    public float getX() {
12655        return mLeft + getTranslationX();
12656    }
12657
12658    /**
12659     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12660     * {@link #setTranslationX(float) translationX} property to be the difference between
12661     * the x value passed in and the current {@link #getLeft() left} property.
12662     *
12663     * @param x The visual x position of this view, in pixels.
12664     */
12665    public void setX(float x) {
12666        setTranslationX(x - mLeft);
12667    }
12668
12669    /**
12670     * The visual y position of this view, in pixels. This is equivalent to the
12671     * {@link #setTranslationY(float) translationY} property plus the current
12672     * {@link #getTop() top} property.
12673     *
12674     * @return The visual y position of this view, in pixels.
12675     */
12676    @ViewDebug.ExportedProperty(category = "drawing")
12677    public float getY() {
12678        return mTop + getTranslationY();
12679    }
12680
12681    /**
12682     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12683     * {@link #setTranslationY(float) translationY} property to be the difference between
12684     * the y value passed in and the current {@link #getTop() top} property.
12685     *
12686     * @param y The visual y position of this view, in pixels.
12687     */
12688    public void setY(float y) {
12689        setTranslationY(y - mTop);
12690    }
12691
12692    /**
12693     * The visual z position of this view, in pixels. This is equivalent to the
12694     * {@link #setTranslationZ(float) translationZ} property plus the current
12695     * {@link #getElevation() elevation} property.
12696     *
12697     * @return The visual z position of this view, in pixels.
12698     */
12699    @ViewDebug.ExportedProperty(category = "drawing")
12700    public float getZ() {
12701        return getElevation() + getTranslationZ();
12702    }
12703
12704    /**
12705     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12706     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12707     * the x value passed in and the current {@link #getElevation() elevation} property.
12708     *
12709     * @param z The visual z position of this view, in pixels.
12710     */
12711    public void setZ(float z) {
12712        setTranslationZ(z - getElevation());
12713    }
12714
12715    /**
12716     * The base elevation of this view relative to its parent, in pixels.
12717     *
12718     * @return The base depth position of the view, in pixels.
12719     */
12720    @ViewDebug.ExportedProperty(category = "drawing")
12721    public float getElevation() {
12722        return mRenderNode.getElevation();
12723    }
12724
12725    /**
12726     * Sets the base elevation of this view, in pixels.
12727     *
12728     * @attr ref android.R.styleable#View_elevation
12729     */
12730    public void setElevation(float elevation) {
12731        if (elevation != getElevation()) {
12732            invalidateViewProperty(true, false);
12733            mRenderNode.setElevation(elevation);
12734            invalidateViewProperty(false, true);
12735
12736            invalidateParentIfNeededAndWasQuickRejected();
12737        }
12738    }
12739
12740    /**
12741     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12742     * This position is post-layout, in addition to wherever the object's
12743     * layout placed it.
12744     *
12745     * @return The horizontal position of this view relative to its left position, in pixels.
12746     */
12747    @ViewDebug.ExportedProperty(category = "drawing")
12748    public float getTranslationX() {
12749        return mRenderNode.getTranslationX();
12750    }
12751
12752    /**
12753     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12754     * This effectively positions the object post-layout, in addition to wherever the object's
12755     * layout placed it.
12756     *
12757     * @param translationX The horizontal position of this view relative to its left position,
12758     * in pixels.
12759     *
12760     * @attr ref android.R.styleable#View_translationX
12761     */
12762    public void setTranslationX(float translationX) {
12763        if (translationX != getTranslationX()) {
12764            invalidateViewProperty(true, false);
12765            mRenderNode.setTranslationX(translationX);
12766            invalidateViewProperty(false, true);
12767
12768            invalidateParentIfNeededAndWasQuickRejected();
12769            notifySubtreeAccessibilityStateChangedIfNeeded();
12770        }
12771    }
12772
12773    /**
12774     * The vertical location of this view relative to its {@link #getTop() top} position.
12775     * This position is post-layout, in addition to wherever the object's
12776     * layout placed it.
12777     *
12778     * @return The vertical position of this view relative to its top position,
12779     * in pixels.
12780     */
12781    @ViewDebug.ExportedProperty(category = "drawing")
12782    public float getTranslationY() {
12783        return mRenderNode.getTranslationY();
12784    }
12785
12786    /**
12787     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12788     * This effectively positions the object post-layout, in addition to wherever the object's
12789     * layout placed it.
12790     *
12791     * @param translationY The vertical position of this view relative to its top position,
12792     * in pixels.
12793     *
12794     * @attr ref android.R.styleable#View_translationY
12795     */
12796    public void setTranslationY(float translationY) {
12797        if (translationY != getTranslationY()) {
12798            invalidateViewProperty(true, false);
12799            mRenderNode.setTranslationY(translationY);
12800            invalidateViewProperty(false, true);
12801
12802            invalidateParentIfNeededAndWasQuickRejected();
12803            notifySubtreeAccessibilityStateChangedIfNeeded();
12804        }
12805    }
12806
12807    /**
12808     * The depth location of this view relative to its {@link #getElevation() elevation}.
12809     *
12810     * @return The depth of this view relative to its elevation.
12811     */
12812    @ViewDebug.ExportedProperty(category = "drawing")
12813    public float getTranslationZ() {
12814        return mRenderNode.getTranslationZ();
12815    }
12816
12817    /**
12818     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12819     *
12820     * @attr ref android.R.styleable#View_translationZ
12821     */
12822    public void setTranslationZ(float translationZ) {
12823        if (translationZ != getTranslationZ()) {
12824            invalidateViewProperty(true, false);
12825            mRenderNode.setTranslationZ(translationZ);
12826            invalidateViewProperty(false, true);
12827
12828            invalidateParentIfNeededAndWasQuickRejected();
12829        }
12830    }
12831
12832    /** @hide */
12833    public void setAnimationMatrix(Matrix matrix) {
12834        invalidateViewProperty(true, false);
12835        mRenderNode.setAnimationMatrix(matrix);
12836        invalidateViewProperty(false, true);
12837
12838        invalidateParentIfNeededAndWasQuickRejected();
12839    }
12840
12841    /**
12842     * Returns the current StateListAnimator if exists.
12843     *
12844     * @return StateListAnimator or null if it does not exists
12845     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12846     */
12847    public StateListAnimator getStateListAnimator() {
12848        return mStateListAnimator;
12849    }
12850
12851    /**
12852     * Attaches the provided StateListAnimator to this View.
12853     * <p>
12854     * Any previously attached StateListAnimator will be detached.
12855     *
12856     * @param stateListAnimator The StateListAnimator to update the view
12857     * @see {@link android.animation.StateListAnimator}
12858     */
12859    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12860        if (mStateListAnimator == stateListAnimator) {
12861            return;
12862        }
12863        if (mStateListAnimator != null) {
12864            mStateListAnimator.setTarget(null);
12865        }
12866        mStateListAnimator = stateListAnimator;
12867        if (stateListAnimator != null) {
12868            stateListAnimator.setTarget(this);
12869            if (isAttachedToWindow()) {
12870                stateListAnimator.setState(getDrawableState());
12871            }
12872        }
12873    }
12874
12875    /**
12876     * Returns whether the Outline should be used to clip the contents of the View.
12877     * <p>
12878     * Note that this flag will only be respected if the View's Outline returns true from
12879     * {@link Outline#canClip()}.
12880     *
12881     * @see #setOutlineProvider(ViewOutlineProvider)
12882     * @see #setClipToOutline(boolean)
12883     */
12884    public final boolean getClipToOutline() {
12885        return mRenderNode.getClipToOutline();
12886    }
12887
12888    /**
12889     * Sets whether the View's Outline should be used to clip the contents of the View.
12890     * <p>
12891     * Only a single non-rectangular clip can be applied on a View at any time.
12892     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12893     * circular reveal} animation take priority over Outline clipping, and
12894     * child Outline clipping takes priority over Outline clipping done by a
12895     * parent.
12896     * <p>
12897     * Note that this flag will only be respected if the View's Outline returns true from
12898     * {@link Outline#canClip()}.
12899     *
12900     * @see #setOutlineProvider(ViewOutlineProvider)
12901     * @see #getClipToOutline()
12902     */
12903    public void setClipToOutline(boolean clipToOutline) {
12904        damageInParent();
12905        if (getClipToOutline() != clipToOutline) {
12906            mRenderNode.setClipToOutline(clipToOutline);
12907        }
12908    }
12909
12910    // correspond to the enum values of View_outlineProvider
12911    private static final int PROVIDER_BACKGROUND = 0;
12912    private static final int PROVIDER_NONE = 1;
12913    private static final int PROVIDER_BOUNDS = 2;
12914    private static final int PROVIDER_PADDED_BOUNDS = 3;
12915    private void setOutlineProviderFromAttribute(int providerInt) {
12916        switch (providerInt) {
12917            case PROVIDER_BACKGROUND:
12918                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12919                break;
12920            case PROVIDER_NONE:
12921                setOutlineProvider(null);
12922                break;
12923            case PROVIDER_BOUNDS:
12924                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12925                break;
12926            case PROVIDER_PADDED_BOUNDS:
12927                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12928                break;
12929        }
12930    }
12931
12932    /**
12933     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12934     * the shape of the shadow it casts, and enables outline clipping.
12935     * <p>
12936     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12937     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12938     * outline provider with this method allows this behavior to be overridden.
12939     * <p>
12940     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12941     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12942     * <p>
12943     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12944     *
12945     * @see #setClipToOutline(boolean)
12946     * @see #getClipToOutline()
12947     * @see #getOutlineProvider()
12948     */
12949    public void setOutlineProvider(ViewOutlineProvider provider) {
12950        mOutlineProvider = provider;
12951        invalidateOutline();
12952    }
12953
12954    /**
12955     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12956     * that defines the shape of the shadow it casts, and enables outline clipping.
12957     *
12958     * @see #setOutlineProvider(ViewOutlineProvider)
12959     */
12960    public ViewOutlineProvider getOutlineProvider() {
12961        return mOutlineProvider;
12962    }
12963
12964    /**
12965     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12966     *
12967     * @see #setOutlineProvider(ViewOutlineProvider)
12968     */
12969    public void invalidateOutline() {
12970        rebuildOutline();
12971
12972        notifySubtreeAccessibilityStateChangedIfNeeded();
12973        invalidateViewProperty(false, false);
12974    }
12975
12976    /**
12977     * Internal version of {@link #invalidateOutline()} which invalidates the
12978     * outline without invalidating the view itself. This is intended to be called from
12979     * within methods in the View class itself which are the result of the view being
12980     * invalidated already. For example, when we are drawing the background of a View,
12981     * we invalidate the outline in case it changed in the meantime, but we do not
12982     * need to invalidate the view because we're already drawing the background as part
12983     * of drawing the view in response to an earlier invalidation of the view.
12984     */
12985    private void rebuildOutline() {
12986        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12987        if (mAttachInfo == null) return;
12988
12989        if (mOutlineProvider == null) {
12990            // no provider, remove outline
12991            mRenderNode.setOutline(null);
12992        } else {
12993            final Outline outline = mAttachInfo.mTmpOutline;
12994            outline.setEmpty();
12995            outline.setAlpha(1.0f);
12996
12997            mOutlineProvider.getOutline(this, outline);
12998            mRenderNode.setOutline(outline);
12999        }
13000    }
13001
13002    /**
13003     * HierarchyViewer only
13004     *
13005     * @hide
13006     */
13007    @ViewDebug.ExportedProperty(category = "drawing")
13008    public boolean hasShadow() {
13009        return mRenderNode.hasShadow();
13010    }
13011
13012
13013    /** @hide */
13014    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13015        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13016        invalidateViewProperty(false, false);
13017    }
13018
13019    /**
13020     * Hit rectangle in parent's coordinates
13021     *
13022     * @param outRect The hit rectangle of the view.
13023     */
13024    public void getHitRect(Rect outRect) {
13025        if (hasIdentityMatrix() || mAttachInfo == null) {
13026            outRect.set(mLeft, mTop, mRight, mBottom);
13027        } else {
13028            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13029            tmpRect.set(0, 0, getWidth(), getHeight());
13030            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13031            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13032                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13033        }
13034    }
13035
13036    /**
13037     * Determines whether the given point, in local coordinates is inside the view.
13038     */
13039    /*package*/ final boolean pointInView(float localX, float localY) {
13040        return pointInView(localX, localY, 0);
13041    }
13042
13043    /**
13044     * Utility method to determine whether the given point, in local coordinates,
13045     * is inside the view, where the area of the view is expanded by the slop factor.
13046     * This method is called while processing touch-move events to determine if the event
13047     * is still within the view.
13048     *
13049     * @hide
13050     */
13051    public boolean pointInView(float localX, float localY, float slop) {
13052        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13053                localY < ((mBottom - mTop) + slop);
13054    }
13055
13056    /**
13057     * When a view has focus and the user navigates away from it, the next view is searched for
13058     * starting from the rectangle filled in by this method.
13059     *
13060     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13061     * of the view.  However, if your view maintains some idea of internal selection,
13062     * such as a cursor, or a selected row or column, you should override this method and
13063     * fill in a more specific rectangle.
13064     *
13065     * @param r The rectangle to fill in, in this view's coordinates.
13066     */
13067    public void getFocusedRect(Rect r) {
13068        getDrawingRect(r);
13069    }
13070
13071    /**
13072     * If some part of this view is not clipped by any of its parents, then
13073     * return that area in r in global (root) coordinates. To convert r to local
13074     * coordinates (without taking possible View rotations into account), offset
13075     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13076     * If the view is completely clipped or translated out, return false.
13077     *
13078     * @param r If true is returned, r holds the global coordinates of the
13079     *        visible portion of this view.
13080     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13081     *        between this view and its root. globalOffet may be null.
13082     * @return true if r is non-empty (i.e. part of the view is visible at the
13083     *         root level.
13084     */
13085    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13086        int width = mRight - mLeft;
13087        int height = mBottom - mTop;
13088        if (width > 0 && height > 0) {
13089            r.set(0, 0, width, height);
13090            if (globalOffset != null) {
13091                globalOffset.set(-mScrollX, -mScrollY);
13092            }
13093            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13094        }
13095        return false;
13096    }
13097
13098    public final boolean getGlobalVisibleRect(Rect r) {
13099        return getGlobalVisibleRect(r, null);
13100    }
13101
13102    public final boolean getLocalVisibleRect(Rect r) {
13103        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13104        if (getGlobalVisibleRect(r, offset)) {
13105            r.offset(-offset.x, -offset.y); // make r local
13106            return true;
13107        }
13108        return false;
13109    }
13110
13111    /**
13112     * Offset this view's vertical location by the specified number of pixels.
13113     *
13114     * @param offset the number of pixels to offset the view by
13115     */
13116    public void offsetTopAndBottom(int offset) {
13117        if (offset != 0) {
13118            final boolean matrixIsIdentity = hasIdentityMatrix();
13119            if (matrixIsIdentity) {
13120                if (isHardwareAccelerated()) {
13121                    invalidateViewProperty(false, false);
13122                } else {
13123                    final ViewParent p = mParent;
13124                    if (p != null && mAttachInfo != null) {
13125                        final Rect r = mAttachInfo.mTmpInvalRect;
13126                        int minTop;
13127                        int maxBottom;
13128                        int yLoc;
13129                        if (offset < 0) {
13130                            minTop = mTop + offset;
13131                            maxBottom = mBottom;
13132                            yLoc = offset;
13133                        } else {
13134                            minTop = mTop;
13135                            maxBottom = mBottom + offset;
13136                            yLoc = 0;
13137                        }
13138                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13139                        p.invalidateChild(this, r);
13140                    }
13141                }
13142            } else {
13143                invalidateViewProperty(false, false);
13144            }
13145
13146            mTop += offset;
13147            mBottom += offset;
13148            mRenderNode.offsetTopAndBottom(offset);
13149            if (isHardwareAccelerated()) {
13150                invalidateViewProperty(false, false);
13151                invalidateParentIfNeededAndWasQuickRejected();
13152            } else {
13153                if (!matrixIsIdentity) {
13154                    invalidateViewProperty(false, true);
13155                }
13156                invalidateParentIfNeeded();
13157            }
13158            notifySubtreeAccessibilityStateChangedIfNeeded();
13159        }
13160    }
13161
13162    /**
13163     * Offset this view's horizontal location by the specified amount of pixels.
13164     *
13165     * @param offset the number of pixels to offset the view by
13166     */
13167    public void offsetLeftAndRight(int offset) {
13168        if (offset != 0) {
13169            final boolean matrixIsIdentity = hasIdentityMatrix();
13170            if (matrixIsIdentity) {
13171                if (isHardwareAccelerated()) {
13172                    invalidateViewProperty(false, false);
13173                } else {
13174                    final ViewParent p = mParent;
13175                    if (p != null && mAttachInfo != null) {
13176                        final Rect r = mAttachInfo.mTmpInvalRect;
13177                        int minLeft;
13178                        int maxRight;
13179                        if (offset < 0) {
13180                            minLeft = mLeft + offset;
13181                            maxRight = mRight;
13182                        } else {
13183                            minLeft = mLeft;
13184                            maxRight = mRight + offset;
13185                        }
13186                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13187                        p.invalidateChild(this, r);
13188                    }
13189                }
13190            } else {
13191                invalidateViewProperty(false, false);
13192            }
13193
13194            mLeft += offset;
13195            mRight += offset;
13196            mRenderNode.offsetLeftAndRight(offset);
13197            if (isHardwareAccelerated()) {
13198                invalidateViewProperty(false, false);
13199                invalidateParentIfNeededAndWasQuickRejected();
13200            } else {
13201                if (!matrixIsIdentity) {
13202                    invalidateViewProperty(false, true);
13203                }
13204                invalidateParentIfNeeded();
13205            }
13206            notifySubtreeAccessibilityStateChangedIfNeeded();
13207        }
13208    }
13209
13210    /**
13211     * Get the LayoutParams associated with this view. All views should have
13212     * layout parameters. These supply parameters to the <i>parent</i> of this
13213     * view specifying how it should be arranged. There are many subclasses of
13214     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13215     * of ViewGroup that are responsible for arranging their children.
13216     *
13217     * This method may return null if this View is not attached to a parent
13218     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13219     * was not invoked successfully. When a View is attached to a parent
13220     * ViewGroup, this method must not return null.
13221     *
13222     * @return The LayoutParams associated with this view, or null if no
13223     *         parameters have been set yet
13224     */
13225    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13226    public ViewGroup.LayoutParams getLayoutParams() {
13227        return mLayoutParams;
13228    }
13229
13230    /**
13231     * Set the layout parameters associated with this view. These supply
13232     * parameters to the <i>parent</i> of this view specifying how it should be
13233     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13234     * correspond to the different subclasses of ViewGroup that are responsible
13235     * for arranging their children.
13236     *
13237     * @param params The layout parameters for this view, cannot be null
13238     */
13239    public void setLayoutParams(ViewGroup.LayoutParams params) {
13240        if (params == null) {
13241            throw new NullPointerException("Layout parameters cannot be null");
13242        }
13243        mLayoutParams = params;
13244        resolveLayoutParams();
13245        if (mParent instanceof ViewGroup) {
13246            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13247        }
13248        requestLayout();
13249    }
13250
13251    /**
13252     * Resolve the layout parameters depending on the resolved layout direction
13253     *
13254     * @hide
13255     */
13256    public void resolveLayoutParams() {
13257        if (mLayoutParams != null) {
13258            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13259        }
13260    }
13261
13262    /**
13263     * Set the scrolled position of your view. This will cause a call to
13264     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13265     * invalidated.
13266     * @param x the x position to scroll to
13267     * @param y the y position to scroll to
13268     */
13269    public void scrollTo(int x, int y) {
13270        if (mScrollX != x || mScrollY != y) {
13271            int oldX = mScrollX;
13272            int oldY = mScrollY;
13273            mScrollX = x;
13274            mScrollY = y;
13275            invalidateParentCaches();
13276            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13277            if (!awakenScrollBars()) {
13278                postInvalidateOnAnimation();
13279            }
13280        }
13281    }
13282
13283    /**
13284     * Move the scrolled position of your view. This will cause a call to
13285     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13286     * invalidated.
13287     * @param x the amount of pixels to scroll by horizontally
13288     * @param y the amount of pixels to scroll by vertically
13289     */
13290    public void scrollBy(int x, int y) {
13291        scrollTo(mScrollX + x, mScrollY + y);
13292    }
13293
13294    /**
13295     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13296     * animation to fade the scrollbars out after a default delay. If a subclass
13297     * provides animated scrolling, the start delay should equal the duration
13298     * of the scrolling animation.</p>
13299     *
13300     * <p>The animation starts only if at least one of the scrollbars is
13301     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13302     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13303     * this method returns true, and false otherwise. If the animation is
13304     * started, this method calls {@link #invalidate()}; in that case the
13305     * caller should not call {@link #invalidate()}.</p>
13306     *
13307     * <p>This method should be invoked every time a subclass directly updates
13308     * the scroll parameters.</p>
13309     *
13310     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13311     * and {@link #scrollTo(int, int)}.</p>
13312     *
13313     * @return true if the animation is played, false otherwise
13314     *
13315     * @see #awakenScrollBars(int)
13316     * @see #scrollBy(int, int)
13317     * @see #scrollTo(int, int)
13318     * @see #isHorizontalScrollBarEnabled()
13319     * @see #isVerticalScrollBarEnabled()
13320     * @see #setHorizontalScrollBarEnabled(boolean)
13321     * @see #setVerticalScrollBarEnabled(boolean)
13322     */
13323    protected boolean awakenScrollBars() {
13324        return mScrollCache != null &&
13325                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13326    }
13327
13328    /**
13329     * Trigger the scrollbars to draw.
13330     * This method differs from awakenScrollBars() only in its default duration.
13331     * initialAwakenScrollBars() will show the scroll bars for longer than
13332     * usual to give the user more of a chance to notice them.
13333     *
13334     * @return true if the animation is played, false otherwise.
13335     */
13336    private boolean initialAwakenScrollBars() {
13337        return mScrollCache != null &&
13338                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13339    }
13340
13341    /**
13342     * <p>
13343     * Trigger the scrollbars to draw. When invoked this method starts an
13344     * animation to fade the scrollbars out after a fixed delay. If a subclass
13345     * provides animated scrolling, the start delay should equal the duration of
13346     * the scrolling animation.
13347     * </p>
13348     *
13349     * <p>
13350     * The animation starts only if at least one of the scrollbars is enabled,
13351     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13352     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13353     * this method returns true, and false otherwise. If the animation is
13354     * started, this method calls {@link #invalidate()}; in that case the caller
13355     * should not call {@link #invalidate()}.
13356     * </p>
13357     *
13358     * <p>
13359     * This method should be invoked every time a subclass directly updates the
13360     * scroll parameters.
13361     * </p>
13362     *
13363     * @param startDelay the delay, in milliseconds, after which the animation
13364     *        should start; when the delay is 0, the animation starts
13365     *        immediately
13366     * @return true if the animation is played, false otherwise
13367     *
13368     * @see #scrollBy(int, int)
13369     * @see #scrollTo(int, int)
13370     * @see #isHorizontalScrollBarEnabled()
13371     * @see #isVerticalScrollBarEnabled()
13372     * @see #setHorizontalScrollBarEnabled(boolean)
13373     * @see #setVerticalScrollBarEnabled(boolean)
13374     */
13375    protected boolean awakenScrollBars(int startDelay) {
13376        return awakenScrollBars(startDelay, true);
13377    }
13378
13379    /**
13380     * <p>
13381     * Trigger the scrollbars to draw. When invoked this method starts an
13382     * animation to fade the scrollbars out after a fixed delay. If a subclass
13383     * provides animated scrolling, the start delay should equal the duration of
13384     * the scrolling animation.
13385     * </p>
13386     *
13387     * <p>
13388     * The animation starts only if at least one of the scrollbars is enabled,
13389     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13390     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13391     * this method returns true, and false otherwise. If the animation is
13392     * started, this method calls {@link #invalidate()} if the invalidate parameter
13393     * is set to true; in that case the caller
13394     * should not call {@link #invalidate()}.
13395     * </p>
13396     *
13397     * <p>
13398     * This method should be invoked every time a subclass directly updates the
13399     * scroll parameters.
13400     * </p>
13401     *
13402     * @param startDelay the delay, in milliseconds, after which the animation
13403     *        should start; when the delay is 0, the animation starts
13404     *        immediately
13405     *
13406     * @param invalidate Whether this method should call invalidate
13407     *
13408     * @return true if the animation is played, false otherwise
13409     *
13410     * @see #scrollBy(int, int)
13411     * @see #scrollTo(int, int)
13412     * @see #isHorizontalScrollBarEnabled()
13413     * @see #isVerticalScrollBarEnabled()
13414     * @see #setHorizontalScrollBarEnabled(boolean)
13415     * @see #setVerticalScrollBarEnabled(boolean)
13416     */
13417    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13418        final ScrollabilityCache scrollCache = mScrollCache;
13419
13420        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13421            return false;
13422        }
13423
13424        if (scrollCache.scrollBar == null) {
13425            scrollCache.scrollBar = new ScrollBarDrawable();
13426            scrollCache.scrollBar.setState(getDrawableState());
13427            scrollCache.scrollBar.setCallback(this);
13428        }
13429
13430        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13431
13432            if (invalidate) {
13433                // Invalidate to show the scrollbars
13434                postInvalidateOnAnimation();
13435            }
13436
13437            if (scrollCache.state == ScrollabilityCache.OFF) {
13438                // FIXME: this is copied from WindowManagerService.
13439                // We should get this value from the system when it
13440                // is possible to do so.
13441                final int KEY_REPEAT_FIRST_DELAY = 750;
13442                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13443            }
13444
13445            // Tell mScrollCache when we should start fading. This may
13446            // extend the fade start time if one was already scheduled
13447            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13448            scrollCache.fadeStartTime = fadeStartTime;
13449            scrollCache.state = ScrollabilityCache.ON;
13450
13451            // Schedule our fader to run, unscheduling any old ones first
13452            if (mAttachInfo != null) {
13453                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13454                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13455            }
13456
13457            return true;
13458        }
13459
13460        return false;
13461    }
13462
13463    /**
13464     * Do not invalidate views which are not visible and which are not running an animation. They
13465     * will not get drawn and they should not set dirty flags as if they will be drawn
13466     */
13467    private boolean skipInvalidate() {
13468        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13469                (!(mParent instanceof ViewGroup) ||
13470                        !((ViewGroup) mParent).isViewTransitioning(this));
13471    }
13472
13473    /**
13474     * Mark the area defined by dirty as needing to be drawn. If the view is
13475     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13476     * point in the future.
13477     * <p>
13478     * This must be called from a UI thread. To call from a non-UI thread, call
13479     * {@link #postInvalidate()}.
13480     * <p>
13481     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13482     * {@code dirty}.
13483     *
13484     * @param dirty the rectangle representing the bounds of the dirty region
13485     */
13486    public void invalidate(Rect dirty) {
13487        final int scrollX = mScrollX;
13488        final int scrollY = mScrollY;
13489        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13490                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13491    }
13492
13493    /**
13494     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13495     * coordinates of the dirty rect are relative to the view. If the view is
13496     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13497     * point in the future.
13498     * <p>
13499     * This must be called from a UI thread. To call from a non-UI thread, call
13500     * {@link #postInvalidate()}.
13501     *
13502     * @param l the left position of the dirty region
13503     * @param t the top position of the dirty region
13504     * @param r the right position of the dirty region
13505     * @param b the bottom position of the dirty region
13506     */
13507    public void invalidate(int l, int t, int r, int b) {
13508        final int scrollX = mScrollX;
13509        final int scrollY = mScrollY;
13510        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13511    }
13512
13513    /**
13514     * Invalidate the whole view. If the view is visible,
13515     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13516     * the future.
13517     * <p>
13518     * This must be called from a UI thread. To call from a non-UI thread, call
13519     * {@link #postInvalidate()}.
13520     */
13521    public void invalidate() {
13522        invalidate(true);
13523    }
13524
13525    /**
13526     * This is where the invalidate() work actually happens. A full invalidate()
13527     * causes the drawing cache to be invalidated, but this function can be
13528     * called with invalidateCache set to false to skip that invalidation step
13529     * for cases that do not need it (for example, a component that remains at
13530     * the same dimensions with the same content).
13531     *
13532     * @param invalidateCache Whether the drawing cache for this view should be
13533     *            invalidated as well. This is usually true for a full
13534     *            invalidate, but may be set to false if the View's contents or
13535     *            dimensions have not changed.
13536     */
13537    void invalidate(boolean invalidateCache) {
13538        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13539    }
13540
13541    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13542            boolean fullInvalidate) {
13543        if (mGhostView != null) {
13544            mGhostView.invalidate(true);
13545            return;
13546        }
13547
13548        if (skipInvalidate()) {
13549            return;
13550        }
13551
13552        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13553                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13554                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13555                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13556            if (fullInvalidate) {
13557                mLastIsOpaque = isOpaque();
13558                mPrivateFlags &= ~PFLAG_DRAWN;
13559            }
13560
13561            mPrivateFlags |= PFLAG_DIRTY;
13562
13563            if (invalidateCache) {
13564                mPrivateFlags |= PFLAG_INVALIDATED;
13565                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13566            }
13567
13568            // Propagate the damage rectangle to the parent view.
13569            final AttachInfo ai = mAttachInfo;
13570            final ViewParent p = mParent;
13571            if (p != null && ai != null && l < r && t < b) {
13572                final Rect damage = ai.mTmpInvalRect;
13573                damage.set(l, t, r, b);
13574                p.invalidateChild(this, damage);
13575            }
13576
13577            // Damage the entire projection receiver, if necessary.
13578            if (mBackground != null && mBackground.isProjected()) {
13579                final View receiver = getProjectionReceiver();
13580                if (receiver != null) {
13581                    receiver.damageInParent();
13582                }
13583            }
13584
13585            // Damage the entire IsolatedZVolume receiving this view's shadow.
13586            if (isHardwareAccelerated() && getZ() != 0) {
13587                damageShadowReceiver();
13588            }
13589        }
13590    }
13591
13592    /**
13593     * @return this view's projection receiver, or {@code null} if none exists
13594     */
13595    private View getProjectionReceiver() {
13596        ViewParent p = getParent();
13597        while (p != null && p instanceof View) {
13598            final View v = (View) p;
13599            if (v.isProjectionReceiver()) {
13600                return v;
13601            }
13602            p = p.getParent();
13603        }
13604
13605        return null;
13606    }
13607
13608    /**
13609     * @return whether the view is a projection receiver
13610     */
13611    private boolean isProjectionReceiver() {
13612        return mBackground != null;
13613    }
13614
13615    /**
13616     * Damage area of the screen that can be covered by this View's shadow.
13617     *
13618     * This method will guarantee that any changes to shadows cast by a View
13619     * are damaged on the screen for future redraw.
13620     */
13621    private void damageShadowReceiver() {
13622        final AttachInfo ai = mAttachInfo;
13623        if (ai != null) {
13624            ViewParent p = getParent();
13625            if (p != null && p instanceof ViewGroup) {
13626                final ViewGroup vg = (ViewGroup) p;
13627                vg.damageInParent();
13628            }
13629        }
13630    }
13631
13632    /**
13633     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13634     * set any flags or handle all of the cases handled by the default invalidation methods.
13635     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13636     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13637     * walk up the hierarchy, transforming the dirty rect as necessary.
13638     *
13639     * The method also handles normal invalidation logic if display list properties are not
13640     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13641     * backup approach, to handle these cases used in the various property-setting methods.
13642     *
13643     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13644     * are not being used in this view
13645     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13646     * list properties are not being used in this view
13647     */
13648    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13649        if (!isHardwareAccelerated()
13650                || !mRenderNode.isValid()
13651                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13652            if (invalidateParent) {
13653                invalidateParentCaches();
13654            }
13655            if (forceRedraw) {
13656                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13657            }
13658            invalidate(false);
13659        } else {
13660            damageInParent();
13661        }
13662        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13663            damageShadowReceiver();
13664        }
13665    }
13666
13667    /**
13668     * Tells the parent view to damage this view's bounds.
13669     *
13670     * @hide
13671     */
13672    protected void damageInParent() {
13673        final AttachInfo ai = mAttachInfo;
13674        final ViewParent p = mParent;
13675        if (p != null && ai != null) {
13676            final Rect r = ai.mTmpInvalRect;
13677            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13678            if (mParent instanceof ViewGroup) {
13679                ((ViewGroup) mParent).damageChild(this, r);
13680            } else {
13681                mParent.invalidateChild(this, r);
13682            }
13683        }
13684    }
13685
13686    /**
13687     * Utility method to transform a given Rect by the current matrix of this view.
13688     */
13689    void transformRect(final Rect rect) {
13690        if (!getMatrix().isIdentity()) {
13691            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13692            boundingRect.set(rect);
13693            getMatrix().mapRect(boundingRect);
13694            rect.set((int) Math.floor(boundingRect.left),
13695                    (int) Math.floor(boundingRect.top),
13696                    (int) Math.ceil(boundingRect.right),
13697                    (int) Math.ceil(boundingRect.bottom));
13698        }
13699    }
13700
13701    /**
13702     * Used to indicate that the parent of this view should clear its caches. This functionality
13703     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13704     * which is necessary when various parent-managed properties of the view change, such as
13705     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13706     * clears the parent caches and does not causes an invalidate event.
13707     *
13708     * @hide
13709     */
13710    protected void invalidateParentCaches() {
13711        if (mParent instanceof View) {
13712            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13713        }
13714    }
13715
13716    /**
13717     * Used to indicate that the parent of this view should be invalidated. This functionality
13718     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13719     * which is necessary when various parent-managed properties of the view change, such as
13720     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13721     * an invalidation event to the parent.
13722     *
13723     * @hide
13724     */
13725    protected void invalidateParentIfNeeded() {
13726        if (isHardwareAccelerated() && mParent instanceof View) {
13727            ((View) mParent).invalidate(true);
13728        }
13729    }
13730
13731    /**
13732     * @hide
13733     */
13734    protected void invalidateParentIfNeededAndWasQuickRejected() {
13735        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13736            // View was rejected last time it was drawn by its parent; this may have changed
13737            invalidateParentIfNeeded();
13738        }
13739    }
13740
13741    /**
13742     * Indicates whether this View is opaque. An opaque View guarantees that it will
13743     * draw all the pixels overlapping its bounds using a fully opaque color.
13744     *
13745     * Subclasses of View should override this method whenever possible to indicate
13746     * whether an instance is opaque. Opaque Views are treated in a special way by
13747     * the View hierarchy, possibly allowing it to perform optimizations during
13748     * invalidate/draw passes.
13749     *
13750     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13751     */
13752    @ViewDebug.ExportedProperty(category = "drawing")
13753    public boolean isOpaque() {
13754        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13755                getFinalAlpha() >= 1.0f;
13756    }
13757
13758    /**
13759     * @hide
13760     */
13761    protected void computeOpaqueFlags() {
13762        // Opaque if:
13763        //   - Has a background
13764        //   - Background is opaque
13765        //   - Doesn't have scrollbars or scrollbars overlay
13766
13767        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13768            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13769        } else {
13770            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13771        }
13772
13773        final int flags = mViewFlags;
13774        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13775                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13776                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13777            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13778        } else {
13779            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13780        }
13781    }
13782
13783    /**
13784     * @hide
13785     */
13786    protected boolean hasOpaqueScrollbars() {
13787        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13788    }
13789
13790    /**
13791     * @return A handler associated with the thread running the View. This
13792     * handler can be used to pump events in the UI events queue.
13793     */
13794    public Handler getHandler() {
13795        final AttachInfo attachInfo = mAttachInfo;
13796        if (attachInfo != null) {
13797            return attachInfo.mHandler;
13798        }
13799        return null;
13800    }
13801
13802    /**
13803     * Returns the queue of runnable for this view.
13804     *
13805     * @return the queue of runnables for this view
13806     */
13807    private HandlerActionQueue getRunQueue() {
13808        if (mRunQueue == null) {
13809            mRunQueue = new HandlerActionQueue();
13810        }
13811        return mRunQueue;
13812    }
13813
13814    /**
13815     * Gets the view root associated with the View.
13816     * @return The view root, or null if none.
13817     * @hide
13818     */
13819    public ViewRootImpl getViewRootImpl() {
13820        if (mAttachInfo != null) {
13821            return mAttachInfo.mViewRootImpl;
13822        }
13823        return null;
13824    }
13825
13826    /**
13827     * @hide
13828     */
13829    public ThreadedRenderer getHardwareRenderer() {
13830        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
13831    }
13832
13833    /**
13834     * <p>Causes the Runnable to be added to the message queue.
13835     * The runnable will be run on the user interface thread.</p>
13836     *
13837     * @param action The Runnable that will be executed.
13838     *
13839     * @return Returns true if the Runnable was successfully placed in to the
13840     *         message queue.  Returns false on failure, usually because the
13841     *         looper processing the message queue is exiting.
13842     *
13843     * @see #postDelayed
13844     * @see #removeCallbacks
13845     */
13846    public boolean post(Runnable action) {
13847        final AttachInfo attachInfo = mAttachInfo;
13848        if (attachInfo != null) {
13849            return attachInfo.mHandler.post(action);
13850        }
13851
13852        // Postpone the runnable until we know on which thread it needs to run.
13853        // Assume that the runnable will be successfully placed after attach.
13854        getRunQueue().post(action);
13855        return true;
13856    }
13857
13858    /**
13859     * <p>Causes the Runnable to be added to the message queue, to be run
13860     * after the specified amount of time elapses.
13861     * The runnable will be run on the user interface thread.</p>
13862     *
13863     * @param action The Runnable that will be executed.
13864     * @param delayMillis The delay (in milliseconds) until the Runnable
13865     *        will be executed.
13866     *
13867     * @return true if the Runnable was successfully placed in to the
13868     *         message queue.  Returns false on failure, usually because the
13869     *         looper processing the message queue is exiting.  Note that a
13870     *         result of true does not mean the Runnable will be processed --
13871     *         if the looper is quit before the delivery time of the message
13872     *         occurs then the message will be dropped.
13873     *
13874     * @see #post
13875     * @see #removeCallbacks
13876     */
13877    public boolean postDelayed(Runnable action, long delayMillis) {
13878        final AttachInfo attachInfo = mAttachInfo;
13879        if (attachInfo != null) {
13880            return attachInfo.mHandler.postDelayed(action, delayMillis);
13881        }
13882
13883        // Postpone the runnable until we know on which thread it needs to run.
13884        // Assume that the runnable will be successfully placed after attach.
13885        getRunQueue().postDelayed(action, delayMillis);
13886        return true;
13887    }
13888
13889    /**
13890     * <p>Causes the Runnable to execute on the next animation time step.
13891     * The runnable will be run on the user interface thread.</p>
13892     *
13893     * @param action The Runnable that will be executed.
13894     *
13895     * @see #postOnAnimationDelayed
13896     * @see #removeCallbacks
13897     */
13898    public void postOnAnimation(Runnable action) {
13899        final AttachInfo attachInfo = mAttachInfo;
13900        if (attachInfo != null) {
13901            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13902                    Choreographer.CALLBACK_ANIMATION, action, null);
13903        } else {
13904            // Postpone the runnable until we know
13905            // on which thread it needs to run.
13906            getRunQueue().post(action);
13907        }
13908    }
13909
13910    /**
13911     * <p>Causes the Runnable to execute on the next animation time step,
13912     * after the specified amount of time elapses.
13913     * The runnable will be run on the user interface thread.</p>
13914     *
13915     * @param action The Runnable that will be executed.
13916     * @param delayMillis The delay (in milliseconds) until the Runnable
13917     *        will be executed.
13918     *
13919     * @see #postOnAnimation
13920     * @see #removeCallbacks
13921     */
13922    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13923        final AttachInfo attachInfo = mAttachInfo;
13924        if (attachInfo != null) {
13925            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13926                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13927        } else {
13928            // Postpone the runnable until we know
13929            // on which thread it needs to run.
13930            getRunQueue().postDelayed(action, delayMillis);
13931        }
13932    }
13933
13934    /**
13935     * <p>Removes the specified Runnable from the message queue.</p>
13936     *
13937     * @param action The Runnable to remove from the message handling queue
13938     *
13939     * @return true if this view could ask the Handler to remove the Runnable,
13940     *         false otherwise. When the returned value is true, the Runnable
13941     *         may or may not have been actually removed from the message queue
13942     *         (for instance, if the Runnable was not in the queue already.)
13943     *
13944     * @see #post
13945     * @see #postDelayed
13946     * @see #postOnAnimation
13947     * @see #postOnAnimationDelayed
13948     */
13949    public boolean removeCallbacks(Runnable action) {
13950        if (action != null) {
13951            final AttachInfo attachInfo = mAttachInfo;
13952            if (attachInfo != null) {
13953                attachInfo.mHandler.removeCallbacks(action);
13954                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13955                        Choreographer.CALLBACK_ANIMATION, action, null);
13956            }
13957            getRunQueue().removeCallbacks(action);
13958        }
13959        return true;
13960    }
13961
13962    /**
13963     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13964     * Use this to invalidate the View from a non-UI thread.</p>
13965     *
13966     * <p>This method can be invoked from outside of the UI thread
13967     * only when this View is attached to a window.</p>
13968     *
13969     * @see #invalidate()
13970     * @see #postInvalidateDelayed(long)
13971     */
13972    public void postInvalidate() {
13973        postInvalidateDelayed(0);
13974    }
13975
13976    /**
13977     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13978     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13979     *
13980     * <p>This method can be invoked from outside of the UI thread
13981     * only when this View is attached to a window.</p>
13982     *
13983     * @param left The left coordinate of the rectangle to invalidate.
13984     * @param top The top coordinate of the rectangle to invalidate.
13985     * @param right The right coordinate of the rectangle to invalidate.
13986     * @param bottom The bottom coordinate of the rectangle to invalidate.
13987     *
13988     * @see #invalidate(int, int, int, int)
13989     * @see #invalidate(Rect)
13990     * @see #postInvalidateDelayed(long, int, int, int, int)
13991     */
13992    public void postInvalidate(int left, int top, int right, int bottom) {
13993        postInvalidateDelayed(0, left, top, right, bottom);
13994    }
13995
13996    /**
13997     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13998     * loop. Waits for the specified amount of time.</p>
13999     *
14000     * <p>This method can be invoked from outside of the UI thread
14001     * only when this View is attached to a window.</p>
14002     *
14003     * @param delayMilliseconds the duration in milliseconds to delay the
14004     *         invalidation by
14005     *
14006     * @see #invalidate()
14007     * @see #postInvalidate()
14008     */
14009    public void postInvalidateDelayed(long delayMilliseconds) {
14010        // We try only with the AttachInfo because there's no point in invalidating
14011        // if we are not attached to our window
14012        final AttachInfo attachInfo = mAttachInfo;
14013        if (attachInfo != null) {
14014            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14015        }
14016    }
14017
14018    /**
14019     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14020     * through the event loop. Waits for the specified amount of time.</p>
14021     *
14022     * <p>This method can be invoked from outside of the UI thread
14023     * only when this View is attached to a window.</p>
14024     *
14025     * @param delayMilliseconds the duration in milliseconds to delay the
14026     *         invalidation by
14027     * @param left The left coordinate of the rectangle to invalidate.
14028     * @param top The top coordinate of the rectangle to invalidate.
14029     * @param right The right coordinate of the rectangle to invalidate.
14030     * @param bottom The bottom coordinate of the rectangle to invalidate.
14031     *
14032     * @see #invalidate(int, int, int, int)
14033     * @see #invalidate(Rect)
14034     * @see #postInvalidate(int, int, int, int)
14035     */
14036    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14037            int right, int bottom) {
14038
14039        // We try only with the AttachInfo because there's no point in invalidating
14040        // if we are not attached to our window
14041        final AttachInfo attachInfo = mAttachInfo;
14042        if (attachInfo != null) {
14043            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14044            info.target = this;
14045            info.left = left;
14046            info.top = top;
14047            info.right = right;
14048            info.bottom = bottom;
14049
14050            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14051        }
14052    }
14053
14054    /**
14055     * <p>Cause an invalidate to happen on the next animation time step, typically the
14056     * next display frame.</p>
14057     *
14058     * <p>This method can be invoked from outside of the UI thread
14059     * only when this View is attached to a window.</p>
14060     *
14061     * @see #invalidate()
14062     */
14063    public void postInvalidateOnAnimation() {
14064        // We try only with the AttachInfo because there's no point in invalidating
14065        // if we are not attached to our window
14066        final AttachInfo attachInfo = mAttachInfo;
14067        if (attachInfo != null) {
14068            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14069        }
14070    }
14071
14072    /**
14073     * <p>Cause an invalidate of the specified area to happen on the next animation
14074     * time step, typically the next display frame.</p>
14075     *
14076     * <p>This method can be invoked from outside of the UI thread
14077     * only when this View is attached to a window.</p>
14078     *
14079     * @param left The left coordinate of the rectangle to invalidate.
14080     * @param top The top coordinate of the rectangle to invalidate.
14081     * @param right The right coordinate of the rectangle to invalidate.
14082     * @param bottom The bottom coordinate of the rectangle to invalidate.
14083     *
14084     * @see #invalidate(int, int, int, int)
14085     * @see #invalidate(Rect)
14086     */
14087    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14088        // We try only with the AttachInfo because there's no point in invalidating
14089        // if we are not attached to our window
14090        final AttachInfo attachInfo = mAttachInfo;
14091        if (attachInfo != null) {
14092            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14093            info.target = this;
14094            info.left = left;
14095            info.top = top;
14096            info.right = right;
14097            info.bottom = bottom;
14098
14099            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14100        }
14101    }
14102
14103    /**
14104     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14105     * This event is sent at most once every
14106     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14107     */
14108    private void postSendViewScrolledAccessibilityEventCallback() {
14109        if (mSendViewScrolledAccessibilityEvent == null) {
14110            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14111        }
14112        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14113            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14114            postDelayed(mSendViewScrolledAccessibilityEvent,
14115                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14116        }
14117    }
14118
14119    /**
14120     * Called by a parent to request that a child update its values for mScrollX
14121     * and mScrollY if necessary. This will typically be done if the child is
14122     * animating a scroll using a {@link android.widget.Scroller Scroller}
14123     * object.
14124     */
14125    public void computeScroll() {
14126    }
14127
14128    /**
14129     * <p>Indicate whether the horizontal edges are faded when the view is
14130     * scrolled horizontally.</p>
14131     *
14132     * @return true if the horizontal edges should are faded on scroll, false
14133     *         otherwise
14134     *
14135     * @see #setHorizontalFadingEdgeEnabled(boolean)
14136     *
14137     * @attr ref android.R.styleable#View_requiresFadingEdge
14138     */
14139    public boolean isHorizontalFadingEdgeEnabled() {
14140        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14141    }
14142
14143    /**
14144     * <p>Define whether the horizontal edges should be faded when this view
14145     * is scrolled horizontally.</p>
14146     *
14147     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14148     *                                    be faded when the view is scrolled
14149     *                                    horizontally
14150     *
14151     * @see #isHorizontalFadingEdgeEnabled()
14152     *
14153     * @attr ref android.R.styleable#View_requiresFadingEdge
14154     */
14155    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14156        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14157            if (horizontalFadingEdgeEnabled) {
14158                initScrollCache();
14159            }
14160
14161            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14162        }
14163    }
14164
14165    /**
14166     * <p>Indicate whether the vertical edges are faded when the view is
14167     * scrolled horizontally.</p>
14168     *
14169     * @return true if the vertical edges should are faded on scroll, false
14170     *         otherwise
14171     *
14172     * @see #setVerticalFadingEdgeEnabled(boolean)
14173     *
14174     * @attr ref android.R.styleable#View_requiresFadingEdge
14175     */
14176    public boolean isVerticalFadingEdgeEnabled() {
14177        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14178    }
14179
14180    /**
14181     * <p>Define whether the vertical edges should be faded when this view
14182     * is scrolled vertically.</p>
14183     *
14184     * @param verticalFadingEdgeEnabled true if the vertical edges should
14185     *                                  be faded when the view is scrolled
14186     *                                  vertically
14187     *
14188     * @see #isVerticalFadingEdgeEnabled()
14189     *
14190     * @attr ref android.R.styleable#View_requiresFadingEdge
14191     */
14192    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14193        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14194            if (verticalFadingEdgeEnabled) {
14195                initScrollCache();
14196            }
14197
14198            mViewFlags ^= FADING_EDGE_VERTICAL;
14199        }
14200    }
14201
14202    /**
14203     * Returns the strength, or intensity, of the top faded edge. The strength is
14204     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14205     * returns 0.0 or 1.0 but no value in between.
14206     *
14207     * Subclasses should override this method to provide a smoother fade transition
14208     * when scrolling occurs.
14209     *
14210     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14211     */
14212    protected float getTopFadingEdgeStrength() {
14213        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14214    }
14215
14216    /**
14217     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14218     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14219     * returns 0.0 or 1.0 but no value in between.
14220     *
14221     * Subclasses should override this method to provide a smoother fade transition
14222     * when scrolling occurs.
14223     *
14224     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14225     */
14226    protected float getBottomFadingEdgeStrength() {
14227        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14228                computeVerticalScrollRange() ? 1.0f : 0.0f;
14229    }
14230
14231    /**
14232     * Returns the strength, or intensity, of the left faded edge. The strength is
14233     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14234     * returns 0.0 or 1.0 but no value in between.
14235     *
14236     * Subclasses should override this method to provide a smoother fade transition
14237     * when scrolling occurs.
14238     *
14239     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14240     */
14241    protected float getLeftFadingEdgeStrength() {
14242        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14243    }
14244
14245    /**
14246     * Returns the strength, or intensity, of the right faded edge. The strength is
14247     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14248     * returns 0.0 or 1.0 but no value in between.
14249     *
14250     * Subclasses should override this method to provide a smoother fade transition
14251     * when scrolling occurs.
14252     *
14253     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14254     */
14255    protected float getRightFadingEdgeStrength() {
14256        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14257                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14258    }
14259
14260    /**
14261     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14262     * scrollbar is not drawn by default.</p>
14263     *
14264     * @return true if the horizontal scrollbar should be painted, false
14265     *         otherwise
14266     *
14267     * @see #setHorizontalScrollBarEnabled(boolean)
14268     */
14269    public boolean isHorizontalScrollBarEnabled() {
14270        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14271    }
14272
14273    /**
14274     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14275     * scrollbar is not drawn by default.</p>
14276     *
14277     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14278     *                                   be painted
14279     *
14280     * @see #isHorizontalScrollBarEnabled()
14281     */
14282    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14283        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14284            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14285            computeOpaqueFlags();
14286            resolvePadding();
14287        }
14288    }
14289
14290    /**
14291     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14292     * scrollbar is not drawn by default.</p>
14293     *
14294     * @return true if the vertical scrollbar should be painted, false
14295     *         otherwise
14296     *
14297     * @see #setVerticalScrollBarEnabled(boolean)
14298     */
14299    public boolean isVerticalScrollBarEnabled() {
14300        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14301    }
14302
14303    /**
14304     * <p>Define whether the vertical scrollbar should be drawn or not. The
14305     * scrollbar is not drawn by default.</p>
14306     *
14307     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14308     *                                 be painted
14309     *
14310     * @see #isVerticalScrollBarEnabled()
14311     */
14312    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14313        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14314            mViewFlags ^= SCROLLBARS_VERTICAL;
14315            computeOpaqueFlags();
14316            resolvePadding();
14317        }
14318    }
14319
14320    /**
14321     * @hide
14322     */
14323    protected void recomputePadding() {
14324        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14325    }
14326
14327    /**
14328     * Define whether scrollbars will fade when the view is not scrolling.
14329     *
14330     * @param fadeScrollbars whether to enable fading
14331     *
14332     * @attr ref android.R.styleable#View_fadeScrollbars
14333     */
14334    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14335        initScrollCache();
14336        final ScrollabilityCache scrollabilityCache = mScrollCache;
14337        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14338        if (fadeScrollbars) {
14339            scrollabilityCache.state = ScrollabilityCache.OFF;
14340        } else {
14341            scrollabilityCache.state = ScrollabilityCache.ON;
14342        }
14343    }
14344
14345    /**
14346     *
14347     * Returns true if scrollbars will fade when this view is not scrolling
14348     *
14349     * @return true if scrollbar fading is enabled
14350     *
14351     * @attr ref android.R.styleable#View_fadeScrollbars
14352     */
14353    public boolean isScrollbarFadingEnabled() {
14354        return mScrollCache != null && mScrollCache.fadeScrollBars;
14355    }
14356
14357    /**
14358     *
14359     * Returns the delay before scrollbars fade.
14360     *
14361     * @return the delay before scrollbars fade
14362     *
14363     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14364     */
14365    public int getScrollBarDefaultDelayBeforeFade() {
14366        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14367                mScrollCache.scrollBarDefaultDelayBeforeFade;
14368    }
14369
14370    /**
14371     * Define the delay before scrollbars fade.
14372     *
14373     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14374     *
14375     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14376     */
14377    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14378        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14379    }
14380
14381    /**
14382     *
14383     * Returns the scrollbar fade duration.
14384     *
14385     * @return the scrollbar fade duration
14386     *
14387     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14388     */
14389    public int getScrollBarFadeDuration() {
14390        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14391                mScrollCache.scrollBarFadeDuration;
14392    }
14393
14394    /**
14395     * Define the scrollbar fade duration.
14396     *
14397     * @param scrollBarFadeDuration - the scrollbar fade duration
14398     *
14399     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14400     */
14401    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14402        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14403    }
14404
14405    /**
14406     *
14407     * Returns the scrollbar size.
14408     *
14409     * @return the scrollbar size
14410     *
14411     * @attr ref android.R.styleable#View_scrollbarSize
14412     */
14413    public int getScrollBarSize() {
14414        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14415                mScrollCache.scrollBarSize;
14416    }
14417
14418    /**
14419     * Define the scrollbar size.
14420     *
14421     * @param scrollBarSize - the scrollbar size
14422     *
14423     * @attr ref android.R.styleable#View_scrollbarSize
14424     */
14425    public void setScrollBarSize(int scrollBarSize) {
14426        getScrollCache().scrollBarSize = scrollBarSize;
14427    }
14428
14429    /**
14430     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14431     * inset. When inset, they add to the padding of the view. And the scrollbars
14432     * can be drawn inside the padding area or on the edge of the view. For example,
14433     * if a view has a background drawable and you want to draw the scrollbars
14434     * inside the padding specified by the drawable, you can use
14435     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14436     * appear at the edge of the view, ignoring the padding, then you can use
14437     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14438     * @param style the style of the scrollbars. Should be one of
14439     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14440     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14441     * @see #SCROLLBARS_INSIDE_OVERLAY
14442     * @see #SCROLLBARS_INSIDE_INSET
14443     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14444     * @see #SCROLLBARS_OUTSIDE_INSET
14445     *
14446     * @attr ref android.R.styleable#View_scrollbarStyle
14447     */
14448    public void setScrollBarStyle(@ScrollBarStyle int style) {
14449        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14450            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14451            computeOpaqueFlags();
14452            resolvePadding();
14453        }
14454    }
14455
14456    /**
14457     * <p>Returns the current scrollbar style.</p>
14458     * @return the current scrollbar style
14459     * @see #SCROLLBARS_INSIDE_OVERLAY
14460     * @see #SCROLLBARS_INSIDE_INSET
14461     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14462     * @see #SCROLLBARS_OUTSIDE_INSET
14463     *
14464     * @attr ref android.R.styleable#View_scrollbarStyle
14465     */
14466    @ViewDebug.ExportedProperty(mapping = {
14467            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14468            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14469            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14470            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14471    })
14472    @ScrollBarStyle
14473    public int getScrollBarStyle() {
14474        return mViewFlags & SCROLLBARS_STYLE_MASK;
14475    }
14476
14477    /**
14478     * <p>Compute the horizontal range that the horizontal scrollbar
14479     * represents.</p>
14480     *
14481     * <p>The range is expressed in arbitrary units that must be the same as the
14482     * units used by {@link #computeHorizontalScrollExtent()} and
14483     * {@link #computeHorizontalScrollOffset()}.</p>
14484     *
14485     * <p>The default range is the drawing width of this view.</p>
14486     *
14487     * @return the total horizontal range represented by the horizontal
14488     *         scrollbar
14489     *
14490     * @see #computeHorizontalScrollExtent()
14491     * @see #computeHorizontalScrollOffset()
14492     * @see android.widget.ScrollBarDrawable
14493     */
14494    protected int computeHorizontalScrollRange() {
14495        return getWidth();
14496    }
14497
14498    /**
14499     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14500     * within the horizontal range. This value is used to compute the position
14501     * of the thumb within the scrollbar's track.</p>
14502     *
14503     * <p>The range is expressed in arbitrary units that must be the same as the
14504     * units used by {@link #computeHorizontalScrollRange()} and
14505     * {@link #computeHorizontalScrollExtent()}.</p>
14506     *
14507     * <p>The default offset is the scroll offset of this view.</p>
14508     *
14509     * @return the horizontal offset of the scrollbar's thumb
14510     *
14511     * @see #computeHorizontalScrollRange()
14512     * @see #computeHorizontalScrollExtent()
14513     * @see android.widget.ScrollBarDrawable
14514     */
14515    protected int computeHorizontalScrollOffset() {
14516        return mScrollX;
14517    }
14518
14519    /**
14520     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14521     * within the horizontal range. This value is used to compute the length
14522     * of the thumb within the scrollbar's track.</p>
14523     *
14524     * <p>The range is expressed in arbitrary units that must be the same as the
14525     * units used by {@link #computeHorizontalScrollRange()} and
14526     * {@link #computeHorizontalScrollOffset()}.</p>
14527     *
14528     * <p>The default extent is the drawing width of this view.</p>
14529     *
14530     * @return the horizontal extent of the scrollbar's thumb
14531     *
14532     * @see #computeHorizontalScrollRange()
14533     * @see #computeHorizontalScrollOffset()
14534     * @see android.widget.ScrollBarDrawable
14535     */
14536    protected int computeHorizontalScrollExtent() {
14537        return getWidth();
14538    }
14539
14540    /**
14541     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14542     *
14543     * <p>The range is expressed in arbitrary units that must be the same as the
14544     * units used by {@link #computeVerticalScrollExtent()} and
14545     * {@link #computeVerticalScrollOffset()}.</p>
14546     *
14547     * @return the total vertical range represented by the vertical scrollbar
14548     *
14549     * <p>The default range is the drawing height of this view.</p>
14550     *
14551     * @see #computeVerticalScrollExtent()
14552     * @see #computeVerticalScrollOffset()
14553     * @see android.widget.ScrollBarDrawable
14554     */
14555    protected int computeVerticalScrollRange() {
14556        return getHeight();
14557    }
14558
14559    /**
14560     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14561     * within the horizontal range. This value is used to compute the position
14562     * of the thumb within the scrollbar's track.</p>
14563     *
14564     * <p>The range is expressed in arbitrary units that must be the same as the
14565     * units used by {@link #computeVerticalScrollRange()} and
14566     * {@link #computeVerticalScrollExtent()}.</p>
14567     *
14568     * <p>The default offset is the scroll offset of this view.</p>
14569     *
14570     * @return the vertical offset of the scrollbar's thumb
14571     *
14572     * @see #computeVerticalScrollRange()
14573     * @see #computeVerticalScrollExtent()
14574     * @see android.widget.ScrollBarDrawable
14575     */
14576    protected int computeVerticalScrollOffset() {
14577        return mScrollY;
14578    }
14579
14580    /**
14581     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14582     * within the vertical range. This value is used to compute the length
14583     * of the thumb within the scrollbar's track.</p>
14584     *
14585     * <p>The range is expressed in arbitrary units that must be the same as the
14586     * units used by {@link #computeVerticalScrollRange()} and
14587     * {@link #computeVerticalScrollOffset()}.</p>
14588     *
14589     * <p>The default extent is the drawing height of this view.</p>
14590     *
14591     * @return the vertical extent of the scrollbar's thumb
14592     *
14593     * @see #computeVerticalScrollRange()
14594     * @see #computeVerticalScrollOffset()
14595     * @see android.widget.ScrollBarDrawable
14596     */
14597    protected int computeVerticalScrollExtent() {
14598        return getHeight();
14599    }
14600
14601    /**
14602     * Check if this view can be scrolled horizontally in a certain direction.
14603     *
14604     * @param direction Negative to check scrolling left, positive to check scrolling right.
14605     * @return true if this view can be scrolled in the specified direction, false otherwise.
14606     */
14607    public boolean canScrollHorizontally(int direction) {
14608        final int offset = computeHorizontalScrollOffset();
14609        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14610        if (range == 0) return false;
14611        if (direction < 0) {
14612            return offset > 0;
14613        } else {
14614            return offset < range - 1;
14615        }
14616    }
14617
14618    /**
14619     * Check if this view can be scrolled vertically in a certain direction.
14620     *
14621     * @param direction Negative to check scrolling up, positive to check scrolling down.
14622     * @return true if this view can be scrolled in the specified direction, false otherwise.
14623     */
14624    public boolean canScrollVertically(int direction) {
14625        final int offset = computeVerticalScrollOffset();
14626        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14627        if (range == 0) return false;
14628        if (direction < 0) {
14629            return offset > 0;
14630        } else {
14631            return offset < range - 1;
14632        }
14633    }
14634
14635    void getScrollIndicatorBounds(@NonNull Rect out) {
14636        out.left = mScrollX;
14637        out.right = mScrollX + mRight - mLeft;
14638        out.top = mScrollY;
14639        out.bottom = mScrollY + mBottom - mTop;
14640    }
14641
14642    private void onDrawScrollIndicators(Canvas c) {
14643        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14644            // No scroll indicators enabled.
14645            return;
14646        }
14647
14648        final Drawable dr = mScrollIndicatorDrawable;
14649        if (dr == null) {
14650            // Scroll indicators aren't supported here.
14651            return;
14652        }
14653
14654        final int h = dr.getIntrinsicHeight();
14655        final int w = dr.getIntrinsicWidth();
14656        final Rect rect = mAttachInfo.mTmpInvalRect;
14657        getScrollIndicatorBounds(rect);
14658
14659        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14660            final boolean canScrollUp = canScrollVertically(-1);
14661            if (canScrollUp) {
14662                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14663                dr.draw(c);
14664            }
14665        }
14666
14667        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14668            final boolean canScrollDown = canScrollVertically(1);
14669            if (canScrollDown) {
14670                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14671                dr.draw(c);
14672            }
14673        }
14674
14675        final int leftRtl;
14676        final int rightRtl;
14677        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14678            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14679            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14680        } else {
14681            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14682            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14683        }
14684
14685        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14686        if ((mPrivateFlags3 & leftMask) != 0) {
14687            final boolean canScrollLeft = canScrollHorizontally(-1);
14688            if (canScrollLeft) {
14689                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14690                dr.draw(c);
14691            }
14692        }
14693
14694        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14695        if ((mPrivateFlags3 & rightMask) != 0) {
14696            final boolean canScrollRight = canScrollHorizontally(1);
14697            if (canScrollRight) {
14698                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14699                dr.draw(c);
14700            }
14701        }
14702    }
14703
14704    private void getHorizontalScrollBarBounds(Rect bounds) {
14705        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14706        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14707                && !isVerticalScrollBarHidden();
14708        final int size = getHorizontalScrollbarHeight();
14709        final int verticalScrollBarGap = drawVerticalScrollBar ?
14710                getVerticalScrollbarWidth() : 0;
14711        final int width = mRight - mLeft;
14712        final int height = mBottom - mTop;
14713        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14714        bounds.left = mScrollX + (mPaddingLeft & inside);
14715        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14716        bounds.bottom = bounds.top + size;
14717    }
14718
14719    private void getVerticalScrollBarBounds(Rect bounds) {
14720        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14721        final int size = getVerticalScrollbarWidth();
14722        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14723        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14724            verticalScrollbarPosition = isLayoutRtl() ?
14725                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14726        }
14727        final int width = mRight - mLeft;
14728        final int height = mBottom - mTop;
14729        switch (verticalScrollbarPosition) {
14730            default:
14731            case SCROLLBAR_POSITION_RIGHT:
14732                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14733                break;
14734            case SCROLLBAR_POSITION_LEFT:
14735                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14736                break;
14737        }
14738        bounds.top = mScrollY + (mPaddingTop & inside);
14739        bounds.right = bounds.left + size;
14740        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14741    }
14742
14743    /**
14744     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14745     * scrollbars are painted only if they have been awakened first.</p>
14746     *
14747     * @param canvas the canvas on which to draw the scrollbars
14748     *
14749     * @see #awakenScrollBars(int)
14750     */
14751    protected final void onDrawScrollBars(Canvas canvas) {
14752        // scrollbars are drawn only when the animation is running
14753        final ScrollabilityCache cache = mScrollCache;
14754        if (cache != null) {
14755
14756            int state = cache.state;
14757
14758            if (state == ScrollabilityCache.OFF) {
14759                return;
14760            }
14761
14762            boolean invalidate = false;
14763
14764            if (state == ScrollabilityCache.FADING) {
14765                // We're fading -- get our fade interpolation
14766                if (cache.interpolatorValues == null) {
14767                    cache.interpolatorValues = new float[1];
14768                }
14769
14770                float[] values = cache.interpolatorValues;
14771
14772                // Stops the animation if we're done
14773                if (cache.scrollBarInterpolator.timeToValues(values) ==
14774                        Interpolator.Result.FREEZE_END) {
14775                    cache.state = ScrollabilityCache.OFF;
14776                } else {
14777                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14778                }
14779
14780                // This will make the scroll bars inval themselves after
14781                // drawing. We only want this when we're fading so that
14782                // we prevent excessive redraws
14783                invalidate = true;
14784            } else {
14785                // We're just on -- but we may have been fading before so
14786                // reset alpha
14787                cache.scrollBar.mutate().setAlpha(255);
14788            }
14789
14790            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14791            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14792                    && !isVerticalScrollBarHidden();
14793
14794            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14795                final ScrollBarDrawable scrollBar = cache.scrollBar;
14796
14797                if (drawHorizontalScrollBar) {
14798                    scrollBar.setParameters(computeHorizontalScrollRange(),
14799                                            computeHorizontalScrollOffset(),
14800                                            computeHorizontalScrollExtent(), false);
14801                    final Rect bounds = cache.mScrollBarBounds;
14802                    getHorizontalScrollBarBounds(bounds);
14803                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14804                            bounds.right, bounds.bottom);
14805                    if (invalidate) {
14806                        invalidate(bounds);
14807                    }
14808                }
14809
14810                if (drawVerticalScrollBar) {
14811                    scrollBar.setParameters(computeVerticalScrollRange(),
14812                                            computeVerticalScrollOffset(),
14813                                            computeVerticalScrollExtent(), true);
14814                    final Rect bounds = cache.mScrollBarBounds;
14815                    getVerticalScrollBarBounds(bounds);
14816                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14817                            bounds.right, bounds.bottom);
14818                    if (invalidate) {
14819                        invalidate(bounds);
14820                    }
14821                }
14822            }
14823        }
14824    }
14825
14826    /**
14827     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14828     * FastScroller is visible.
14829     * @return whether to temporarily hide the vertical scrollbar
14830     * @hide
14831     */
14832    protected boolean isVerticalScrollBarHidden() {
14833        return false;
14834    }
14835
14836    /**
14837     * <p>Draw the horizontal scrollbar if
14838     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14839     *
14840     * @param canvas the canvas on which to draw the scrollbar
14841     * @param scrollBar the scrollbar's drawable
14842     *
14843     * @see #isHorizontalScrollBarEnabled()
14844     * @see #computeHorizontalScrollRange()
14845     * @see #computeHorizontalScrollExtent()
14846     * @see #computeHorizontalScrollOffset()
14847     * @see android.widget.ScrollBarDrawable
14848     * @hide
14849     */
14850    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14851            int l, int t, int r, int b) {
14852        scrollBar.setBounds(l, t, r, b);
14853        scrollBar.draw(canvas);
14854    }
14855
14856    /**
14857     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14858     * returns true.</p>
14859     *
14860     * @param canvas the canvas on which to draw the scrollbar
14861     * @param scrollBar the scrollbar's drawable
14862     *
14863     * @see #isVerticalScrollBarEnabled()
14864     * @see #computeVerticalScrollRange()
14865     * @see #computeVerticalScrollExtent()
14866     * @see #computeVerticalScrollOffset()
14867     * @see android.widget.ScrollBarDrawable
14868     * @hide
14869     */
14870    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14871            int l, int t, int r, int b) {
14872        scrollBar.setBounds(l, t, r, b);
14873        scrollBar.draw(canvas);
14874    }
14875
14876    /**
14877     * Implement this to do your drawing.
14878     *
14879     * @param canvas the canvas on which the background will be drawn
14880     */
14881    protected void onDraw(Canvas canvas) {
14882    }
14883
14884    /*
14885     * Caller is responsible for calling requestLayout if necessary.
14886     * (This allows addViewInLayout to not request a new layout.)
14887     */
14888    void assignParent(ViewParent parent) {
14889        if (mParent == null) {
14890            mParent = parent;
14891        } else if (parent == null) {
14892            mParent = null;
14893        } else {
14894            throw new RuntimeException("view " + this + " being added, but"
14895                    + " it already has a parent");
14896        }
14897    }
14898
14899    /**
14900     * This is called when the view is attached to a window.  At this point it
14901     * has a Surface and will start drawing.  Note that this function is
14902     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14903     * however it may be called any time before the first onDraw -- including
14904     * before or after {@link #onMeasure(int, int)}.
14905     *
14906     * @see #onDetachedFromWindow()
14907     */
14908    @CallSuper
14909    protected void onAttachedToWindow() {
14910        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14911            mParent.requestTransparentRegion(this);
14912        }
14913
14914        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14915
14916        jumpDrawablesToCurrentState();
14917
14918        resetSubtreeAccessibilityStateChanged();
14919
14920        // rebuild, since Outline not maintained while View is detached
14921        rebuildOutline();
14922
14923        if (isFocused()) {
14924            InputMethodManager imm = InputMethodManager.peekInstance();
14925            if (imm != null) {
14926                imm.focusIn(this);
14927            }
14928        }
14929    }
14930
14931    /**
14932     * Resolve all RTL related properties.
14933     *
14934     * @return true if resolution of RTL properties has been done
14935     *
14936     * @hide
14937     */
14938    public boolean resolveRtlPropertiesIfNeeded() {
14939        if (!needRtlPropertiesResolution()) return false;
14940
14941        // Order is important here: LayoutDirection MUST be resolved first
14942        if (!isLayoutDirectionResolved()) {
14943            resolveLayoutDirection();
14944            resolveLayoutParams();
14945        }
14946        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14947        if (!isTextDirectionResolved()) {
14948            resolveTextDirection();
14949        }
14950        if (!isTextAlignmentResolved()) {
14951            resolveTextAlignment();
14952        }
14953        // Should resolve Drawables before Padding because we need the layout direction of the
14954        // Drawable to correctly resolve Padding.
14955        if (!areDrawablesResolved()) {
14956            resolveDrawables();
14957        }
14958        if (!isPaddingResolved()) {
14959            resolvePadding();
14960        }
14961        onRtlPropertiesChanged(getLayoutDirection());
14962        return true;
14963    }
14964
14965    /**
14966     * Reset resolution of all RTL related properties.
14967     *
14968     * @hide
14969     */
14970    public void resetRtlProperties() {
14971        resetResolvedLayoutDirection();
14972        resetResolvedTextDirection();
14973        resetResolvedTextAlignment();
14974        resetResolvedPadding();
14975        resetResolvedDrawables();
14976    }
14977
14978    /**
14979     * @see #onScreenStateChanged(int)
14980     */
14981    void dispatchScreenStateChanged(int screenState) {
14982        onScreenStateChanged(screenState);
14983    }
14984
14985    /**
14986     * This method is called whenever the state of the screen this view is
14987     * attached to changes. A state change will usually occurs when the screen
14988     * turns on or off (whether it happens automatically or the user does it
14989     * manually.)
14990     *
14991     * @param screenState The new state of the screen. Can be either
14992     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14993     */
14994    public void onScreenStateChanged(int screenState) {
14995    }
14996
14997    /**
14998     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
14999     */
15000    private boolean hasRtlSupport() {
15001        return mContext.getApplicationInfo().hasRtlSupport();
15002    }
15003
15004    /**
15005     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15006     * RTL not supported)
15007     */
15008    private boolean isRtlCompatibilityMode() {
15009        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15010        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15011    }
15012
15013    /**
15014     * @return true if RTL properties need resolution.
15015     *
15016     */
15017    private boolean needRtlPropertiesResolution() {
15018        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15019    }
15020
15021    /**
15022     * Called when any RTL property (layout direction or text direction or text alignment) has
15023     * been changed.
15024     *
15025     * Subclasses need to override this method to take care of cached information that depends on the
15026     * resolved layout direction, or to inform child views that inherit their layout direction.
15027     *
15028     * The default implementation does nothing.
15029     *
15030     * @param layoutDirection the direction of the layout
15031     *
15032     * @see #LAYOUT_DIRECTION_LTR
15033     * @see #LAYOUT_DIRECTION_RTL
15034     */
15035    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15036    }
15037
15038    /**
15039     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15040     * that the parent directionality can and will be resolved before its children.
15041     *
15042     * @return true if resolution has been done, false otherwise.
15043     *
15044     * @hide
15045     */
15046    public boolean resolveLayoutDirection() {
15047        // Clear any previous layout direction resolution
15048        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15049
15050        if (hasRtlSupport()) {
15051            // Set resolved depending on layout direction
15052            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15053                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15054                case LAYOUT_DIRECTION_INHERIT:
15055                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15056                    // later to get the correct resolved value
15057                    if (!canResolveLayoutDirection()) return false;
15058
15059                    // Parent has not yet resolved, LTR is still the default
15060                    try {
15061                        if (!mParent.isLayoutDirectionResolved()) return false;
15062
15063                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15064                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15065                        }
15066                    } catch (AbstractMethodError e) {
15067                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15068                                " does not fully implement ViewParent", e);
15069                    }
15070                    break;
15071                case LAYOUT_DIRECTION_RTL:
15072                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15073                    break;
15074                case LAYOUT_DIRECTION_LOCALE:
15075                    if((LAYOUT_DIRECTION_RTL ==
15076                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15077                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15078                    }
15079                    break;
15080                default:
15081                    // Nothing to do, LTR by default
15082            }
15083        }
15084
15085        // Set to resolved
15086        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15087        return true;
15088    }
15089
15090    /**
15091     * Check if layout direction resolution can be done.
15092     *
15093     * @return true if layout direction resolution can be done otherwise return false.
15094     */
15095    public boolean canResolveLayoutDirection() {
15096        switch (getRawLayoutDirection()) {
15097            case LAYOUT_DIRECTION_INHERIT:
15098                if (mParent != null) {
15099                    try {
15100                        return mParent.canResolveLayoutDirection();
15101                    } catch (AbstractMethodError e) {
15102                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15103                                " does not fully implement ViewParent", e);
15104                    }
15105                }
15106                return false;
15107
15108            default:
15109                return true;
15110        }
15111    }
15112
15113    /**
15114     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15115     * {@link #onMeasure(int, int)}.
15116     *
15117     * @hide
15118     */
15119    public void resetResolvedLayoutDirection() {
15120        // Reset the current resolved bits
15121        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15122    }
15123
15124    /**
15125     * @return true if the layout direction is inherited.
15126     *
15127     * @hide
15128     */
15129    public boolean isLayoutDirectionInherited() {
15130        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15131    }
15132
15133    /**
15134     * @return true if layout direction has been resolved.
15135     */
15136    public boolean isLayoutDirectionResolved() {
15137        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15138    }
15139
15140    /**
15141     * Return if padding has been resolved
15142     *
15143     * @hide
15144     */
15145    boolean isPaddingResolved() {
15146        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15147    }
15148
15149    /**
15150     * Resolves padding depending on layout direction, if applicable, and
15151     * recomputes internal padding values to adjust for scroll bars.
15152     *
15153     * @hide
15154     */
15155    public void resolvePadding() {
15156        final int resolvedLayoutDirection = getLayoutDirection();
15157
15158        if (!isRtlCompatibilityMode()) {
15159            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15160            // If start / end padding are defined, they will be resolved (hence overriding) to
15161            // left / right or right / left depending on the resolved layout direction.
15162            // If start / end padding are not defined, use the left / right ones.
15163            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15164                Rect padding = sThreadLocal.get();
15165                if (padding == null) {
15166                    padding = new Rect();
15167                    sThreadLocal.set(padding);
15168                }
15169                mBackground.getPadding(padding);
15170                if (!mLeftPaddingDefined) {
15171                    mUserPaddingLeftInitial = padding.left;
15172                }
15173                if (!mRightPaddingDefined) {
15174                    mUserPaddingRightInitial = padding.right;
15175                }
15176            }
15177            switch (resolvedLayoutDirection) {
15178                case LAYOUT_DIRECTION_RTL:
15179                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15180                        mUserPaddingRight = mUserPaddingStart;
15181                    } else {
15182                        mUserPaddingRight = mUserPaddingRightInitial;
15183                    }
15184                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15185                        mUserPaddingLeft = mUserPaddingEnd;
15186                    } else {
15187                        mUserPaddingLeft = mUserPaddingLeftInitial;
15188                    }
15189                    break;
15190                case LAYOUT_DIRECTION_LTR:
15191                default:
15192                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15193                        mUserPaddingLeft = mUserPaddingStart;
15194                    } else {
15195                        mUserPaddingLeft = mUserPaddingLeftInitial;
15196                    }
15197                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15198                        mUserPaddingRight = mUserPaddingEnd;
15199                    } else {
15200                        mUserPaddingRight = mUserPaddingRightInitial;
15201                    }
15202            }
15203
15204            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15205        }
15206
15207        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15208        onRtlPropertiesChanged(resolvedLayoutDirection);
15209
15210        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15211    }
15212
15213    /**
15214     * Reset the resolved layout direction.
15215     *
15216     * @hide
15217     */
15218    public void resetResolvedPadding() {
15219        resetResolvedPaddingInternal();
15220    }
15221
15222    /**
15223     * Used when we only want to reset *this* view's padding and not trigger overrides
15224     * in ViewGroup that reset children too.
15225     */
15226    void resetResolvedPaddingInternal() {
15227        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15228    }
15229
15230    /**
15231     * This is called when the view is detached from a window.  At this point it
15232     * no longer has a surface for drawing.
15233     *
15234     * @see #onAttachedToWindow()
15235     */
15236    @CallSuper
15237    protected void onDetachedFromWindow() {
15238    }
15239
15240    /**
15241     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15242     * after onDetachedFromWindow().
15243     *
15244     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15245     * The super method should be called at the end of the overridden method to ensure
15246     * subclasses are destroyed first
15247     *
15248     * @hide
15249     */
15250    @CallSuper
15251    protected void onDetachedFromWindowInternal() {
15252        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15253        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15254        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15255
15256        removeUnsetPressCallback();
15257        removeLongPressCallback();
15258        removePerformClickCallback();
15259        removeSendViewScrolledAccessibilityEventCallback();
15260        stopNestedScroll();
15261
15262        // Anything that started animating right before detach should already
15263        // be in its final state when re-attached.
15264        jumpDrawablesToCurrentState();
15265
15266        destroyDrawingCache();
15267
15268        cleanupDraw();
15269        mCurrentAnimation = null;
15270    }
15271
15272    private void cleanupDraw() {
15273        resetDisplayList();
15274        if (mAttachInfo != null) {
15275            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15276        }
15277    }
15278
15279    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15280    }
15281
15282    /**
15283     * @return The number of times this view has been attached to a window
15284     */
15285    protected int getWindowAttachCount() {
15286        return mWindowAttachCount;
15287    }
15288
15289    /**
15290     * Retrieve a unique token identifying the window this view is attached to.
15291     * @return Return the window's token for use in
15292     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15293     */
15294    public IBinder getWindowToken() {
15295        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15296    }
15297
15298    /**
15299     * Retrieve the {@link WindowId} for the window this view is
15300     * currently attached to.
15301     */
15302    public WindowId getWindowId() {
15303        if (mAttachInfo == null) {
15304            return null;
15305        }
15306        if (mAttachInfo.mWindowId == null) {
15307            try {
15308                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15309                        mAttachInfo.mWindowToken);
15310                mAttachInfo.mWindowId = new WindowId(
15311                        mAttachInfo.mIWindowId);
15312            } catch (RemoteException e) {
15313            }
15314        }
15315        return mAttachInfo.mWindowId;
15316    }
15317
15318    /**
15319     * Retrieve a unique token identifying the top-level "real" window of
15320     * the window that this view is attached to.  That is, this is like
15321     * {@link #getWindowToken}, except if the window this view in is a panel
15322     * window (attached to another containing window), then the token of
15323     * the containing window is returned instead.
15324     *
15325     * @return Returns the associated window token, either
15326     * {@link #getWindowToken()} or the containing window's token.
15327     */
15328    public IBinder getApplicationWindowToken() {
15329        AttachInfo ai = mAttachInfo;
15330        if (ai != null) {
15331            IBinder appWindowToken = ai.mPanelParentWindowToken;
15332            if (appWindowToken == null) {
15333                appWindowToken = ai.mWindowToken;
15334            }
15335            return appWindowToken;
15336        }
15337        return null;
15338    }
15339
15340    /**
15341     * Gets the logical display to which the view's window has been attached.
15342     *
15343     * @return The logical display, or null if the view is not currently attached to a window.
15344     */
15345    public Display getDisplay() {
15346        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15347    }
15348
15349    /**
15350     * Retrieve private session object this view hierarchy is using to
15351     * communicate with the window manager.
15352     * @return the session object to communicate with the window manager
15353     */
15354    /*package*/ IWindowSession getWindowSession() {
15355        return mAttachInfo != null ? mAttachInfo.mSession : null;
15356    }
15357
15358    /**
15359     * Return the visibility value of the least visible component passed.
15360     */
15361    int combineVisibility(int vis1, int vis2) {
15362        // This works because VISIBLE < INVISIBLE < GONE.
15363        return Math.max(vis1, vis2);
15364    }
15365
15366    /**
15367     * @param info the {@link android.view.View.AttachInfo} to associated with
15368     *        this view
15369     */
15370    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15371        mAttachInfo = info;
15372        if (mOverlay != null) {
15373            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15374        }
15375        mWindowAttachCount++;
15376        // We will need to evaluate the drawable state at least once.
15377        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15378        if (mFloatingTreeObserver != null) {
15379            info.mTreeObserver.merge(mFloatingTreeObserver);
15380            mFloatingTreeObserver = null;
15381        }
15382
15383        registerPendingFrameMetricsObservers();
15384
15385        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15386            mAttachInfo.mScrollContainers.add(this);
15387            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15388        }
15389        // Transfer all pending runnables.
15390        if (mRunQueue != null) {
15391            mRunQueue.executeActions(info.mHandler);
15392            mRunQueue = null;
15393        }
15394        performCollectViewAttributes(mAttachInfo, visibility);
15395        onAttachedToWindow();
15396
15397        ListenerInfo li = mListenerInfo;
15398        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15399                li != null ? li.mOnAttachStateChangeListeners : null;
15400        if (listeners != null && listeners.size() > 0) {
15401            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15402            // perform the dispatching. The iterator is a safe guard against listeners that
15403            // could mutate the list by calling the various add/remove methods. This prevents
15404            // the array from being modified while we iterate it.
15405            for (OnAttachStateChangeListener listener : listeners) {
15406                listener.onViewAttachedToWindow(this);
15407            }
15408        }
15409
15410        int vis = info.mWindowVisibility;
15411        if (vis != GONE) {
15412            onWindowVisibilityChanged(vis);
15413            if (isShown()) {
15414                // Calling onVisibilityChanged directly here since the subtree will also
15415                // receive dispatchAttachedToWindow and this same call
15416                onVisibilityAggregated(vis == VISIBLE);
15417            }
15418        }
15419
15420        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15421        // As all views in the subtree will already receive dispatchAttachedToWindow
15422        // traversing the subtree again here is not desired.
15423        onVisibilityChanged(this, visibility);
15424
15425        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15426            // If nobody has evaluated the drawable state yet, then do it now.
15427            refreshDrawableState();
15428        }
15429        needGlobalAttributesUpdate(false);
15430    }
15431
15432    void dispatchDetachedFromWindow() {
15433        AttachInfo info = mAttachInfo;
15434        if (info != null) {
15435            int vis = info.mWindowVisibility;
15436            if (vis != GONE) {
15437                onWindowVisibilityChanged(GONE);
15438                if (isShown()) {
15439                    // Invoking onVisibilityAggregated directly here since the subtree
15440                    // will also receive detached from window
15441                    onVisibilityAggregated(false);
15442                }
15443            }
15444        }
15445
15446        onDetachedFromWindow();
15447        onDetachedFromWindowInternal();
15448
15449        InputMethodManager imm = InputMethodManager.peekInstance();
15450        if (imm != null) {
15451            imm.onViewDetachedFromWindow(this);
15452        }
15453
15454        ListenerInfo li = mListenerInfo;
15455        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15456                li != null ? li.mOnAttachStateChangeListeners : null;
15457        if (listeners != null && listeners.size() > 0) {
15458            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15459            // perform the dispatching. The iterator is a safe guard against listeners that
15460            // could mutate the list by calling the various add/remove methods. This prevents
15461            // the array from being modified while we iterate it.
15462            for (OnAttachStateChangeListener listener : listeners) {
15463                listener.onViewDetachedFromWindow(this);
15464            }
15465        }
15466
15467        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15468            mAttachInfo.mScrollContainers.remove(this);
15469            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15470        }
15471
15472        mAttachInfo = null;
15473        if (mOverlay != null) {
15474            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15475        }
15476    }
15477
15478    /**
15479     * Cancel any deferred high-level input events that were previously posted to the event queue.
15480     *
15481     * <p>Many views post high-level events such as click handlers to the event queue
15482     * to run deferred in order to preserve a desired user experience - clearing visible
15483     * pressed states before executing, etc. This method will abort any events of this nature
15484     * that are currently in flight.</p>
15485     *
15486     * <p>Custom views that generate their own high-level deferred input events should override
15487     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15488     *
15489     * <p>This will also cancel pending input events for any child views.</p>
15490     *
15491     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15492     * This will not impact newer events posted after this call that may occur as a result of
15493     * lower-level input events still waiting in the queue. If you are trying to prevent
15494     * double-submitted  events for the duration of some sort of asynchronous transaction
15495     * you should also take other steps to protect against unexpected double inputs e.g. calling
15496     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15497     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15498     */
15499    public final void cancelPendingInputEvents() {
15500        dispatchCancelPendingInputEvents();
15501    }
15502
15503    /**
15504     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15505     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15506     */
15507    void dispatchCancelPendingInputEvents() {
15508        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15509        onCancelPendingInputEvents();
15510        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15511            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15512                    " did not call through to super.onCancelPendingInputEvents()");
15513        }
15514    }
15515
15516    /**
15517     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15518     * a parent view.
15519     *
15520     * <p>This method is responsible for removing any pending high-level input events that were
15521     * posted to the event queue to run later. Custom view classes that post their own deferred
15522     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15523     * {@link android.os.Handler} should override this method, call
15524     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15525     * </p>
15526     */
15527    public void onCancelPendingInputEvents() {
15528        removePerformClickCallback();
15529        cancelLongPress();
15530        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15531    }
15532
15533    /**
15534     * Store this view hierarchy's frozen state into the given container.
15535     *
15536     * @param container The SparseArray in which to save the view's state.
15537     *
15538     * @see #restoreHierarchyState(android.util.SparseArray)
15539     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15540     * @see #onSaveInstanceState()
15541     */
15542    public void saveHierarchyState(SparseArray<Parcelable> container) {
15543        dispatchSaveInstanceState(container);
15544    }
15545
15546    /**
15547     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15548     * this view and its children. May be overridden to modify how freezing happens to a
15549     * view's children; for example, some views may want to not store state for their children.
15550     *
15551     * @param container The SparseArray in which to save the view's state.
15552     *
15553     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15554     * @see #saveHierarchyState(android.util.SparseArray)
15555     * @see #onSaveInstanceState()
15556     */
15557    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15558        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15559            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15560            Parcelable state = onSaveInstanceState();
15561            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15562                throw new IllegalStateException(
15563                        "Derived class did not call super.onSaveInstanceState()");
15564            }
15565            if (state != null) {
15566                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15567                // + ": " + state);
15568                container.put(mID, state);
15569            }
15570        }
15571    }
15572
15573    /**
15574     * Hook allowing a view to generate a representation of its internal state
15575     * that can later be used to create a new instance with that same state.
15576     * This state should only contain information that is not persistent or can
15577     * not be reconstructed later. For example, you will never store your
15578     * current position on screen because that will be computed again when a
15579     * new instance of the view is placed in its view hierarchy.
15580     * <p>
15581     * Some examples of things you may store here: the current cursor position
15582     * in a text view (but usually not the text itself since that is stored in a
15583     * content provider or other persistent storage), the currently selected
15584     * item in a list view.
15585     *
15586     * @return Returns a Parcelable object containing the view's current dynamic
15587     *         state, or null if there is nothing interesting to save. The
15588     *         default implementation returns null.
15589     * @see #onRestoreInstanceState(android.os.Parcelable)
15590     * @see #saveHierarchyState(android.util.SparseArray)
15591     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15592     * @see #setSaveEnabled(boolean)
15593     */
15594    @CallSuper
15595    protected Parcelable onSaveInstanceState() {
15596        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15597        if (mStartActivityRequestWho != null) {
15598            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15599            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15600            return state;
15601        }
15602        return BaseSavedState.EMPTY_STATE;
15603    }
15604
15605    /**
15606     * Restore this view hierarchy's frozen state from the given container.
15607     *
15608     * @param container The SparseArray which holds previously frozen states.
15609     *
15610     * @see #saveHierarchyState(android.util.SparseArray)
15611     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15612     * @see #onRestoreInstanceState(android.os.Parcelable)
15613     */
15614    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15615        dispatchRestoreInstanceState(container);
15616    }
15617
15618    /**
15619     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15620     * state for this view and its children. May be overridden to modify how restoring
15621     * happens to a view's children; for example, some views may want to not store state
15622     * for their children.
15623     *
15624     * @param container The SparseArray which holds previously saved state.
15625     *
15626     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15627     * @see #restoreHierarchyState(android.util.SparseArray)
15628     * @see #onRestoreInstanceState(android.os.Parcelable)
15629     */
15630    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15631        if (mID != NO_ID) {
15632            Parcelable state = container.get(mID);
15633            if (state != null) {
15634                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15635                // + ": " + state);
15636                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15637                onRestoreInstanceState(state);
15638                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15639                    throw new IllegalStateException(
15640                            "Derived class did not call super.onRestoreInstanceState()");
15641                }
15642            }
15643        }
15644    }
15645
15646    /**
15647     * Hook allowing a view to re-apply a representation of its internal state that had previously
15648     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15649     * null state.
15650     *
15651     * @param state The frozen state that had previously been returned by
15652     *        {@link #onSaveInstanceState}.
15653     *
15654     * @see #onSaveInstanceState()
15655     * @see #restoreHierarchyState(android.util.SparseArray)
15656     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15657     */
15658    @CallSuper
15659    protected void onRestoreInstanceState(Parcelable state) {
15660        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15661        if (state != null && !(state instanceof AbsSavedState)) {
15662            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15663                    + "received " + state.getClass().toString() + " instead. This usually happens "
15664                    + "when two views of different type have the same id in the same hierarchy. "
15665                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15666                    + "other views do not use the same id.");
15667        }
15668        if (state != null && state instanceof BaseSavedState) {
15669            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15670        }
15671    }
15672
15673    /**
15674     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15675     *
15676     * @return the drawing start time in milliseconds
15677     */
15678    public long getDrawingTime() {
15679        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15680    }
15681
15682    /**
15683     * <p>Enables or disables the duplication of the parent's state into this view. When
15684     * duplication is enabled, this view gets its drawable state from its parent rather
15685     * than from its own internal properties.</p>
15686     *
15687     * <p>Note: in the current implementation, setting this property to true after the
15688     * view was added to a ViewGroup might have no effect at all. This property should
15689     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15690     *
15691     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15692     * property is enabled, an exception will be thrown.</p>
15693     *
15694     * <p>Note: if the child view uses and updates additional states which are unknown to the
15695     * parent, these states should not be affected by this method.</p>
15696     *
15697     * @param enabled True to enable duplication of the parent's drawable state, false
15698     *                to disable it.
15699     *
15700     * @see #getDrawableState()
15701     * @see #isDuplicateParentStateEnabled()
15702     */
15703    public void setDuplicateParentStateEnabled(boolean enabled) {
15704        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15705    }
15706
15707    /**
15708     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15709     *
15710     * @return True if this view's drawable state is duplicated from the parent,
15711     *         false otherwise
15712     *
15713     * @see #getDrawableState()
15714     * @see #setDuplicateParentStateEnabled(boolean)
15715     */
15716    public boolean isDuplicateParentStateEnabled() {
15717        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15718    }
15719
15720    /**
15721     * <p>Specifies the type of layer backing this view. The layer can be
15722     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15723     * {@link #LAYER_TYPE_HARDWARE}.</p>
15724     *
15725     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15726     * instance that controls how the layer is composed on screen. The following
15727     * properties of the paint are taken into account when composing the layer:</p>
15728     * <ul>
15729     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15730     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15731     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15732     * </ul>
15733     *
15734     * <p>If this view has an alpha value set to < 1.0 by calling
15735     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15736     * by this view's alpha value.</p>
15737     *
15738     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15739     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15740     * for more information on when and how to use layers.</p>
15741     *
15742     * @param layerType The type of layer to use with this view, must be one of
15743     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15744     *        {@link #LAYER_TYPE_HARDWARE}
15745     * @param paint The paint used to compose the layer. This argument is optional
15746     *        and can be null. It is ignored when the layer type is
15747     *        {@link #LAYER_TYPE_NONE}
15748     *
15749     * @see #getLayerType()
15750     * @see #LAYER_TYPE_NONE
15751     * @see #LAYER_TYPE_SOFTWARE
15752     * @see #LAYER_TYPE_HARDWARE
15753     * @see #setAlpha(float)
15754     *
15755     * @attr ref android.R.styleable#View_layerType
15756     */
15757    public void setLayerType(int layerType, @Nullable Paint paint) {
15758        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15759            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15760                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15761        }
15762
15763        boolean typeChanged = mRenderNode.setLayerType(layerType);
15764
15765        if (!typeChanged) {
15766            setLayerPaint(paint);
15767            return;
15768        }
15769
15770        if (layerType != LAYER_TYPE_SOFTWARE) {
15771            // Destroy any previous software drawing cache if present
15772            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15773            // drawing cache created in View#draw when drawing to a SW canvas.
15774            destroyDrawingCache();
15775        }
15776
15777        mLayerType = layerType;
15778        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15779        mRenderNode.setLayerPaint(mLayerPaint);
15780
15781        // draw() behaves differently if we are on a layer, so we need to
15782        // invalidate() here
15783        invalidateParentCaches();
15784        invalidate(true);
15785    }
15786
15787    /**
15788     * Updates the {@link Paint} object used with the current layer (used only if the current
15789     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15790     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15791     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15792     * ensure that the view gets redrawn immediately.
15793     *
15794     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15795     * instance that controls how the layer is composed on screen. The following
15796     * properties of the paint are taken into account when composing the layer:</p>
15797     * <ul>
15798     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15799     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15800     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15801     * </ul>
15802     *
15803     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15804     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15805     *
15806     * @param paint The paint used to compose the layer. This argument is optional
15807     *        and can be null. It is ignored when the layer type is
15808     *        {@link #LAYER_TYPE_NONE}
15809     *
15810     * @see #setLayerType(int, android.graphics.Paint)
15811     */
15812    public void setLayerPaint(@Nullable Paint paint) {
15813        int layerType = getLayerType();
15814        if (layerType != LAYER_TYPE_NONE) {
15815            mLayerPaint = paint;
15816            if (layerType == LAYER_TYPE_HARDWARE) {
15817                if (mRenderNode.setLayerPaint(paint)) {
15818                    invalidateViewProperty(false, false);
15819                }
15820            } else {
15821                invalidate();
15822            }
15823        }
15824    }
15825
15826    /**
15827     * Indicates what type of layer is currently associated with this view. By default
15828     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15829     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15830     * for more information on the different types of layers.
15831     *
15832     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15833     *         {@link #LAYER_TYPE_HARDWARE}
15834     *
15835     * @see #setLayerType(int, android.graphics.Paint)
15836     * @see #buildLayer()
15837     * @see #LAYER_TYPE_NONE
15838     * @see #LAYER_TYPE_SOFTWARE
15839     * @see #LAYER_TYPE_HARDWARE
15840     */
15841    public int getLayerType() {
15842        return mLayerType;
15843    }
15844
15845    /**
15846     * Forces this view's layer to be created and this view to be rendered
15847     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15848     * invoking this method will have no effect.
15849     *
15850     * This method can for instance be used to render a view into its layer before
15851     * starting an animation. If this view is complex, rendering into the layer
15852     * before starting the animation will avoid skipping frames.
15853     *
15854     * @throws IllegalStateException If this view is not attached to a window
15855     *
15856     * @see #setLayerType(int, android.graphics.Paint)
15857     */
15858    public void buildLayer() {
15859        if (mLayerType == LAYER_TYPE_NONE) return;
15860
15861        final AttachInfo attachInfo = mAttachInfo;
15862        if (attachInfo == null) {
15863            throw new IllegalStateException("This view must be attached to a window first");
15864        }
15865
15866        if (getWidth() == 0 || getHeight() == 0) {
15867            return;
15868        }
15869
15870        switch (mLayerType) {
15871            case LAYER_TYPE_HARDWARE:
15872                updateDisplayListIfDirty();
15873                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
15874                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
15875                }
15876                break;
15877            case LAYER_TYPE_SOFTWARE:
15878                buildDrawingCache(true);
15879                break;
15880        }
15881    }
15882
15883    /**
15884     * Destroys all hardware rendering resources. This method is invoked
15885     * when the system needs to reclaim resources. Upon execution of this
15886     * method, you should free any OpenGL resources created by the view.
15887     *
15888     * Note: you <strong>must</strong> call
15889     * <code>super.destroyHardwareResources()</code> when overriding
15890     * this method.
15891     *
15892     * @hide
15893     */
15894    @CallSuper
15895    protected void destroyHardwareResources() {
15896        // Although the Layer will be destroyed by RenderNode, we want to release
15897        // the staging display list, which is also a signal to RenderNode that it's
15898        // safe to free its copy of the display list as it knows that we will
15899        // push an updated DisplayList if we try to draw again
15900        resetDisplayList();
15901    }
15902
15903    /**
15904     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15905     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15906     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15907     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15908     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15909     * null.</p>
15910     *
15911     * <p>Enabling the drawing cache is similar to
15912     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15913     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15914     * drawing cache has no effect on rendering because the system uses a different mechanism
15915     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15916     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15917     * for information on how to enable software and hardware layers.</p>
15918     *
15919     * <p>This API can be used to manually generate
15920     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15921     * {@link #getDrawingCache()}.</p>
15922     *
15923     * @param enabled true to enable the drawing cache, false otherwise
15924     *
15925     * @see #isDrawingCacheEnabled()
15926     * @see #getDrawingCache()
15927     * @see #buildDrawingCache()
15928     * @see #setLayerType(int, android.graphics.Paint)
15929     */
15930    public void setDrawingCacheEnabled(boolean enabled) {
15931        mCachingFailed = false;
15932        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15933    }
15934
15935    /**
15936     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15937     *
15938     * @return true if the drawing cache is enabled
15939     *
15940     * @see #setDrawingCacheEnabled(boolean)
15941     * @see #getDrawingCache()
15942     */
15943    @ViewDebug.ExportedProperty(category = "drawing")
15944    public boolean isDrawingCacheEnabled() {
15945        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15946    }
15947
15948    /**
15949     * Debugging utility which recursively outputs the dirty state of a view and its
15950     * descendants.
15951     *
15952     * @hide
15953     */
15954    @SuppressWarnings({"UnusedDeclaration"})
15955    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15956        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15957                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15958                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15959                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15960        if (clear) {
15961            mPrivateFlags &= clearMask;
15962        }
15963        if (this instanceof ViewGroup) {
15964            ViewGroup parent = (ViewGroup) this;
15965            final int count = parent.getChildCount();
15966            for (int i = 0; i < count; i++) {
15967                final View child = parent.getChildAt(i);
15968                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15969            }
15970        }
15971    }
15972
15973    /**
15974     * This method is used by ViewGroup to cause its children to restore or recreate their
15975     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15976     * to recreate its own display list, which would happen if it went through the normal
15977     * draw/dispatchDraw mechanisms.
15978     *
15979     * @hide
15980     */
15981    protected void dispatchGetDisplayList() {}
15982
15983    /**
15984     * A view that is not attached or hardware accelerated cannot create a display list.
15985     * This method checks these conditions and returns the appropriate result.
15986     *
15987     * @return true if view has the ability to create a display list, false otherwise.
15988     *
15989     * @hide
15990     */
15991    public boolean canHaveDisplayList() {
15992        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
15993    }
15994
15995    /**
15996     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15997     * @hide
15998     */
15999    @NonNull
16000    public RenderNode updateDisplayListIfDirty() {
16001        final RenderNode renderNode = mRenderNode;
16002        if (!canHaveDisplayList()) {
16003            // can't populate RenderNode, don't try
16004            return renderNode;
16005        }
16006
16007        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16008                || !renderNode.isValid()
16009                || (mRecreateDisplayList)) {
16010            // Don't need to recreate the display list, just need to tell our
16011            // children to restore/recreate theirs
16012            if (renderNode.isValid()
16013                    && !mRecreateDisplayList) {
16014                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16015                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16016                dispatchGetDisplayList();
16017
16018                return renderNode; // no work needed
16019            }
16020
16021            // If we got here, we're recreating it. Mark it as such to ensure that
16022            // we copy in child display lists into ours in drawChild()
16023            mRecreateDisplayList = true;
16024
16025            int width = mRight - mLeft;
16026            int height = mBottom - mTop;
16027            int layerType = getLayerType();
16028
16029            final DisplayListCanvas canvas = renderNode.start(width, height);
16030            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16031
16032            try {
16033                if (layerType == LAYER_TYPE_SOFTWARE) {
16034                    buildDrawingCache(true);
16035                    Bitmap cache = getDrawingCache(true);
16036                    if (cache != null) {
16037                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16038                    }
16039                } else {
16040                    computeScroll();
16041
16042                    canvas.translate(-mScrollX, -mScrollY);
16043                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16044                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16045
16046                    // Fast path for layouts with no backgrounds
16047                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16048                        dispatchDraw(canvas);
16049                        if (mOverlay != null && !mOverlay.isEmpty()) {
16050                            mOverlay.getOverlayView().draw(canvas);
16051                        }
16052                    } else {
16053                        draw(canvas);
16054                    }
16055                }
16056            } finally {
16057                renderNode.end(canvas);
16058                setDisplayListProperties(renderNode);
16059            }
16060        } else {
16061            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16062            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16063        }
16064        return renderNode;
16065    }
16066
16067    private void resetDisplayList() {
16068        if (mRenderNode.isValid()) {
16069            mRenderNode.discardDisplayList();
16070        }
16071
16072        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16073            mBackgroundRenderNode.discardDisplayList();
16074        }
16075    }
16076
16077    /**
16078     * Called when the passed RenderNode is removed from the draw tree
16079     * @hide
16080     */
16081    public void onRenderNodeDetached(RenderNode renderNode) {
16082    }
16083
16084    /**
16085     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16086     *
16087     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16088     *
16089     * @see #getDrawingCache(boolean)
16090     */
16091    public Bitmap getDrawingCache() {
16092        return getDrawingCache(false);
16093    }
16094
16095    /**
16096     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16097     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16098     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16099     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16100     * request the drawing cache by calling this method and draw it on screen if the
16101     * returned bitmap is not null.</p>
16102     *
16103     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16104     * this method will create a bitmap of the same size as this view. Because this bitmap
16105     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16106     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16107     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16108     * size than the view. This implies that your application must be able to handle this
16109     * size.</p>
16110     *
16111     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16112     *        the current density of the screen when the application is in compatibility
16113     *        mode.
16114     *
16115     * @return A bitmap representing this view or null if cache is disabled.
16116     *
16117     * @see #setDrawingCacheEnabled(boolean)
16118     * @see #isDrawingCacheEnabled()
16119     * @see #buildDrawingCache(boolean)
16120     * @see #destroyDrawingCache()
16121     */
16122    public Bitmap getDrawingCache(boolean autoScale) {
16123        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16124            return null;
16125        }
16126        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16127            buildDrawingCache(autoScale);
16128        }
16129        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16130    }
16131
16132    /**
16133     * <p>Frees the resources used by the drawing cache. If you call
16134     * {@link #buildDrawingCache()} manually without calling
16135     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16136     * should cleanup the cache with this method afterwards.</p>
16137     *
16138     * @see #setDrawingCacheEnabled(boolean)
16139     * @see #buildDrawingCache()
16140     * @see #getDrawingCache()
16141     */
16142    public void destroyDrawingCache() {
16143        if (mDrawingCache != null) {
16144            mDrawingCache.recycle();
16145            mDrawingCache = null;
16146        }
16147        if (mUnscaledDrawingCache != null) {
16148            mUnscaledDrawingCache.recycle();
16149            mUnscaledDrawingCache = null;
16150        }
16151    }
16152
16153    /**
16154     * Setting a solid background color for the drawing cache's bitmaps will improve
16155     * performance and memory usage. Note, though that this should only be used if this
16156     * view will always be drawn on top of a solid color.
16157     *
16158     * @param color The background color to use for the drawing cache's bitmap
16159     *
16160     * @see #setDrawingCacheEnabled(boolean)
16161     * @see #buildDrawingCache()
16162     * @see #getDrawingCache()
16163     */
16164    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16165        if (color != mDrawingCacheBackgroundColor) {
16166            mDrawingCacheBackgroundColor = color;
16167            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16168        }
16169    }
16170
16171    /**
16172     * @see #setDrawingCacheBackgroundColor(int)
16173     *
16174     * @return The background color to used for the drawing cache's bitmap
16175     */
16176    @ColorInt
16177    public int getDrawingCacheBackgroundColor() {
16178        return mDrawingCacheBackgroundColor;
16179    }
16180
16181    /**
16182     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16183     *
16184     * @see #buildDrawingCache(boolean)
16185     */
16186    public void buildDrawingCache() {
16187        buildDrawingCache(false);
16188    }
16189
16190    /**
16191     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16192     *
16193     * <p>If you call {@link #buildDrawingCache()} manually without calling
16194     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16195     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16196     *
16197     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16198     * this method will create a bitmap of the same size as this view. Because this bitmap
16199     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16200     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16201     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16202     * size than the view. This implies that your application must be able to handle this
16203     * size.</p>
16204     *
16205     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16206     * you do not need the drawing cache bitmap, calling this method will increase memory
16207     * usage and cause the view to be rendered in software once, thus negatively impacting
16208     * performance.</p>
16209     *
16210     * @see #getDrawingCache()
16211     * @see #destroyDrawingCache()
16212     */
16213    public void buildDrawingCache(boolean autoScale) {
16214        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16215                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16216            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16217                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16218                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16219            }
16220            try {
16221                buildDrawingCacheImpl(autoScale);
16222            } finally {
16223                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16224            }
16225        }
16226    }
16227
16228    /**
16229     * private, internal implementation of buildDrawingCache, used to enable tracing
16230     */
16231    private void buildDrawingCacheImpl(boolean autoScale) {
16232        mCachingFailed = false;
16233
16234        int width = mRight - mLeft;
16235        int height = mBottom - mTop;
16236
16237        final AttachInfo attachInfo = mAttachInfo;
16238        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16239
16240        if (autoScale && scalingRequired) {
16241            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16242            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16243        }
16244
16245        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16246        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16247        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16248
16249        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16250        final long drawingCacheSize =
16251                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16252        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16253            if (width > 0 && height > 0) {
16254                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16255                        + " too large to fit into a software layer (or drawing cache), needs "
16256                        + projectedBitmapSize + " bytes, only "
16257                        + drawingCacheSize + " available");
16258            }
16259            destroyDrawingCache();
16260            mCachingFailed = true;
16261            return;
16262        }
16263
16264        boolean clear = true;
16265        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16266
16267        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16268            Bitmap.Config quality;
16269            if (!opaque) {
16270                // Never pick ARGB_4444 because it looks awful
16271                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16272                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16273                    case DRAWING_CACHE_QUALITY_AUTO:
16274                    case DRAWING_CACHE_QUALITY_LOW:
16275                    case DRAWING_CACHE_QUALITY_HIGH:
16276                    default:
16277                        quality = Bitmap.Config.ARGB_8888;
16278                        break;
16279                }
16280            } else {
16281                // Optimization for translucent windows
16282                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16283                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16284            }
16285
16286            // Try to cleanup memory
16287            if (bitmap != null) bitmap.recycle();
16288
16289            try {
16290                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16291                        width, height, quality);
16292                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16293                if (autoScale) {
16294                    mDrawingCache = bitmap;
16295                } else {
16296                    mUnscaledDrawingCache = bitmap;
16297                }
16298                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16299            } catch (OutOfMemoryError e) {
16300                // If there is not enough memory to create the bitmap cache, just
16301                // ignore the issue as bitmap caches are not required to draw the
16302                // view hierarchy
16303                if (autoScale) {
16304                    mDrawingCache = null;
16305                } else {
16306                    mUnscaledDrawingCache = null;
16307                }
16308                mCachingFailed = true;
16309                return;
16310            }
16311
16312            clear = drawingCacheBackgroundColor != 0;
16313        }
16314
16315        Canvas canvas;
16316        if (attachInfo != null) {
16317            canvas = attachInfo.mCanvas;
16318            if (canvas == null) {
16319                canvas = new Canvas();
16320            }
16321            canvas.setBitmap(bitmap);
16322            // Temporarily clobber the cached Canvas in case one of our children
16323            // is also using a drawing cache. Without this, the children would
16324            // steal the canvas by attaching their own bitmap to it and bad, bad
16325            // thing would happen (invisible views, corrupted drawings, etc.)
16326            attachInfo.mCanvas = null;
16327        } else {
16328            // This case should hopefully never or seldom happen
16329            canvas = new Canvas(bitmap);
16330        }
16331
16332        if (clear) {
16333            bitmap.eraseColor(drawingCacheBackgroundColor);
16334        }
16335
16336        computeScroll();
16337        final int restoreCount = canvas.save();
16338
16339        if (autoScale && scalingRequired) {
16340            final float scale = attachInfo.mApplicationScale;
16341            canvas.scale(scale, scale);
16342        }
16343
16344        canvas.translate(-mScrollX, -mScrollY);
16345
16346        mPrivateFlags |= PFLAG_DRAWN;
16347        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16348                mLayerType != LAYER_TYPE_NONE) {
16349            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16350        }
16351
16352        // Fast path for layouts with no backgrounds
16353        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16354            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16355            dispatchDraw(canvas);
16356            if (mOverlay != null && !mOverlay.isEmpty()) {
16357                mOverlay.getOverlayView().draw(canvas);
16358            }
16359        } else {
16360            draw(canvas);
16361        }
16362
16363        canvas.restoreToCount(restoreCount);
16364        canvas.setBitmap(null);
16365
16366        if (attachInfo != null) {
16367            // Restore the cached Canvas for our siblings
16368            attachInfo.mCanvas = canvas;
16369        }
16370    }
16371
16372    /**
16373     * Create a snapshot of the view into a bitmap.  We should probably make
16374     * some form of this public, but should think about the API.
16375     *
16376     * @hide
16377     */
16378    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16379        int width = mRight - mLeft;
16380        int height = mBottom - mTop;
16381
16382        final AttachInfo attachInfo = mAttachInfo;
16383        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16384        width = (int) ((width * scale) + 0.5f);
16385        height = (int) ((height * scale) + 0.5f);
16386
16387        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16388                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16389        if (bitmap == null) {
16390            throw new OutOfMemoryError();
16391        }
16392
16393        Resources resources = getResources();
16394        if (resources != null) {
16395            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16396        }
16397
16398        Canvas canvas;
16399        if (attachInfo != null) {
16400            canvas = attachInfo.mCanvas;
16401            if (canvas == null) {
16402                canvas = new Canvas();
16403            }
16404            canvas.setBitmap(bitmap);
16405            // Temporarily clobber the cached Canvas in case one of our children
16406            // is also using a drawing cache. Without this, the children would
16407            // steal the canvas by attaching their own bitmap to it and bad, bad
16408            // things would happen (invisible views, corrupted drawings, etc.)
16409            attachInfo.mCanvas = null;
16410        } else {
16411            // This case should hopefully never or seldom happen
16412            canvas = new Canvas(bitmap);
16413        }
16414
16415        if ((backgroundColor & 0xff000000) != 0) {
16416            bitmap.eraseColor(backgroundColor);
16417        }
16418
16419        computeScroll();
16420        final int restoreCount = canvas.save();
16421        canvas.scale(scale, scale);
16422        canvas.translate(-mScrollX, -mScrollY);
16423
16424        // Temporarily remove the dirty mask
16425        int flags = mPrivateFlags;
16426        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16427
16428        // Fast path for layouts with no backgrounds
16429        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16430            dispatchDraw(canvas);
16431            if (mOverlay != null && !mOverlay.isEmpty()) {
16432                mOverlay.getOverlayView().draw(canvas);
16433            }
16434        } else {
16435            draw(canvas);
16436        }
16437
16438        mPrivateFlags = flags;
16439
16440        canvas.restoreToCount(restoreCount);
16441        canvas.setBitmap(null);
16442
16443        if (attachInfo != null) {
16444            // Restore the cached Canvas for our siblings
16445            attachInfo.mCanvas = canvas;
16446        }
16447
16448        return bitmap;
16449    }
16450
16451    /**
16452     * Indicates whether this View is currently in edit mode. A View is usually
16453     * in edit mode when displayed within a developer tool. For instance, if
16454     * this View is being drawn by a visual user interface builder, this method
16455     * should return true.
16456     *
16457     * Subclasses should check the return value of this method to provide
16458     * different behaviors if their normal behavior might interfere with the
16459     * host environment. For instance: the class spawns a thread in its
16460     * constructor, the drawing code relies on device-specific features, etc.
16461     *
16462     * This method is usually checked in the drawing code of custom widgets.
16463     *
16464     * @return True if this View is in edit mode, false otherwise.
16465     */
16466    public boolean isInEditMode() {
16467        return false;
16468    }
16469
16470    /**
16471     * If the View draws content inside its padding and enables fading edges,
16472     * it needs to support padding offsets. Padding offsets are added to the
16473     * fading edges to extend the length of the fade so that it covers pixels
16474     * drawn inside the padding.
16475     *
16476     * Subclasses of this class should override this method if they need
16477     * to draw content inside the padding.
16478     *
16479     * @return True if padding offset must be applied, false otherwise.
16480     *
16481     * @see #getLeftPaddingOffset()
16482     * @see #getRightPaddingOffset()
16483     * @see #getTopPaddingOffset()
16484     * @see #getBottomPaddingOffset()
16485     *
16486     * @since CURRENT
16487     */
16488    protected boolean isPaddingOffsetRequired() {
16489        return false;
16490    }
16491
16492    /**
16493     * Amount by which to extend the left fading region. Called only when
16494     * {@link #isPaddingOffsetRequired()} returns true.
16495     *
16496     * @return The left padding offset in pixels.
16497     *
16498     * @see #isPaddingOffsetRequired()
16499     *
16500     * @since CURRENT
16501     */
16502    protected int getLeftPaddingOffset() {
16503        return 0;
16504    }
16505
16506    /**
16507     * Amount by which to extend the right fading region. Called only when
16508     * {@link #isPaddingOffsetRequired()} returns true.
16509     *
16510     * @return The right padding offset in pixels.
16511     *
16512     * @see #isPaddingOffsetRequired()
16513     *
16514     * @since CURRENT
16515     */
16516    protected int getRightPaddingOffset() {
16517        return 0;
16518    }
16519
16520    /**
16521     * Amount by which to extend the top fading region. Called only when
16522     * {@link #isPaddingOffsetRequired()} returns true.
16523     *
16524     * @return The top padding offset in pixels.
16525     *
16526     * @see #isPaddingOffsetRequired()
16527     *
16528     * @since CURRENT
16529     */
16530    protected int getTopPaddingOffset() {
16531        return 0;
16532    }
16533
16534    /**
16535     * Amount by which to extend the bottom fading region. Called only when
16536     * {@link #isPaddingOffsetRequired()} returns true.
16537     *
16538     * @return The bottom padding offset in pixels.
16539     *
16540     * @see #isPaddingOffsetRequired()
16541     *
16542     * @since CURRENT
16543     */
16544    protected int getBottomPaddingOffset() {
16545        return 0;
16546    }
16547
16548    /**
16549     * @hide
16550     * @param offsetRequired
16551     */
16552    protected int getFadeTop(boolean offsetRequired) {
16553        int top = mPaddingTop;
16554        if (offsetRequired) top += getTopPaddingOffset();
16555        return top;
16556    }
16557
16558    /**
16559     * @hide
16560     * @param offsetRequired
16561     */
16562    protected int getFadeHeight(boolean offsetRequired) {
16563        int padding = mPaddingTop;
16564        if (offsetRequired) padding += getTopPaddingOffset();
16565        return mBottom - mTop - mPaddingBottom - padding;
16566    }
16567
16568    /**
16569     * <p>Indicates whether this view is attached to a hardware accelerated
16570     * window or not.</p>
16571     *
16572     * <p>Even if this method returns true, it does not mean that every call
16573     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16574     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16575     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16576     * window is hardware accelerated,
16577     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16578     * return false, and this method will return true.</p>
16579     *
16580     * @return True if the view is attached to a window and the window is
16581     *         hardware accelerated; false in any other case.
16582     */
16583    @ViewDebug.ExportedProperty(category = "drawing")
16584    public boolean isHardwareAccelerated() {
16585        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16586    }
16587
16588    /**
16589     * Sets a rectangular area on this view to which the view will be clipped
16590     * when it is drawn. Setting the value to null will remove the clip bounds
16591     * and the view will draw normally, using its full bounds.
16592     *
16593     * @param clipBounds The rectangular area, in the local coordinates of
16594     * this view, to which future drawing operations will be clipped.
16595     */
16596    public void setClipBounds(Rect clipBounds) {
16597        if (clipBounds == mClipBounds
16598                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16599            return;
16600        }
16601        if (clipBounds != null) {
16602            if (mClipBounds == null) {
16603                mClipBounds = new Rect(clipBounds);
16604            } else {
16605                mClipBounds.set(clipBounds);
16606            }
16607        } else {
16608            mClipBounds = null;
16609        }
16610        mRenderNode.setClipBounds(mClipBounds);
16611        invalidateViewProperty(false, false);
16612    }
16613
16614    /**
16615     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16616     *
16617     * @return A copy of the current clip bounds if clip bounds are set,
16618     * otherwise null.
16619     */
16620    public Rect getClipBounds() {
16621        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16622    }
16623
16624
16625    /**
16626     * Populates an output rectangle with the clip bounds of the view,
16627     * returning {@code true} if successful or {@code false} if the view's
16628     * clip bounds are {@code null}.
16629     *
16630     * @param outRect rectangle in which to place the clip bounds of the view
16631     * @return {@code true} if successful or {@code false} if the view's
16632     *         clip bounds are {@code null}
16633     */
16634    public boolean getClipBounds(Rect outRect) {
16635        if (mClipBounds != null) {
16636            outRect.set(mClipBounds);
16637            return true;
16638        }
16639        return false;
16640    }
16641
16642    /**
16643     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16644     * case of an active Animation being run on the view.
16645     */
16646    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16647            Animation a, boolean scalingRequired) {
16648        Transformation invalidationTransform;
16649        final int flags = parent.mGroupFlags;
16650        final boolean initialized = a.isInitialized();
16651        if (!initialized) {
16652            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16653            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16654            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16655            onAnimationStart();
16656        }
16657
16658        final Transformation t = parent.getChildTransformation();
16659        boolean more = a.getTransformation(drawingTime, t, 1f);
16660        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16661            if (parent.mInvalidationTransformation == null) {
16662                parent.mInvalidationTransformation = new Transformation();
16663            }
16664            invalidationTransform = parent.mInvalidationTransformation;
16665            a.getTransformation(drawingTime, invalidationTransform, 1f);
16666        } else {
16667            invalidationTransform = t;
16668        }
16669
16670        if (more) {
16671            if (!a.willChangeBounds()) {
16672                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16673                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16674                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16675                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16676                    // The child need to draw an animation, potentially offscreen, so
16677                    // make sure we do not cancel invalidate requests
16678                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16679                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16680                }
16681            } else {
16682                if (parent.mInvalidateRegion == null) {
16683                    parent.mInvalidateRegion = new RectF();
16684                }
16685                final RectF region = parent.mInvalidateRegion;
16686                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16687                        invalidationTransform);
16688
16689                // The child need to draw an animation, potentially offscreen, so
16690                // make sure we do not cancel invalidate requests
16691                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16692
16693                final int left = mLeft + (int) region.left;
16694                final int top = mTop + (int) region.top;
16695                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16696                        top + (int) (region.height() + .5f));
16697            }
16698        }
16699        return more;
16700    }
16701
16702    /**
16703     * This method is called by getDisplayList() when a display list is recorded for a View.
16704     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16705     */
16706    void setDisplayListProperties(RenderNode renderNode) {
16707        if (renderNode != null) {
16708            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16709            renderNode.setClipToBounds(mParent instanceof ViewGroup
16710                    && ((ViewGroup) mParent).getClipChildren());
16711
16712            float alpha = 1;
16713            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16714                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16715                ViewGroup parentVG = (ViewGroup) mParent;
16716                final Transformation t = parentVG.getChildTransformation();
16717                if (parentVG.getChildStaticTransformation(this, t)) {
16718                    final int transformType = t.getTransformationType();
16719                    if (transformType != Transformation.TYPE_IDENTITY) {
16720                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16721                            alpha = t.getAlpha();
16722                        }
16723                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16724                            renderNode.setStaticMatrix(t.getMatrix());
16725                        }
16726                    }
16727                }
16728            }
16729            if (mTransformationInfo != null) {
16730                alpha *= getFinalAlpha();
16731                if (alpha < 1) {
16732                    final int multipliedAlpha = (int) (255 * alpha);
16733                    if (onSetAlpha(multipliedAlpha)) {
16734                        alpha = 1;
16735                    }
16736                }
16737                renderNode.setAlpha(alpha);
16738            } else if (alpha < 1) {
16739                renderNode.setAlpha(alpha);
16740            }
16741        }
16742    }
16743
16744    /**
16745     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16746     *
16747     * This is where the View specializes rendering behavior based on layer type,
16748     * and hardware acceleration.
16749     */
16750    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16751        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16752        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16753         *
16754         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16755         * HW accelerated, it can't handle drawing RenderNodes.
16756         */
16757        boolean drawingWithRenderNode = mAttachInfo != null
16758                && mAttachInfo.mHardwareAccelerated
16759                && hardwareAcceleratedCanvas;
16760
16761        boolean more = false;
16762        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16763        final int parentFlags = parent.mGroupFlags;
16764
16765        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16766            parent.getChildTransformation().clear();
16767            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16768        }
16769
16770        Transformation transformToApply = null;
16771        boolean concatMatrix = false;
16772        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16773        final Animation a = getAnimation();
16774        if (a != null) {
16775            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16776            concatMatrix = a.willChangeTransformationMatrix();
16777            if (concatMatrix) {
16778                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16779            }
16780            transformToApply = parent.getChildTransformation();
16781        } else {
16782            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16783                // No longer animating: clear out old animation matrix
16784                mRenderNode.setAnimationMatrix(null);
16785                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16786            }
16787            if (!drawingWithRenderNode
16788                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16789                final Transformation t = parent.getChildTransformation();
16790                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16791                if (hasTransform) {
16792                    final int transformType = t.getTransformationType();
16793                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16794                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16795                }
16796            }
16797        }
16798
16799        concatMatrix |= !childHasIdentityMatrix;
16800
16801        // Sets the flag as early as possible to allow draw() implementations
16802        // to call invalidate() successfully when doing animations
16803        mPrivateFlags |= PFLAG_DRAWN;
16804
16805        if (!concatMatrix &&
16806                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16807                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16808                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16809                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16810            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16811            return more;
16812        }
16813        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16814
16815        if (hardwareAcceleratedCanvas) {
16816            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16817            // retain the flag's value temporarily in the mRecreateDisplayList flag
16818            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16819            mPrivateFlags &= ~PFLAG_INVALIDATED;
16820        }
16821
16822        RenderNode renderNode = null;
16823        Bitmap cache = null;
16824        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16825        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16826             if (layerType != LAYER_TYPE_NONE) {
16827                 // If not drawing with RenderNode, treat HW layers as SW
16828                 layerType = LAYER_TYPE_SOFTWARE;
16829                 buildDrawingCache(true);
16830            }
16831            cache = getDrawingCache(true);
16832        }
16833
16834        if (drawingWithRenderNode) {
16835            // Delay getting the display list until animation-driven alpha values are
16836            // set up and possibly passed on to the view
16837            renderNode = updateDisplayListIfDirty();
16838            if (!renderNode.isValid()) {
16839                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16840                // to getDisplayList(), the display list will be marked invalid and we should not
16841                // try to use it again.
16842                renderNode = null;
16843                drawingWithRenderNode = false;
16844            }
16845        }
16846
16847        int sx = 0;
16848        int sy = 0;
16849        if (!drawingWithRenderNode) {
16850            computeScroll();
16851            sx = mScrollX;
16852            sy = mScrollY;
16853        }
16854
16855        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16856        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16857
16858        int restoreTo = -1;
16859        if (!drawingWithRenderNode || transformToApply != null) {
16860            restoreTo = canvas.save();
16861        }
16862        if (offsetForScroll) {
16863            canvas.translate(mLeft - sx, mTop - sy);
16864        } else {
16865            if (!drawingWithRenderNode) {
16866                canvas.translate(mLeft, mTop);
16867            }
16868            if (scalingRequired) {
16869                if (drawingWithRenderNode) {
16870                    // TODO: Might not need this if we put everything inside the DL
16871                    restoreTo = canvas.save();
16872                }
16873                // mAttachInfo cannot be null, otherwise scalingRequired == false
16874                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16875                canvas.scale(scale, scale);
16876            }
16877        }
16878
16879        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16880        if (transformToApply != null
16881                || alpha < 1
16882                || !hasIdentityMatrix()
16883                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16884            if (transformToApply != null || !childHasIdentityMatrix) {
16885                int transX = 0;
16886                int transY = 0;
16887
16888                if (offsetForScroll) {
16889                    transX = -sx;
16890                    transY = -sy;
16891                }
16892
16893                if (transformToApply != null) {
16894                    if (concatMatrix) {
16895                        if (drawingWithRenderNode) {
16896                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16897                        } else {
16898                            // Undo the scroll translation, apply the transformation matrix,
16899                            // then redo the scroll translate to get the correct result.
16900                            canvas.translate(-transX, -transY);
16901                            canvas.concat(transformToApply.getMatrix());
16902                            canvas.translate(transX, transY);
16903                        }
16904                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16905                    }
16906
16907                    float transformAlpha = transformToApply.getAlpha();
16908                    if (transformAlpha < 1) {
16909                        alpha *= transformAlpha;
16910                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16911                    }
16912                }
16913
16914                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16915                    canvas.translate(-transX, -transY);
16916                    canvas.concat(getMatrix());
16917                    canvas.translate(transX, transY);
16918                }
16919            }
16920
16921            // Deal with alpha if it is or used to be <1
16922            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16923                if (alpha < 1) {
16924                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16925                } else {
16926                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16927                }
16928                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16929                if (!drawingWithDrawingCache) {
16930                    final int multipliedAlpha = (int) (255 * alpha);
16931                    if (!onSetAlpha(multipliedAlpha)) {
16932                        if (drawingWithRenderNode) {
16933                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16934                        } else if (layerType == LAYER_TYPE_NONE) {
16935                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16936                                    multipliedAlpha);
16937                        }
16938                    } else {
16939                        // Alpha is handled by the child directly, clobber the layer's alpha
16940                        mPrivateFlags |= PFLAG_ALPHA_SET;
16941                    }
16942                }
16943            }
16944        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16945            onSetAlpha(255);
16946            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16947        }
16948
16949        if (!drawingWithRenderNode) {
16950            // apply clips directly, since RenderNode won't do it for this draw
16951            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16952                if (offsetForScroll) {
16953                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16954                } else {
16955                    if (!scalingRequired || cache == null) {
16956                        canvas.clipRect(0, 0, getWidth(), getHeight());
16957                    } else {
16958                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16959                    }
16960                }
16961            }
16962
16963            if (mClipBounds != null) {
16964                // clip bounds ignore scroll
16965                canvas.clipRect(mClipBounds);
16966            }
16967        }
16968
16969        if (!drawingWithDrawingCache) {
16970            if (drawingWithRenderNode) {
16971                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16972                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16973            } else {
16974                // Fast path for layouts with no backgrounds
16975                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16976                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16977                    dispatchDraw(canvas);
16978                } else {
16979                    draw(canvas);
16980                }
16981            }
16982        } else if (cache != null) {
16983            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16984            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
16985                // no layer paint, use temporary paint to draw bitmap
16986                Paint cachePaint = parent.mCachePaint;
16987                if (cachePaint == null) {
16988                    cachePaint = new Paint();
16989                    cachePaint.setDither(false);
16990                    parent.mCachePaint = cachePaint;
16991                }
16992                cachePaint.setAlpha((int) (alpha * 255));
16993                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16994            } else {
16995                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16996                int layerPaintAlpha = mLayerPaint.getAlpha();
16997                if (alpha < 1) {
16998                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16999                }
17000                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17001                if (alpha < 1) {
17002                    mLayerPaint.setAlpha(layerPaintAlpha);
17003                }
17004            }
17005        }
17006
17007        if (restoreTo >= 0) {
17008            canvas.restoreToCount(restoreTo);
17009        }
17010
17011        if (a != null && !more) {
17012            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17013                onSetAlpha(255);
17014            }
17015            parent.finishAnimatingView(this, a);
17016        }
17017
17018        if (more && hardwareAcceleratedCanvas) {
17019            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17020                // alpha animations should cause the child to recreate its display list
17021                invalidate(true);
17022            }
17023        }
17024
17025        mRecreateDisplayList = false;
17026
17027        return more;
17028    }
17029
17030    /**
17031     * Manually render this view (and all of its children) to the given Canvas.
17032     * The view must have already done a full layout before this function is
17033     * called.  When implementing a view, implement
17034     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17035     * If you do need to override this method, call the superclass version.
17036     *
17037     * @param canvas The Canvas to which the View is rendered.
17038     */
17039    @CallSuper
17040    public void draw(Canvas canvas) {
17041        final int privateFlags = mPrivateFlags;
17042        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17043                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17044        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17045
17046        /*
17047         * Draw traversal performs several drawing steps which must be executed
17048         * in the appropriate order:
17049         *
17050         *      1. Draw the background
17051         *      2. If necessary, save the canvas' layers to prepare for fading
17052         *      3. Draw view's content
17053         *      4. Draw children
17054         *      5. If necessary, draw the fading edges and restore layers
17055         *      6. Draw decorations (scrollbars for instance)
17056         */
17057
17058        // Step 1, draw the background, if needed
17059        int saveCount;
17060
17061        if (!dirtyOpaque) {
17062            drawBackground(canvas);
17063        }
17064
17065        // skip step 2 & 5 if possible (common case)
17066        final int viewFlags = mViewFlags;
17067        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17068        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17069        if (!verticalEdges && !horizontalEdges) {
17070            // Step 3, draw the content
17071            if (!dirtyOpaque) onDraw(canvas);
17072
17073            // Step 4, draw the children
17074            dispatchDraw(canvas);
17075
17076            // Overlay is part of the content and draws beneath Foreground
17077            if (mOverlay != null && !mOverlay.isEmpty()) {
17078                mOverlay.getOverlayView().dispatchDraw(canvas);
17079            }
17080
17081            // Step 6, draw decorations (foreground, scrollbars)
17082            onDrawForeground(canvas);
17083
17084            // we're done...
17085            return;
17086        }
17087
17088        /*
17089         * Here we do the full fledged routine...
17090         * (this is an uncommon case where speed matters less,
17091         * this is why we repeat some of the tests that have been
17092         * done above)
17093         */
17094
17095        boolean drawTop = false;
17096        boolean drawBottom = false;
17097        boolean drawLeft = false;
17098        boolean drawRight = false;
17099
17100        float topFadeStrength = 0.0f;
17101        float bottomFadeStrength = 0.0f;
17102        float leftFadeStrength = 0.0f;
17103        float rightFadeStrength = 0.0f;
17104
17105        // Step 2, save the canvas' layers
17106        int paddingLeft = mPaddingLeft;
17107
17108        final boolean offsetRequired = isPaddingOffsetRequired();
17109        if (offsetRequired) {
17110            paddingLeft += getLeftPaddingOffset();
17111        }
17112
17113        int left = mScrollX + paddingLeft;
17114        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17115        int top = mScrollY + getFadeTop(offsetRequired);
17116        int bottom = top + getFadeHeight(offsetRequired);
17117
17118        if (offsetRequired) {
17119            right += getRightPaddingOffset();
17120            bottom += getBottomPaddingOffset();
17121        }
17122
17123        final ScrollabilityCache scrollabilityCache = mScrollCache;
17124        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17125        int length = (int) fadeHeight;
17126
17127        // clip the fade length if top and bottom fades overlap
17128        // overlapping fades produce odd-looking artifacts
17129        if (verticalEdges && (top + length > bottom - length)) {
17130            length = (bottom - top) / 2;
17131        }
17132
17133        // also clip horizontal fades if necessary
17134        if (horizontalEdges && (left + length > right - length)) {
17135            length = (right - left) / 2;
17136        }
17137
17138        if (verticalEdges) {
17139            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17140            drawTop = topFadeStrength * fadeHeight > 1.0f;
17141            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17142            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17143        }
17144
17145        if (horizontalEdges) {
17146            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17147            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17148            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17149            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17150        }
17151
17152        saveCount = canvas.getSaveCount();
17153
17154        int solidColor = getSolidColor();
17155        if (solidColor == 0) {
17156            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17157
17158            if (drawTop) {
17159                canvas.saveLayer(left, top, right, top + length, null, flags);
17160            }
17161
17162            if (drawBottom) {
17163                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17164            }
17165
17166            if (drawLeft) {
17167                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17168            }
17169
17170            if (drawRight) {
17171                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17172            }
17173        } else {
17174            scrollabilityCache.setFadeColor(solidColor);
17175        }
17176
17177        // Step 3, draw the content
17178        if (!dirtyOpaque) onDraw(canvas);
17179
17180        // Step 4, draw the children
17181        dispatchDraw(canvas);
17182
17183        // Step 5, draw the fade effect and restore layers
17184        final Paint p = scrollabilityCache.paint;
17185        final Matrix matrix = scrollabilityCache.matrix;
17186        final Shader fade = scrollabilityCache.shader;
17187
17188        if (drawTop) {
17189            matrix.setScale(1, fadeHeight * topFadeStrength);
17190            matrix.postTranslate(left, top);
17191            fade.setLocalMatrix(matrix);
17192            p.setShader(fade);
17193            canvas.drawRect(left, top, right, top + length, p);
17194        }
17195
17196        if (drawBottom) {
17197            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17198            matrix.postRotate(180);
17199            matrix.postTranslate(left, bottom);
17200            fade.setLocalMatrix(matrix);
17201            p.setShader(fade);
17202            canvas.drawRect(left, bottom - length, right, bottom, p);
17203        }
17204
17205        if (drawLeft) {
17206            matrix.setScale(1, fadeHeight * leftFadeStrength);
17207            matrix.postRotate(-90);
17208            matrix.postTranslate(left, top);
17209            fade.setLocalMatrix(matrix);
17210            p.setShader(fade);
17211            canvas.drawRect(left, top, left + length, bottom, p);
17212        }
17213
17214        if (drawRight) {
17215            matrix.setScale(1, fadeHeight * rightFadeStrength);
17216            matrix.postRotate(90);
17217            matrix.postTranslate(right, top);
17218            fade.setLocalMatrix(matrix);
17219            p.setShader(fade);
17220            canvas.drawRect(right - length, top, right, bottom, p);
17221        }
17222
17223        canvas.restoreToCount(saveCount);
17224
17225        // Overlay is part of the content and draws beneath Foreground
17226        if (mOverlay != null && !mOverlay.isEmpty()) {
17227            mOverlay.getOverlayView().dispatchDraw(canvas);
17228        }
17229
17230        // Step 6, draw decorations (foreground, scrollbars)
17231        onDrawForeground(canvas);
17232    }
17233
17234    /**
17235     * Draws the background onto the specified canvas.
17236     *
17237     * @param canvas Canvas on which to draw the background
17238     */
17239    private void drawBackground(Canvas canvas) {
17240        final Drawable background = mBackground;
17241        if (background == null) {
17242            return;
17243        }
17244
17245        setBackgroundBounds();
17246
17247        // Attempt to use a display list if requested.
17248        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17249                && mAttachInfo.mHardwareRenderer != null) {
17250            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17251
17252            final RenderNode renderNode = mBackgroundRenderNode;
17253            if (renderNode != null && renderNode.isValid()) {
17254                setBackgroundRenderNodeProperties(renderNode);
17255                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17256                return;
17257            }
17258        }
17259
17260        final int scrollX = mScrollX;
17261        final int scrollY = mScrollY;
17262        if ((scrollX | scrollY) == 0) {
17263            background.draw(canvas);
17264        } else {
17265            canvas.translate(scrollX, scrollY);
17266            background.draw(canvas);
17267            canvas.translate(-scrollX, -scrollY);
17268        }
17269    }
17270
17271    /**
17272     * Sets the correct background bounds and rebuilds the outline, if needed.
17273     * <p/>
17274     * This is called by LayoutLib.
17275     */
17276    void setBackgroundBounds() {
17277        if (mBackgroundSizeChanged && mBackground != null) {
17278            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17279            mBackgroundSizeChanged = false;
17280            rebuildOutline();
17281        }
17282    }
17283
17284    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17285        renderNode.setTranslationX(mScrollX);
17286        renderNode.setTranslationY(mScrollY);
17287    }
17288
17289    /**
17290     * Creates a new display list or updates the existing display list for the
17291     * specified Drawable.
17292     *
17293     * @param drawable Drawable for which to create a display list
17294     * @param renderNode Existing RenderNode, or {@code null}
17295     * @return A valid display list for the specified drawable
17296     */
17297    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17298        if (renderNode == null) {
17299            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17300        }
17301
17302        final Rect bounds = drawable.getBounds();
17303        final int width = bounds.width();
17304        final int height = bounds.height();
17305        final DisplayListCanvas canvas = renderNode.start(width, height);
17306
17307        // Reverse left/top translation done by drawable canvas, which will
17308        // instead be applied by rendernode's LTRB bounds below. This way, the
17309        // drawable's bounds match with its rendernode bounds and its content
17310        // will lie within those bounds in the rendernode tree.
17311        canvas.translate(-bounds.left, -bounds.top);
17312
17313        try {
17314            drawable.draw(canvas);
17315        } finally {
17316            renderNode.end(canvas);
17317        }
17318
17319        // Set up drawable properties that are view-independent.
17320        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17321        renderNode.setProjectBackwards(drawable.isProjected());
17322        renderNode.setProjectionReceiver(true);
17323        renderNode.setClipToBounds(false);
17324        return renderNode;
17325    }
17326
17327    /**
17328     * Returns the overlay for this view, creating it if it does not yet exist.
17329     * Adding drawables to the overlay will cause them to be displayed whenever
17330     * the view itself is redrawn. Objects in the overlay should be actively
17331     * managed: remove them when they should not be displayed anymore. The
17332     * overlay will always have the same size as its host view.
17333     *
17334     * <p>Note: Overlays do not currently work correctly with {@link
17335     * SurfaceView} or {@link TextureView}; contents in overlays for these
17336     * types of views may not display correctly.</p>
17337     *
17338     * @return The ViewOverlay object for this view.
17339     * @see ViewOverlay
17340     */
17341    public ViewOverlay getOverlay() {
17342        if (mOverlay == null) {
17343            mOverlay = new ViewOverlay(mContext, this);
17344        }
17345        return mOverlay;
17346    }
17347
17348    /**
17349     * Override this if your view is known to always be drawn on top of a solid color background,
17350     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17351     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17352     * should be set to 0xFF.
17353     *
17354     * @see #setVerticalFadingEdgeEnabled(boolean)
17355     * @see #setHorizontalFadingEdgeEnabled(boolean)
17356     *
17357     * @return The known solid color background for this view, or 0 if the color may vary
17358     */
17359    @ViewDebug.ExportedProperty(category = "drawing")
17360    @ColorInt
17361    public int getSolidColor() {
17362        return 0;
17363    }
17364
17365    /**
17366     * Build a human readable string representation of the specified view flags.
17367     *
17368     * @param flags the view flags to convert to a string
17369     * @return a String representing the supplied flags
17370     */
17371    private static String printFlags(int flags) {
17372        String output = "";
17373        int numFlags = 0;
17374        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17375            output += "TAKES_FOCUS";
17376            numFlags++;
17377        }
17378
17379        switch (flags & VISIBILITY_MASK) {
17380        case INVISIBLE:
17381            if (numFlags > 0) {
17382                output += " ";
17383            }
17384            output += "INVISIBLE";
17385            // USELESS HERE numFlags++;
17386            break;
17387        case GONE:
17388            if (numFlags > 0) {
17389                output += " ";
17390            }
17391            output += "GONE";
17392            // USELESS HERE numFlags++;
17393            break;
17394        default:
17395            break;
17396        }
17397        return output;
17398    }
17399
17400    /**
17401     * Build a human readable string representation of the specified private
17402     * view flags.
17403     *
17404     * @param privateFlags the private view flags to convert to a string
17405     * @return a String representing the supplied flags
17406     */
17407    private static String printPrivateFlags(int privateFlags) {
17408        String output = "";
17409        int numFlags = 0;
17410
17411        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17412            output += "WANTS_FOCUS";
17413            numFlags++;
17414        }
17415
17416        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17417            if (numFlags > 0) {
17418                output += " ";
17419            }
17420            output += "FOCUSED";
17421            numFlags++;
17422        }
17423
17424        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17425            if (numFlags > 0) {
17426                output += " ";
17427            }
17428            output += "SELECTED";
17429            numFlags++;
17430        }
17431
17432        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17433            if (numFlags > 0) {
17434                output += " ";
17435            }
17436            output += "IS_ROOT_NAMESPACE";
17437            numFlags++;
17438        }
17439
17440        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17441            if (numFlags > 0) {
17442                output += " ";
17443            }
17444            output += "HAS_BOUNDS";
17445            numFlags++;
17446        }
17447
17448        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17449            if (numFlags > 0) {
17450                output += " ";
17451            }
17452            output += "DRAWN";
17453            // USELESS HERE numFlags++;
17454        }
17455        return output;
17456    }
17457
17458    /**
17459     * <p>Indicates whether or not this view's layout will be requested during
17460     * the next hierarchy layout pass.</p>
17461     *
17462     * @return true if the layout will be forced during next layout pass
17463     */
17464    public boolean isLayoutRequested() {
17465        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17466    }
17467
17468    /**
17469     * Return true if o is a ViewGroup that is laying out using optical bounds.
17470     * @hide
17471     */
17472    public static boolean isLayoutModeOptical(Object o) {
17473        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17474    }
17475
17476    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17477        Insets parentInsets = mParent instanceof View ?
17478                ((View) mParent).getOpticalInsets() : Insets.NONE;
17479        Insets childInsets = getOpticalInsets();
17480        return setFrame(
17481                left   + parentInsets.left - childInsets.left,
17482                top    + parentInsets.top  - childInsets.top,
17483                right  + parentInsets.left + childInsets.right,
17484                bottom + parentInsets.top  + childInsets.bottom);
17485    }
17486
17487    /**
17488     * Assign a size and position to a view and all of its
17489     * descendants
17490     *
17491     * <p>This is the second phase of the layout mechanism.
17492     * (The first is measuring). In this phase, each parent calls
17493     * layout on all of its children to position them.
17494     * This is typically done using the child measurements
17495     * that were stored in the measure pass().</p>
17496     *
17497     * <p>Derived classes should not override this method.
17498     * Derived classes with children should override
17499     * onLayout. In that method, they should
17500     * call layout on each of their children.</p>
17501     *
17502     * @param l Left position, relative to parent
17503     * @param t Top position, relative to parent
17504     * @param r Right position, relative to parent
17505     * @param b Bottom position, relative to parent
17506     */
17507    @SuppressWarnings({"unchecked"})
17508    public void layout(int l, int t, int r, int b) {
17509        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17510            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17511            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17512        }
17513
17514        int oldL = mLeft;
17515        int oldT = mTop;
17516        int oldB = mBottom;
17517        int oldR = mRight;
17518
17519        boolean changed = isLayoutModeOptical(mParent) ?
17520                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17521
17522        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17523            onLayout(changed, l, t, r, b);
17524            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17525
17526            ListenerInfo li = mListenerInfo;
17527            if (li != null && li.mOnLayoutChangeListeners != null) {
17528                ArrayList<OnLayoutChangeListener> listenersCopy =
17529                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17530                int numListeners = listenersCopy.size();
17531                for (int i = 0; i < numListeners; ++i) {
17532                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17533                }
17534            }
17535        }
17536
17537        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17538        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17539    }
17540
17541    /**
17542     * Called from layout when this view should
17543     * assign a size and position to each of its children.
17544     *
17545     * Derived classes with children should override
17546     * this method and call layout on each of
17547     * their children.
17548     * @param changed This is a new size or position for this view
17549     * @param left Left position, relative to parent
17550     * @param top Top position, relative to parent
17551     * @param right Right position, relative to parent
17552     * @param bottom Bottom position, relative to parent
17553     */
17554    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17555    }
17556
17557    /**
17558     * Assign a size and position to this view.
17559     *
17560     * This is called from layout.
17561     *
17562     * @param left Left position, relative to parent
17563     * @param top Top position, relative to parent
17564     * @param right Right position, relative to parent
17565     * @param bottom Bottom position, relative to parent
17566     * @return true if the new size and position are different than the
17567     *         previous ones
17568     * {@hide}
17569     */
17570    protected boolean setFrame(int left, int top, int right, int bottom) {
17571        boolean changed = false;
17572
17573        if (DBG) {
17574            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17575                    + right + "," + bottom + ")");
17576        }
17577
17578        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17579            changed = true;
17580
17581            // Remember our drawn bit
17582            int drawn = mPrivateFlags & PFLAG_DRAWN;
17583
17584            int oldWidth = mRight - mLeft;
17585            int oldHeight = mBottom - mTop;
17586            int newWidth = right - left;
17587            int newHeight = bottom - top;
17588            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17589
17590            // Invalidate our old position
17591            invalidate(sizeChanged);
17592
17593            mLeft = left;
17594            mTop = top;
17595            mRight = right;
17596            mBottom = bottom;
17597            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17598
17599            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17600
17601
17602            if (sizeChanged) {
17603                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17604            }
17605
17606            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17607                // If we are visible, force the DRAWN bit to on so that
17608                // this invalidate will go through (at least to our parent).
17609                // This is because someone may have invalidated this view
17610                // before this call to setFrame came in, thereby clearing
17611                // the DRAWN bit.
17612                mPrivateFlags |= PFLAG_DRAWN;
17613                invalidate(sizeChanged);
17614                // parent display list may need to be recreated based on a change in the bounds
17615                // of any child
17616                invalidateParentCaches();
17617            }
17618
17619            // Reset drawn bit to original value (invalidate turns it off)
17620            mPrivateFlags |= drawn;
17621
17622            mBackgroundSizeChanged = true;
17623            if (mForegroundInfo != null) {
17624                mForegroundInfo.mBoundsChanged = true;
17625            }
17626
17627            notifySubtreeAccessibilityStateChangedIfNeeded();
17628        }
17629        return changed;
17630    }
17631
17632    /**
17633     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17634     * @hide
17635     */
17636    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17637        setFrame(left, top, right, bottom);
17638    }
17639
17640    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17641        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17642        if (mOverlay != null) {
17643            mOverlay.getOverlayView().setRight(newWidth);
17644            mOverlay.getOverlayView().setBottom(newHeight);
17645        }
17646        rebuildOutline();
17647    }
17648
17649    /**
17650     * Finalize inflating a view from XML.  This is called as the last phase
17651     * of inflation, after all child views have been added.
17652     *
17653     * <p>Even if the subclass overrides onFinishInflate, they should always be
17654     * sure to call the super method, so that we get called.
17655     */
17656    @CallSuper
17657    protected void onFinishInflate() {
17658    }
17659
17660    /**
17661     * Returns the resources associated with this view.
17662     *
17663     * @return Resources object.
17664     */
17665    public Resources getResources() {
17666        return mResources;
17667    }
17668
17669    /**
17670     * Invalidates the specified Drawable.
17671     *
17672     * @param drawable the drawable to invalidate
17673     */
17674    @Override
17675    public void invalidateDrawable(@NonNull Drawable drawable) {
17676        if (verifyDrawable(drawable)) {
17677            final Rect dirty = drawable.getDirtyBounds();
17678            final int scrollX = mScrollX;
17679            final int scrollY = mScrollY;
17680
17681            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17682                    dirty.right + scrollX, dirty.bottom + scrollY);
17683            rebuildOutline();
17684        }
17685    }
17686
17687    /**
17688     * Schedules an action on a drawable to occur at a specified time.
17689     *
17690     * @param who the recipient of the action
17691     * @param what the action to run on the drawable
17692     * @param when the time at which the action must occur. Uses the
17693     *        {@link SystemClock#uptimeMillis} timebase.
17694     */
17695    @Override
17696    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17697        if (verifyDrawable(who) && what != null) {
17698            final long delay = when - SystemClock.uptimeMillis();
17699            if (mAttachInfo != null) {
17700                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17701                        Choreographer.CALLBACK_ANIMATION, what, who,
17702                        Choreographer.subtractFrameDelay(delay));
17703            } else {
17704                // Postpone the runnable until we know
17705                // on which thread it needs to run.
17706                getRunQueue().postDelayed(what, delay);
17707            }
17708        }
17709    }
17710
17711    /**
17712     * Cancels a scheduled action on a drawable.
17713     *
17714     * @param who the recipient of the action
17715     * @param what the action to cancel
17716     */
17717    @Override
17718    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17719        if (verifyDrawable(who) && what != null) {
17720            if (mAttachInfo != null) {
17721                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17722                        Choreographer.CALLBACK_ANIMATION, what, who);
17723            }
17724            getRunQueue().removeCallbacks(what);
17725        }
17726    }
17727
17728    /**
17729     * Unschedule any events associated with the given Drawable.  This can be
17730     * used when selecting a new Drawable into a view, so that the previous
17731     * one is completely unscheduled.
17732     *
17733     * @param who The Drawable to unschedule.
17734     *
17735     * @see #drawableStateChanged
17736     */
17737    public void unscheduleDrawable(Drawable who) {
17738        if (mAttachInfo != null && who != null) {
17739            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17740                    Choreographer.CALLBACK_ANIMATION, null, who);
17741        }
17742    }
17743
17744    /**
17745     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17746     * that the View directionality can and will be resolved before its Drawables.
17747     *
17748     * Will call {@link View#onResolveDrawables} when resolution is done.
17749     *
17750     * @hide
17751     */
17752    protected void resolveDrawables() {
17753        // Drawables resolution may need to happen before resolving the layout direction (which is
17754        // done only during the measure() call).
17755        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17756        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17757        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17758        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17759        // direction to be resolved as its resolved value will be the same as its raw value.
17760        if (!isLayoutDirectionResolved() &&
17761                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17762            return;
17763        }
17764
17765        final int layoutDirection = isLayoutDirectionResolved() ?
17766                getLayoutDirection() : getRawLayoutDirection();
17767
17768        if (mBackground != null) {
17769            mBackground.setLayoutDirection(layoutDirection);
17770        }
17771        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17772            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17773        }
17774        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17775        onResolveDrawables(layoutDirection);
17776    }
17777
17778    boolean areDrawablesResolved() {
17779        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17780    }
17781
17782    /**
17783     * Called when layout direction has been resolved.
17784     *
17785     * The default implementation does nothing.
17786     *
17787     * @param layoutDirection The resolved layout direction.
17788     *
17789     * @see #LAYOUT_DIRECTION_LTR
17790     * @see #LAYOUT_DIRECTION_RTL
17791     *
17792     * @hide
17793     */
17794    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17795    }
17796
17797    /**
17798     * @hide
17799     */
17800    protected void resetResolvedDrawables() {
17801        resetResolvedDrawablesInternal();
17802    }
17803
17804    void resetResolvedDrawablesInternal() {
17805        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17806    }
17807
17808    /**
17809     * If your view subclass is displaying its own Drawable objects, it should
17810     * override this function and return true for any Drawable it is
17811     * displaying.  This allows animations for those drawables to be
17812     * scheduled.
17813     *
17814     * <p>Be sure to call through to the super class when overriding this
17815     * function.
17816     *
17817     * @param who The Drawable to verify.  Return true if it is one you are
17818     *            displaying, else return the result of calling through to the
17819     *            super class.
17820     *
17821     * @return boolean If true than the Drawable is being displayed in the
17822     *         view; else false and it is not allowed to animate.
17823     *
17824     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17825     * @see #drawableStateChanged()
17826     */
17827    @CallSuper
17828    protected boolean verifyDrawable(@NonNull Drawable who) {
17829        // Avoid verifying the scroll bar drawable so that we don't end up in
17830        // an invalidation loop. This effectively prevents the scroll bar
17831        // drawable from triggering invalidations and scheduling runnables.
17832        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17833    }
17834
17835    /**
17836     * This function is called whenever the state of the view changes in such
17837     * a way that it impacts the state of drawables being shown.
17838     * <p>
17839     * If the View has a StateListAnimator, it will also be called to run necessary state
17840     * change animations.
17841     * <p>
17842     * Be sure to call through to the superclass when overriding this function.
17843     *
17844     * @see Drawable#setState(int[])
17845     */
17846    @CallSuper
17847    protected void drawableStateChanged() {
17848        final int[] state = getDrawableState();
17849        boolean changed = false;
17850
17851        final Drawable bg = mBackground;
17852        if (bg != null && bg.isStateful()) {
17853            changed |= bg.setState(state);
17854        }
17855
17856        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17857        if (fg != null && fg.isStateful()) {
17858            changed |= fg.setState(state);
17859        }
17860
17861        if (mScrollCache != null) {
17862            final Drawable scrollBar = mScrollCache.scrollBar;
17863            if (scrollBar != null && scrollBar.isStateful()) {
17864                changed |= scrollBar.setState(state)
17865                        && mScrollCache.state != ScrollabilityCache.OFF;
17866            }
17867        }
17868
17869        if (mStateListAnimator != null) {
17870            mStateListAnimator.setState(state);
17871        }
17872
17873        if (changed) {
17874            invalidate();
17875        }
17876    }
17877
17878    /**
17879     * This function is called whenever the view hotspot changes and needs to
17880     * be propagated to drawables or child views managed by the view.
17881     * <p>
17882     * Dispatching to child views is handled by
17883     * {@link #dispatchDrawableHotspotChanged(float, float)}.
17884     * <p>
17885     * Be sure to call through to the superclass when overriding this function.
17886     *
17887     * @param x hotspot x coordinate
17888     * @param y hotspot y coordinate
17889     */
17890    @CallSuper
17891    public void drawableHotspotChanged(float x, float y) {
17892        if (mBackground != null) {
17893            mBackground.setHotspot(x, y);
17894        }
17895        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17896            mForegroundInfo.mDrawable.setHotspot(x, y);
17897        }
17898
17899        dispatchDrawableHotspotChanged(x, y);
17900    }
17901
17902    /**
17903     * Dispatches drawableHotspotChanged to all of this View's children.
17904     *
17905     * @param x hotspot x coordinate
17906     * @param y hotspot y coordinate
17907     * @see #drawableHotspotChanged(float, float)
17908     */
17909    public void dispatchDrawableHotspotChanged(float x, float y) {
17910    }
17911
17912    /**
17913     * Call this to force a view to update its drawable state. This will cause
17914     * drawableStateChanged to be called on this view. Views that are interested
17915     * in the new state should call getDrawableState.
17916     *
17917     * @see #drawableStateChanged
17918     * @see #getDrawableState
17919     */
17920    public void refreshDrawableState() {
17921        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17922        drawableStateChanged();
17923
17924        ViewParent parent = mParent;
17925        if (parent != null) {
17926            parent.childDrawableStateChanged(this);
17927        }
17928    }
17929
17930    /**
17931     * Return an array of resource IDs of the drawable states representing the
17932     * current state of the view.
17933     *
17934     * @return The current drawable state
17935     *
17936     * @see Drawable#setState(int[])
17937     * @see #drawableStateChanged()
17938     * @see #onCreateDrawableState(int)
17939     */
17940    public final int[] getDrawableState() {
17941        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17942            return mDrawableState;
17943        } else {
17944            mDrawableState = onCreateDrawableState(0);
17945            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17946            return mDrawableState;
17947        }
17948    }
17949
17950    /**
17951     * Generate the new {@link android.graphics.drawable.Drawable} state for
17952     * this view. This is called by the view
17953     * system when the cached Drawable state is determined to be invalid.  To
17954     * retrieve the current state, you should use {@link #getDrawableState}.
17955     *
17956     * @param extraSpace if non-zero, this is the number of extra entries you
17957     * would like in the returned array in which you can place your own
17958     * states.
17959     *
17960     * @return Returns an array holding the current {@link Drawable} state of
17961     * the view.
17962     *
17963     * @see #mergeDrawableStates(int[], int[])
17964     */
17965    protected int[] onCreateDrawableState(int extraSpace) {
17966        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17967                mParent instanceof View) {
17968            return ((View) mParent).onCreateDrawableState(extraSpace);
17969        }
17970
17971        int[] drawableState;
17972
17973        int privateFlags = mPrivateFlags;
17974
17975        int viewStateIndex = 0;
17976        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17977        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17978        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17979        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17980        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17981        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17982        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17983                ThreadedRenderer.isAvailable()) {
17984            // This is set if HW acceleration is requested, even if the current
17985            // process doesn't allow it.  This is just to allow app preview
17986            // windows to better match their app.
17987            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17988        }
17989        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17990
17991        final int privateFlags2 = mPrivateFlags2;
17992        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17993            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17994        }
17995        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17996            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17997        }
17998
17999        drawableState = StateSet.get(viewStateIndex);
18000
18001        //noinspection ConstantIfStatement
18002        if (false) {
18003            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18004            Log.i("View", toString()
18005                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18006                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18007                    + " fo=" + hasFocus()
18008                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18009                    + " wf=" + hasWindowFocus()
18010                    + ": " + Arrays.toString(drawableState));
18011        }
18012
18013        if (extraSpace == 0) {
18014            return drawableState;
18015        }
18016
18017        final int[] fullState;
18018        if (drawableState != null) {
18019            fullState = new int[drawableState.length + extraSpace];
18020            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18021        } else {
18022            fullState = new int[extraSpace];
18023        }
18024
18025        return fullState;
18026    }
18027
18028    /**
18029     * Merge your own state values in <var>additionalState</var> into the base
18030     * state values <var>baseState</var> that were returned by
18031     * {@link #onCreateDrawableState(int)}.
18032     *
18033     * @param baseState The base state values returned by
18034     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18035     * own additional state values.
18036     *
18037     * @param additionalState The additional state values you would like
18038     * added to <var>baseState</var>; this array is not modified.
18039     *
18040     * @return As a convenience, the <var>baseState</var> array you originally
18041     * passed into the function is returned.
18042     *
18043     * @see #onCreateDrawableState(int)
18044     */
18045    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18046        final int N = baseState.length;
18047        int i = N - 1;
18048        while (i >= 0 && baseState[i] == 0) {
18049            i--;
18050        }
18051        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18052        return baseState;
18053    }
18054
18055    /**
18056     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18057     * on all Drawable objects associated with this view.
18058     * <p>
18059     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18060     * attached to this view.
18061     */
18062    @CallSuper
18063    public void jumpDrawablesToCurrentState() {
18064        if (mBackground != null) {
18065            mBackground.jumpToCurrentState();
18066        }
18067        if (mStateListAnimator != null) {
18068            mStateListAnimator.jumpToCurrentState();
18069        }
18070        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18071            mForegroundInfo.mDrawable.jumpToCurrentState();
18072        }
18073    }
18074
18075    /**
18076     * Sets the background color for this view.
18077     * @param color the color of the background
18078     */
18079    @RemotableViewMethod
18080    public void setBackgroundColor(@ColorInt int color) {
18081        if (mBackground instanceof ColorDrawable) {
18082            ((ColorDrawable) mBackground.mutate()).setColor(color);
18083            computeOpaqueFlags();
18084            mBackgroundResource = 0;
18085        } else {
18086            setBackground(new ColorDrawable(color));
18087        }
18088    }
18089
18090    /**
18091     * Set the background to a given resource. The resource should refer to
18092     * a Drawable object or 0 to remove the background.
18093     * @param resid The identifier of the resource.
18094     *
18095     * @attr ref android.R.styleable#View_background
18096     */
18097    @RemotableViewMethod
18098    public void setBackgroundResource(@DrawableRes int resid) {
18099        if (resid != 0 && resid == mBackgroundResource) {
18100            return;
18101        }
18102
18103        Drawable d = null;
18104        if (resid != 0) {
18105            d = mContext.getDrawable(resid);
18106        }
18107        setBackground(d);
18108
18109        mBackgroundResource = resid;
18110    }
18111
18112    /**
18113     * Set the background to a given Drawable, or remove the background. If the
18114     * background has padding, this View's padding is set to the background's
18115     * padding. However, when a background is removed, this View's padding isn't
18116     * touched. If setting the padding is desired, please use
18117     * {@link #setPadding(int, int, int, int)}.
18118     *
18119     * @param background The Drawable to use as the background, or null to remove the
18120     *        background
18121     */
18122    public void setBackground(Drawable background) {
18123        //noinspection deprecation
18124        setBackgroundDrawable(background);
18125    }
18126
18127    /**
18128     * @deprecated use {@link #setBackground(Drawable)} instead
18129     */
18130    @Deprecated
18131    public void setBackgroundDrawable(Drawable background) {
18132        computeOpaqueFlags();
18133
18134        if (background == mBackground) {
18135            return;
18136        }
18137
18138        boolean requestLayout = false;
18139
18140        mBackgroundResource = 0;
18141
18142        /*
18143         * Regardless of whether we're setting a new background or not, we want
18144         * to clear the previous drawable. setVisible first while we still have the callback set.
18145         */
18146        if (mBackground != null) {
18147            if (isAttachedToWindow()) {
18148                mBackground.setVisible(false, false);
18149            }
18150            mBackground.setCallback(null);
18151            unscheduleDrawable(mBackground);
18152        }
18153
18154        if (background != null) {
18155            Rect padding = sThreadLocal.get();
18156            if (padding == null) {
18157                padding = new Rect();
18158                sThreadLocal.set(padding);
18159            }
18160            resetResolvedDrawablesInternal();
18161            background.setLayoutDirection(getLayoutDirection());
18162            if (background.getPadding(padding)) {
18163                resetResolvedPaddingInternal();
18164                switch (background.getLayoutDirection()) {
18165                    case LAYOUT_DIRECTION_RTL:
18166                        mUserPaddingLeftInitial = padding.right;
18167                        mUserPaddingRightInitial = padding.left;
18168                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18169                        break;
18170                    case LAYOUT_DIRECTION_LTR:
18171                    default:
18172                        mUserPaddingLeftInitial = padding.left;
18173                        mUserPaddingRightInitial = padding.right;
18174                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18175                }
18176                mLeftPaddingDefined = false;
18177                mRightPaddingDefined = false;
18178            }
18179
18180            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18181            // if it has a different minimum size, we should layout again
18182            if (mBackground == null
18183                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18184                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18185                requestLayout = true;
18186            }
18187
18188            // Set mBackground before we set this as the callback and start making other
18189            // background drawable state change calls. In particular, the setVisible call below
18190            // can result in drawables attempting to start animations or otherwise invalidate,
18191            // which requires the view set as the callback (us) to recognize the drawable as
18192            // belonging to it as per verifyDrawable.
18193            mBackground = background;
18194            if (background.isStateful()) {
18195                background.setState(getDrawableState());
18196            }
18197            if (isAttachedToWindow()) {
18198                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18199            }
18200
18201            applyBackgroundTint();
18202
18203            // Set callback last, since the view may still be initializing.
18204            background.setCallback(this);
18205
18206            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18207                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18208                requestLayout = true;
18209            }
18210        } else {
18211            /* Remove the background */
18212            mBackground = null;
18213            if ((mViewFlags & WILL_NOT_DRAW) != 0
18214                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18215                mPrivateFlags |= PFLAG_SKIP_DRAW;
18216            }
18217
18218            /*
18219             * When the background is set, we try to apply its padding to this
18220             * View. When the background is removed, we don't touch this View's
18221             * padding. This is noted in the Javadocs. Hence, we don't need to
18222             * requestLayout(), the invalidate() below is sufficient.
18223             */
18224
18225            // The old background's minimum size could have affected this
18226            // View's layout, so let's requestLayout
18227            requestLayout = true;
18228        }
18229
18230        computeOpaqueFlags();
18231
18232        if (requestLayout) {
18233            requestLayout();
18234        }
18235
18236        mBackgroundSizeChanged = true;
18237        invalidate(true);
18238        invalidateOutline();
18239    }
18240
18241    /**
18242     * Gets the background drawable
18243     *
18244     * @return The drawable used as the background for this view, if any.
18245     *
18246     * @see #setBackground(Drawable)
18247     *
18248     * @attr ref android.R.styleable#View_background
18249     */
18250    public Drawable getBackground() {
18251        return mBackground;
18252    }
18253
18254    /**
18255     * Applies a tint to the background drawable. Does not modify the current tint
18256     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18257     * <p>
18258     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18259     * mutate the drawable and apply the specified tint and tint mode using
18260     * {@link Drawable#setTintList(ColorStateList)}.
18261     *
18262     * @param tint the tint to apply, may be {@code null} to clear tint
18263     *
18264     * @attr ref android.R.styleable#View_backgroundTint
18265     * @see #getBackgroundTintList()
18266     * @see Drawable#setTintList(ColorStateList)
18267     */
18268    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18269        if (mBackgroundTint == null) {
18270            mBackgroundTint = new TintInfo();
18271        }
18272        mBackgroundTint.mTintList = tint;
18273        mBackgroundTint.mHasTintList = true;
18274
18275        applyBackgroundTint();
18276    }
18277
18278    /**
18279     * Return the tint applied to the background drawable, if specified.
18280     *
18281     * @return the tint applied to the background drawable
18282     * @attr ref android.R.styleable#View_backgroundTint
18283     * @see #setBackgroundTintList(ColorStateList)
18284     */
18285    @Nullable
18286    public ColorStateList getBackgroundTintList() {
18287        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18288    }
18289
18290    /**
18291     * Specifies the blending mode used to apply the tint specified by
18292     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18293     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18294     *
18295     * @param tintMode the blending mode used to apply the tint, may be
18296     *                 {@code null} to clear tint
18297     * @attr ref android.R.styleable#View_backgroundTintMode
18298     * @see #getBackgroundTintMode()
18299     * @see Drawable#setTintMode(PorterDuff.Mode)
18300     */
18301    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18302        if (mBackgroundTint == null) {
18303            mBackgroundTint = new TintInfo();
18304        }
18305        mBackgroundTint.mTintMode = tintMode;
18306        mBackgroundTint.mHasTintMode = true;
18307
18308        applyBackgroundTint();
18309    }
18310
18311    /**
18312     * Return the blending mode used to apply the tint to the background
18313     * drawable, if specified.
18314     *
18315     * @return the blending mode used to apply the tint to the background
18316     *         drawable
18317     * @attr ref android.R.styleable#View_backgroundTintMode
18318     * @see #setBackgroundTintMode(PorterDuff.Mode)
18319     */
18320    @Nullable
18321    public PorterDuff.Mode getBackgroundTintMode() {
18322        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18323    }
18324
18325    private void applyBackgroundTint() {
18326        if (mBackground != null && mBackgroundTint != null) {
18327            final TintInfo tintInfo = mBackgroundTint;
18328            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18329                mBackground = mBackground.mutate();
18330
18331                if (tintInfo.mHasTintList) {
18332                    mBackground.setTintList(tintInfo.mTintList);
18333                }
18334
18335                if (tintInfo.mHasTintMode) {
18336                    mBackground.setTintMode(tintInfo.mTintMode);
18337                }
18338
18339                // The drawable (or one of its children) may not have been
18340                // stateful before applying the tint, so let's try again.
18341                if (mBackground.isStateful()) {
18342                    mBackground.setState(getDrawableState());
18343                }
18344            }
18345        }
18346    }
18347
18348    /**
18349     * Returns the drawable used as the foreground of this View. The
18350     * foreground drawable, if non-null, is always drawn on top of the view's content.
18351     *
18352     * @return a Drawable or null if no foreground was set
18353     *
18354     * @see #onDrawForeground(Canvas)
18355     */
18356    public Drawable getForeground() {
18357        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18358    }
18359
18360    /**
18361     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18362     *
18363     * @param foreground the Drawable to be drawn on top of the children
18364     *
18365     * @attr ref android.R.styleable#View_foreground
18366     */
18367    public void setForeground(Drawable foreground) {
18368        if (mForegroundInfo == null) {
18369            if (foreground == null) {
18370                // Nothing to do.
18371                return;
18372            }
18373            mForegroundInfo = new ForegroundInfo();
18374        }
18375
18376        if (foreground == mForegroundInfo.mDrawable) {
18377            // Nothing to do
18378            return;
18379        }
18380
18381        if (mForegroundInfo.mDrawable != null) {
18382            if (isAttachedToWindow()) {
18383                mForegroundInfo.mDrawable.setVisible(false, false);
18384            }
18385            mForegroundInfo.mDrawable.setCallback(null);
18386            unscheduleDrawable(mForegroundInfo.mDrawable);
18387        }
18388
18389        mForegroundInfo.mDrawable = foreground;
18390        mForegroundInfo.mBoundsChanged = true;
18391        if (foreground != null) {
18392            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18393                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18394            }
18395            foreground.setLayoutDirection(getLayoutDirection());
18396            if (foreground.isStateful()) {
18397                foreground.setState(getDrawableState());
18398            }
18399            applyForegroundTint();
18400            if (isAttachedToWindow()) {
18401                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18402            }
18403            // Set callback last, since the view may still be initializing.
18404            foreground.setCallback(this);
18405        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18406            mPrivateFlags |= PFLAG_SKIP_DRAW;
18407        }
18408        requestLayout();
18409        invalidate();
18410    }
18411
18412    /**
18413     * Magic bit used to support features of framework-internal window decor implementation details.
18414     * This used to live exclusively in FrameLayout.
18415     *
18416     * @return true if the foreground should draw inside the padding region or false
18417     *         if it should draw inset by the view's padding
18418     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18419     */
18420    public boolean isForegroundInsidePadding() {
18421        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18422    }
18423
18424    /**
18425     * Describes how the foreground is positioned.
18426     *
18427     * @return foreground gravity.
18428     *
18429     * @see #setForegroundGravity(int)
18430     *
18431     * @attr ref android.R.styleable#View_foregroundGravity
18432     */
18433    public int getForegroundGravity() {
18434        return mForegroundInfo != null ? mForegroundInfo.mGravity
18435                : Gravity.START | Gravity.TOP;
18436    }
18437
18438    /**
18439     * Describes how the foreground is positioned. Defaults to START and TOP.
18440     *
18441     * @param gravity see {@link android.view.Gravity}
18442     *
18443     * @see #getForegroundGravity()
18444     *
18445     * @attr ref android.R.styleable#View_foregroundGravity
18446     */
18447    public void setForegroundGravity(int gravity) {
18448        if (mForegroundInfo == null) {
18449            mForegroundInfo = new ForegroundInfo();
18450        }
18451
18452        if (mForegroundInfo.mGravity != gravity) {
18453            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18454                gravity |= Gravity.START;
18455            }
18456
18457            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18458                gravity |= Gravity.TOP;
18459            }
18460
18461            mForegroundInfo.mGravity = gravity;
18462            requestLayout();
18463        }
18464    }
18465
18466    /**
18467     * Applies a tint to the foreground drawable. Does not modify the current tint
18468     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18469     * <p>
18470     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18471     * mutate the drawable and apply the specified tint and tint mode using
18472     * {@link Drawable#setTintList(ColorStateList)}.
18473     *
18474     * @param tint the tint to apply, may be {@code null} to clear tint
18475     *
18476     * @attr ref android.R.styleable#View_foregroundTint
18477     * @see #getForegroundTintList()
18478     * @see Drawable#setTintList(ColorStateList)
18479     */
18480    public void setForegroundTintList(@Nullable ColorStateList tint) {
18481        if (mForegroundInfo == null) {
18482            mForegroundInfo = new ForegroundInfo();
18483        }
18484        if (mForegroundInfo.mTintInfo == null) {
18485            mForegroundInfo.mTintInfo = new TintInfo();
18486        }
18487        mForegroundInfo.mTintInfo.mTintList = tint;
18488        mForegroundInfo.mTintInfo.mHasTintList = true;
18489
18490        applyForegroundTint();
18491    }
18492
18493    /**
18494     * Return the tint applied to the foreground drawable, if specified.
18495     *
18496     * @return the tint applied to the foreground drawable
18497     * @attr ref android.R.styleable#View_foregroundTint
18498     * @see #setForegroundTintList(ColorStateList)
18499     */
18500    @Nullable
18501    public ColorStateList getForegroundTintList() {
18502        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18503                ? mForegroundInfo.mTintInfo.mTintList : null;
18504    }
18505
18506    /**
18507     * Specifies the blending mode used to apply the tint specified by
18508     * {@link #setForegroundTintList(ColorStateList)}} to the background
18509     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18510     *
18511     * @param tintMode the blending mode used to apply the tint, may be
18512     *                 {@code null} to clear tint
18513     * @attr ref android.R.styleable#View_foregroundTintMode
18514     * @see #getForegroundTintMode()
18515     * @see Drawable#setTintMode(PorterDuff.Mode)
18516     */
18517    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18518        if (mForegroundInfo == null) {
18519            mForegroundInfo = new ForegroundInfo();
18520        }
18521        if (mForegroundInfo.mTintInfo == null) {
18522            mForegroundInfo.mTintInfo = new TintInfo();
18523        }
18524        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18525        mForegroundInfo.mTintInfo.mHasTintMode = true;
18526
18527        applyForegroundTint();
18528    }
18529
18530    /**
18531     * Return the blending mode used to apply the tint to the foreground
18532     * drawable, if specified.
18533     *
18534     * @return the blending mode used to apply the tint to the foreground
18535     *         drawable
18536     * @attr ref android.R.styleable#View_foregroundTintMode
18537     * @see #setForegroundTintMode(PorterDuff.Mode)
18538     */
18539    @Nullable
18540    public PorterDuff.Mode getForegroundTintMode() {
18541        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18542                ? mForegroundInfo.mTintInfo.mTintMode : null;
18543    }
18544
18545    private void applyForegroundTint() {
18546        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18547                && mForegroundInfo.mTintInfo != null) {
18548            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18549            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18550                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18551
18552                if (tintInfo.mHasTintList) {
18553                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18554                }
18555
18556                if (tintInfo.mHasTintMode) {
18557                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18558                }
18559
18560                // The drawable (or one of its children) may not have been
18561                // stateful before applying the tint, so let's try again.
18562                if (mForegroundInfo.mDrawable.isStateful()) {
18563                    mForegroundInfo.mDrawable.setState(getDrawableState());
18564                }
18565            }
18566        }
18567    }
18568
18569    /**
18570     * Draw any foreground content for this view.
18571     *
18572     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18573     * drawable or other view-specific decorations. The foreground is drawn on top of the
18574     * primary view content.</p>
18575     *
18576     * @param canvas canvas to draw into
18577     */
18578    public void onDrawForeground(Canvas canvas) {
18579        onDrawScrollIndicators(canvas);
18580        onDrawScrollBars(canvas);
18581
18582        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18583        if (foreground != null) {
18584            if (mForegroundInfo.mBoundsChanged) {
18585                mForegroundInfo.mBoundsChanged = false;
18586                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18587                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18588
18589                if (mForegroundInfo.mInsidePadding) {
18590                    selfBounds.set(0, 0, getWidth(), getHeight());
18591                } else {
18592                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18593                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18594                }
18595
18596                final int ld = getLayoutDirection();
18597                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18598                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18599                foreground.setBounds(overlayBounds);
18600            }
18601
18602            foreground.draw(canvas);
18603        }
18604    }
18605
18606    /**
18607     * Sets the padding. The view may add on the space required to display
18608     * the scrollbars, depending on the style and visibility of the scrollbars.
18609     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18610     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18611     * from the values set in this call.
18612     *
18613     * @attr ref android.R.styleable#View_padding
18614     * @attr ref android.R.styleable#View_paddingBottom
18615     * @attr ref android.R.styleable#View_paddingLeft
18616     * @attr ref android.R.styleable#View_paddingRight
18617     * @attr ref android.R.styleable#View_paddingTop
18618     * @param left the left padding in pixels
18619     * @param top the top padding in pixels
18620     * @param right the right padding in pixels
18621     * @param bottom the bottom padding in pixels
18622     */
18623    public void setPadding(int left, int top, int right, int bottom) {
18624        resetResolvedPaddingInternal();
18625
18626        mUserPaddingStart = UNDEFINED_PADDING;
18627        mUserPaddingEnd = UNDEFINED_PADDING;
18628
18629        mUserPaddingLeftInitial = left;
18630        mUserPaddingRightInitial = right;
18631
18632        mLeftPaddingDefined = true;
18633        mRightPaddingDefined = true;
18634
18635        internalSetPadding(left, top, right, bottom);
18636    }
18637
18638    /**
18639     * @hide
18640     */
18641    protected void internalSetPadding(int left, int top, int right, int bottom) {
18642        mUserPaddingLeft = left;
18643        mUserPaddingRight = right;
18644        mUserPaddingBottom = bottom;
18645
18646        final int viewFlags = mViewFlags;
18647        boolean changed = false;
18648
18649        // Common case is there are no scroll bars.
18650        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18651            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18652                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18653                        ? 0 : getVerticalScrollbarWidth();
18654                switch (mVerticalScrollbarPosition) {
18655                    case SCROLLBAR_POSITION_DEFAULT:
18656                        if (isLayoutRtl()) {
18657                            left += offset;
18658                        } else {
18659                            right += offset;
18660                        }
18661                        break;
18662                    case SCROLLBAR_POSITION_RIGHT:
18663                        right += offset;
18664                        break;
18665                    case SCROLLBAR_POSITION_LEFT:
18666                        left += offset;
18667                        break;
18668                }
18669            }
18670            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18671                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18672                        ? 0 : getHorizontalScrollbarHeight();
18673            }
18674        }
18675
18676        if (mPaddingLeft != left) {
18677            changed = true;
18678            mPaddingLeft = left;
18679        }
18680        if (mPaddingTop != top) {
18681            changed = true;
18682            mPaddingTop = top;
18683        }
18684        if (mPaddingRight != right) {
18685            changed = true;
18686            mPaddingRight = right;
18687        }
18688        if (mPaddingBottom != bottom) {
18689            changed = true;
18690            mPaddingBottom = bottom;
18691        }
18692
18693        if (changed) {
18694            requestLayout();
18695            invalidateOutline();
18696        }
18697    }
18698
18699    /**
18700     * Sets the relative padding. The view may add on the space required to display
18701     * the scrollbars, depending on the style and visibility of the scrollbars.
18702     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18703     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18704     * from the values set in this call.
18705     *
18706     * @attr ref android.R.styleable#View_padding
18707     * @attr ref android.R.styleable#View_paddingBottom
18708     * @attr ref android.R.styleable#View_paddingStart
18709     * @attr ref android.R.styleable#View_paddingEnd
18710     * @attr ref android.R.styleable#View_paddingTop
18711     * @param start the start padding in pixels
18712     * @param top the top padding in pixels
18713     * @param end the end padding in pixels
18714     * @param bottom the bottom padding in pixels
18715     */
18716    public void setPaddingRelative(int start, int top, int end, int bottom) {
18717        resetResolvedPaddingInternal();
18718
18719        mUserPaddingStart = start;
18720        mUserPaddingEnd = end;
18721        mLeftPaddingDefined = true;
18722        mRightPaddingDefined = true;
18723
18724        switch(getLayoutDirection()) {
18725            case LAYOUT_DIRECTION_RTL:
18726                mUserPaddingLeftInitial = end;
18727                mUserPaddingRightInitial = start;
18728                internalSetPadding(end, top, start, bottom);
18729                break;
18730            case LAYOUT_DIRECTION_LTR:
18731            default:
18732                mUserPaddingLeftInitial = start;
18733                mUserPaddingRightInitial = end;
18734                internalSetPadding(start, top, end, bottom);
18735        }
18736    }
18737
18738    /**
18739     * Returns the top padding of this view.
18740     *
18741     * @return the top padding in pixels
18742     */
18743    public int getPaddingTop() {
18744        return mPaddingTop;
18745    }
18746
18747    /**
18748     * Returns the bottom padding of this view. If there are inset and enabled
18749     * scrollbars, this value may include the space required to display the
18750     * scrollbars as well.
18751     *
18752     * @return the bottom padding in pixels
18753     */
18754    public int getPaddingBottom() {
18755        return mPaddingBottom;
18756    }
18757
18758    /**
18759     * Returns the left padding of this view. If there are inset and enabled
18760     * scrollbars, this value may include the space required to display the
18761     * scrollbars as well.
18762     *
18763     * @return the left padding in pixels
18764     */
18765    public int getPaddingLeft() {
18766        if (!isPaddingResolved()) {
18767            resolvePadding();
18768        }
18769        return mPaddingLeft;
18770    }
18771
18772    /**
18773     * Returns the start padding of this view depending on its resolved layout direction.
18774     * If there are inset and enabled scrollbars, this value may include the space
18775     * required to display the scrollbars as well.
18776     *
18777     * @return the start padding in pixels
18778     */
18779    public int getPaddingStart() {
18780        if (!isPaddingResolved()) {
18781            resolvePadding();
18782        }
18783        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18784                mPaddingRight : mPaddingLeft;
18785    }
18786
18787    /**
18788     * Returns the right padding of this view. If there are inset and enabled
18789     * scrollbars, this value may include the space required to display the
18790     * scrollbars as well.
18791     *
18792     * @return the right padding in pixels
18793     */
18794    public int getPaddingRight() {
18795        if (!isPaddingResolved()) {
18796            resolvePadding();
18797        }
18798        return mPaddingRight;
18799    }
18800
18801    /**
18802     * Returns the end padding of this view depending on its resolved layout direction.
18803     * If there are inset and enabled scrollbars, this value may include the space
18804     * required to display the scrollbars as well.
18805     *
18806     * @return the end padding in pixels
18807     */
18808    public int getPaddingEnd() {
18809        if (!isPaddingResolved()) {
18810            resolvePadding();
18811        }
18812        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18813                mPaddingLeft : mPaddingRight;
18814    }
18815
18816    /**
18817     * Return if the padding has been set through relative values
18818     * {@link #setPaddingRelative(int, int, int, int)} or through
18819     * @attr ref android.R.styleable#View_paddingStart or
18820     * @attr ref android.R.styleable#View_paddingEnd
18821     *
18822     * @return true if the padding is relative or false if it is not.
18823     */
18824    public boolean isPaddingRelative() {
18825        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18826    }
18827
18828    Insets computeOpticalInsets() {
18829        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18830    }
18831
18832    /**
18833     * @hide
18834     */
18835    public void resetPaddingToInitialValues() {
18836        if (isRtlCompatibilityMode()) {
18837            mPaddingLeft = mUserPaddingLeftInitial;
18838            mPaddingRight = mUserPaddingRightInitial;
18839            return;
18840        }
18841        if (isLayoutRtl()) {
18842            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18843            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18844        } else {
18845            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18846            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18847        }
18848    }
18849
18850    /**
18851     * @hide
18852     */
18853    public Insets getOpticalInsets() {
18854        if (mLayoutInsets == null) {
18855            mLayoutInsets = computeOpticalInsets();
18856        }
18857        return mLayoutInsets;
18858    }
18859
18860    /**
18861     * Set this view's optical insets.
18862     *
18863     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18864     * property. Views that compute their own optical insets should call it as part of measurement.
18865     * This method does not request layout. If you are setting optical insets outside of
18866     * measure/layout itself you will want to call requestLayout() yourself.
18867     * </p>
18868     * @hide
18869     */
18870    public void setOpticalInsets(Insets insets) {
18871        mLayoutInsets = insets;
18872    }
18873
18874    /**
18875     * Changes the selection state of this view. A view can be selected or not.
18876     * Note that selection is not the same as focus. Views are typically
18877     * selected in the context of an AdapterView like ListView or GridView;
18878     * the selected view is the view that is highlighted.
18879     *
18880     * @param selected true if the view must be selected, false otherwise
18881     */
18882    public void setSelected(boolean selected) {
18883        //noinspection DoubleNegation
18884        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
18885            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
18886            if (!selected) resetPressedState();
18887            invalidate(true);
18888            refreshDrawableState();
18889            dispatchSetSelected(selected);
18890            if (selected) {
18891                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
18892            } else {
18893                notifyViewAccessibilityStateChangedIfNeeded(
18894                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
18895            }
18896        }
18897    }
18898
18899    /**
18900     * Dispatch setSelected to all of this View's children.
18901     *
18902     * @see #setSelected(boolean)
18903     *
18904     * @param selected The new selected state
18905     */
18906    protected void dispatchSetSelected(boolean selected) {
18907    }
18908
18909    /**
18910     * Indicates the selection state of this view.
18911     *
18912     * @return true if the view is selected, false otherwise
18913     */
18914    @ViewDebug.ExportedProperty
18915    public boolean isSelected() {
18916        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18917    }
18918
18919    /**
18920     * Changes the activated state of this view. A view can be activated or not.
18921     * Note that activation is not the same as selection.  Selection is
18922     * a transient property, representing the view (hierarchy) the user is
18923     * currently interacting with.  Activation is a longer-term state that the
18924     * user can move views in and out of.  For example, in a list view with
18925     * single or multiple selection enabled, the views in the current selection
18926     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18927     * here.)  The activated state is propagated down to children of the view it
18928     * is set on.
18929     *
18930     * @param activated true if the view must be activated, false otherwise
18931     */
18932    public void setActivated(boolean activated) {
18933        //noinspection DoubleNegation
18934        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18935            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18936            invalidate(true);
18937            refreshDrawableState();
18938            dispatchSetActivated(activated);
18939        }
18940    }
18941
18942    /**
18943     * Dispatch setActivated to all of this View's children.
18944     *
18945     * @see #setActivated(boolean)
18946     *
18947     * @param activated The new activated state
18948     */
18949    protected void dispatchSetActivated(boolean activated) {
18950    }
18951
18952    /**
18953     * Indicates the activation state of this view.
18954     *
18955     * @return true if the view is activated, false otherwise
18956     */
18957    @ViewDebug.ExportedProperty
18958    public boolean isActivated() {
18959        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18960    }
18961
18962    /**
18963     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18964     * observer can be used to get notifications when global events, like
18965     * layout, happen.
18966     *
18967     * The returned ViewTreeObserver observer is not guaranteed to remain
18968     * valid for the lifetime of this View. If the caller of this method keeps
18969     * a long-lived reference to ViewTreeObserver, it should always check for
18970     * the return value of {@link ViewTreeObserver#isAlive()}.
18971     *
18972     * @return The ViewTreeObserver for this view's hierarchy.
18973     */
18974    public ViewTreeObserver getViewTreeObserver() {
18975        if (mAttachInfo != null) {
18976            return mAttachInfo.mTreeObserver;
18977        }
18978        if (mFloatingTreeObserver == null) {
18979            mFloatingTreeObserver = new ViewTreeObserver();
18980        }
18981        return mFloatingTreeObserver;
18982    }
18983
18984    /**
18985     * <p>Finds the topmost view in the current view hierarchy.</p>
18986     *
18987     * @return the topmost view containing this view
18988     */
18989    public View getRootView() {
18990        if (mAttachInfo != null) {
18991            final View v = mAttachInfo.mRootView;
18992            if (v != null) {
18993                return v;
18994            }
18995        }
18996
18997        View parent = this;
18998
18999        while (parent.mParent != null && parent.mParent instanceof View) {
19000            parent = (View) parent.mParent;
19001        }
19002
19003        return parent;
19004    }
19005
19006    /**
19007     * Transforms a motion event from view-local coordinates to on-screen
19008     * coordinates.
19009     *
19010     * @param ev the view-local motion event
19011     * @return false if the transformation could not be applied
19012     * @hide
19013     */
19014    public boolean toGlobalMotionEvent(MotionEvent ev) {
19015        final AttachInfo info = mAttachInfo;
19016        if (info == null) {
19017            return false;
19018        }
19019
19020        final Matrix m = info.mTmpMatrix;
19021        m.set(Matrix.IDENTITY_MATRIX);
19022        transformMatrixToGlobal(m);
19023        ev.transform(m);
19024        return true;
19025    }
19026
19027    /**
19028     * Transforms a motion event from on-screen coordinates to view-local
19029     * coordinates.
19030     *
19031     * @param ev the on-screen motion event
19032     * @return false if the transformation could not be applied
19033     * @hide
19034     */
19035    public boolean toLocalMotionEvent(MotionEvent ev) {
19036        final AttachInfo info = mAttachInfo;
19037        if (info == null) {
19038            return false;
19039        }
19040
19041        final Matrix m = info.mTmpMatrix;
19042        m.set(Matrix.IDENTITY_MATRIX);
19043        transformMatrixToLocal(m);
19044        ev.transform(m);
19045        return true;
19046    }
19047
19048    /**
19049     * Modifies the input matrix such that it maps view-local coordinates to
19050     * on-screen coordinates.
19051     *
19052     * @param m input matrix to modify
19053     * @hide
19054     */
19055    public void transformMatrixToGlobal(Matrix m) {
19056        final ViewParent parent = mParent;
19057        if (parent instanceof View) {
19058            final View vp = (View) parent;
19059            vp.transformMatrixToGlobal(m);
19060            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19061        } else if (parent instanceof ViewRootImpl) {
19062            final ViewRootImpl vr = (ViewRootImpl) parent;
19063            vr.transformMatrixToGlobal(m);
19064            m.preTranslate(0, -vr.mCurScrollY);
19065        }
19066
19067        m.preTranslate(mLeft, mTop);
19068
19069        if (!hasIdentityMatrix()) {
19070            m.preConcat(getMatrix());
19071        }
19072    }
19073
19074    /**
19075     * Modifies the input matrix such that it maps on-screen coordinates to
19076     * view-local coordinates.
19077     *
19078     * @param m input matrix to modify
19079     * @hide
19080     */
19081    public void transformMatrixToLocal(Matrix m) {
19082        final ViewParent parent = mParent;
19083        if (parent instanceof View) {
19084            final View vp = (View) parent;
19085            vp.transformMatrixToLocal(m);
19086            m.postTranslate(vp.mScrollX, vp.mScrollY);
19087        } else if (parent instanceof ViewRootImpl) {
19088            final ViewRootImpl vr = (ViewRootImpl) parent;
19089            vr.transformMatrixToLocal(m);
19090            m.postTranslate(0, vr.mCurScrollY);
19091        }
19092
19093        m.postTranslate(-mLeft, -mTop);
19094
19095        if (!hasIdentityMatrix()) {
19096            m.postConcat(getInverseMatrix());
19097        }
19098    }
19099
19100    /**
19101     * @hide
19102     */
19103    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19104            @ViewDebug.IntToString(from = 0, to = "x"),
19105            @ViewDebug.IntToString(from = 1, to = "y")
19106    })
19107    public int[] getLocationOnScreen() {
19108        int[] location = new int[2];
19109        getLocationOnScreen(location);
19110        return location;
19111    }
19112
19113    /**
19114     * <p>Computes the coordinates of this view on the screen. The argument
19115     * must be an array of two integers. After the method returns, the array
19116     * contains the x and y location in that order.</p>
19117     *
19118     * @param outLocation an array of two integers in which to hold the coordinates
19119     */
19120    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19121        getLocationInWindow(outLocation);
19122
19123        final AttachInfo info = mAttachInfo;
19124        if (info != null) {
19125            outLocation[0] += info.mWindowLeft;
19126            outLocation[1] += info.mWindowTop;
19127        }
19128    }
19129
19130    /**
19131     * <p>Computes the coordinates of this view in its window. The argument
19132     * must be an array of two integers. After the method returns, the array
19133     * contains the x and y location in that order.</p>
19134     *
19135     * @param outLocation an array of two integers in which to hold the coordinates
19136     */
19137    public void getLocationInWindow(@Size(2) int[] outLocation) {
19138        if (outLocation == null || outLocation.length < 2) {
19139            throw new IllegalArgumentException("outLocation must be an array of two integers");
19140        }
19141
19142        outLocation[0] = 0;
19143        outLocation[1] = 0;
19144
19145        transformFromViewToWindowSpace(outLocation);
19146    }
19147
19148    /** @hide */
19149    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19150        if (inOutLocation == null || inOutLocation.length < 2) {
19151            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19152        }
19153
19154        if (mAttachInfo == null) {
19155            // When the view is not attached to a window, this method does not make sense
19156            inOutLocation[0] = inOutLocation[1] = 0;
19157            return;
19158        }
19159
19160        float position[] = mAttachInfo.mTmpTransformLocation;
19161        position[0] = inOutLocation[0];
19162        position[1] = inOutLocation[1];
19163
19164        if (!hasIdentityMatrix()) {
19165            getMatrix().mapPoints(position);
19166        }
19167
19168        position[0] += mLeft;
19169        position[1] += mTop;
19170
19171        ViewParent viewParent = mParent;
19172        while (viewParent instanceof View) {
19173            final View view = (View) viewParent;
19174
19175            position[0] -= view.mScrollX;
19176            position[1] -= view.mScrollY;
19177
19178            if (!view.hasIdentityMatrix()) {
19179                view.getMatrix().mapPoints(position);
19180            }
19181
19182            position[0] += view.mLeft;
19183            position[1] += view.mTop;
19184
19185            viewParent = view.mParent;
19186         }
19187
19188        if (viewParent instanceof ViewRootImpl) {
19189            // *cough*
19190            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19191            position[1] -= vr.mCurScrollY;
19192        }
19193
19194        inOutLocation[0] = Math.round(position[0]);
19195        inOutLocation[1] = Math.round(position[1]);
19196    }
19197
19198    /**
19199     * {@hide}
19200     * @param id the id of the view to be found
19201     * @return the view of the specified id, null if cannot be found
19202     */
19203    protected View findViewTraversal(@IdRes int id) {
19204        if (id == mID) {
19205            return this;
19206        }
19207        return null;
19208    }
19209
19210    /**
19211     * {@hide}
19212     * @param tag the tag of the view to be found
19213     * @return the view of specified tag, null if cannot be found
19214     */
19215    protected View findViewWithTagTraversal(Object tag) {
19216        if (tag != null && tag.equals(mTag)) {
19217            return this;
19218        }
19219        return null;
19220    }
19221
19222    /**
19223     * {@hide}
19224     * @param predicate The predicate to evaluate.
19225     * @param childToSkip If not null, ignores this child during the recursive traversal.
19226     * @return The first view that matches the predicate or null.
19227     */
19228    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19229        if (predicate.apply(this)) {
19230            return this;
19231        }
19232        return null;
19233    }
19234
19235    /**
19236     * Look for a child view with the given id.  If this view has the given
19237     * id, return this view.
19238     *
19239     * @param id The id to search for.
19240     * @return The view that has the given id in the hierarchy or null
19241     */
19242    @Nullable
19243    public final View findViewById(@IdRes int id) {
19244        if (id < 0) {
19245            return null;
19246        }
19247        return findViewTraversal(id);
19248    }
19249
19250    /**
19251     * Finds a view by its unuque and stable accessibility id.
19252     *
19253     * @param accessibilityId The searched accessibility id.
19254     * @return The found view.
19255     */
19256    final View findViewByAccessibilityId(int accessibilityId) {
19257        if (accessibilityId < 0) {
19258            return null;
19259        }
19260        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19261        if (view != null) {
19262            return view.includeForAccessibility() ? view : null;
19263        }
19264        return null;
19265    }
19266
19267    /**
19268     * Performs the traversal to find a view by its unuque and stable accessibility id.
19269     *
19270     * <strong>Note:</strong>This method does not stop at the root namespace
19271     * boundary since the user can touch the screen at an arbitrary location
19272     * potentially crossing the root namespace bounday which will send an
19273     * accessibility event to accessibility services and they should be able
19274     * to obtain the event source. Also accessibility ids are guaranteed to be
19275     * unique in the window.
19276     *
19277     * @param accessibilityId The accessibility id.
19278     * @return The found view.
19279     *
19280     * @hide
19281     */
19282    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19283        if (getAccessibilityViewId() == accessibilityId) {
19284            return this;
19285        }
19286        return null;
19287    }
19288
19289    /**
19290     * Look for a child view with the given tag.  If this view has the given
19291     * tag, return this view.
19292     *
19293     * @param tag The tag to search for, using "tag.equals(getTag())".
19294     * @return The View that has the given tag in the hierarchy or null
19295     */
19296    public final View findViewWithTag(Object tag) {
19297        if (tag == null) {
19298            return null;
19299        }
19300        return findViewWithTagTraversal(tag);
19301    }
19302
19303    /**
19304     * {@hide}
19305     * Look for a child view that matches the specified predicate.
19306     * If this view matches the predicate, return this view.
19307     *
19308     * @param predicate The predicate to evaluate.
19309     * @return The first view that matches the predicate or null.
19310     */
19311    public final View findViewByPredicate(Predicate<View> predicate) {
19312        return findViewByPredicateTraversal(predicate, null);
19313    }
19314
19315    /**
19316     * {@hide}
19317     * Look for a child view that matches the specified predicate,
19318     * starting with the specified view and its descendents and then
19319     * recusively searching the ancestors and siblings of that view
19320     * until this view is reached.
19321     *
19322     * This method is useful in cases where the predicate does not match
19323     * a single unique view (perhaps multiple views use the same id)
19324     * and we are trying to find the view that is "closest" in scope to the
19325     * starting view.
19326     *
19327     * @param start The view to start from.
19328     * @param predicate The predicate to evaluate.
19329     * @return The first view that matches the predicate or null.
19330     */
19331    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19332        View childToSkip = null;
19333        for (;;) {
19334            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19335            if (view != null || start == this) {
19336                return view;
19337            }
19338
19339            ViewParent parent = start.getParent();
19340            if (parent == null || !(parent instanceof View)) {
19341                return null;
19342            }
19343
19344            childToSkip = start;
19345            start = (View) parent;
19346        }
19347    }
19348
19349    /**
19350     * Sets the identifier for this view. The identifier does not have to be
19351     * unique in this view's hierarchy. The identifier should be a positive
19352     * number.
19353     *
19354     * @see #NO_ID
19355     * @see #getId()
19356     * @see #findViewById(int)
19357     *
19358     * @param id a number used to identify the view
19359     *
19360     * @attr ref android.R.styleable#View_id
19361     */
19362    public void setId(@IdRes int id) {
19363        mID = id;
19364        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19365            mID = generateViewId();
19366        }
19367    }
19368
19369    /**
19370     * {@hide}
19371     *
19372     * @param isRoot true if the view belongs to the root namespace, false
19373     *        otherwise
19374     */
19375    public void setIsRootNamespace(boolean isRoot) {
19376        if (isRoot) {
19377            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19378        } else {
19379            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19380        }
19381    }
19382
19383    /**
19384     * {@hide}
19385     *
19386     * @return true if the view belongs to the root namespace, false otherwise
19387     */
19388    public boolean isRootNamespace() {
19389        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19390    }
19391
19392    /**
19393     * Returns this view's identifier.
19394     *
19395     * @return a positive integer used to identify the view or {@link #NO_ID}
19396     *         if the view has no ID
19397     *
19398     * @see #setId(int)
19399     * @see #findViewById(int)
19400     * @attr ref android.R.styleable#View_id
19401     */
19402    @IdRes
19403    @ViewDebug.CapturedViewProperty
19404    public int getId() {
19405        return mID;
19406    }
19407
19408    /**
19409     * Returns this view's tag.
19410     *
19411     * @return the Object stored in this view as a tag, or {@code null} if not
19412     *         set
19413     *
19414     * @see #setTag(Object)
19415     * @see #getTag(int)
19416     */
19417    @ViewDebug.ExportedProperty
19418    public Object getTag() {
19419        return mTag;
19420    }
19421
19422    /**
19423     * Sets the tag associated with this view. A tag can be used to mark
19424     * a view in its hierarchy and does not have to be unique within the
19425     * hierarchy. Tags can also be used to store data within a view without
19426     * resorting to another data structure.
19427     *
19428     * @param tag an Object to tag the view with
19429     *
19430     * @see #getTag()
19431     * @see #setTag(int, Object)
19432     */
19433    public void setTag(final Object tag) {
19434        mTag = tag;
19435    }
19436
19437    /**
19438     * Returns the tag associated with this view and the specified key.
19439     *
19440     * @param key The key identifying the tag
19441     *
19442     * @return the Object stored in this view as a tag, or {@code null} if not
19443     *         set
19444     *
19445     * @see #setTag(int, Object)
19446     * @see #getTag()
19447     */
19448    public Object getTag(int key) {
19449        if (mKeyedTags != null) return mKeyedTags.get(key);
19450        return null;
19451    }
19452
19453    /**
19454     * Sets a tag associated with this view and a key. A tag can be used
19455     * to mark a view in its hierarchy and does not have to be unique within
19456     * the hierarchy. Tags can also be used to store data within a view
19457     * without resorting to another data structure.
19458     *
19459     * The specified key should be an id declared in the resources of the
19460     * application to ensure it is unique (see the <a
19461     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19462     * Keys identified as belonging to
19463     * the Android framework or not associated with any package will cause
19464     * an {@link IllegalArgumentException} to be thrown.
19465     *
19466     * @param key The key identifying the tag
19467     * @param tag An Object to tag the view with
19468     *
19469     * @throws IllegalArgumentException If they specified key is not valid
19470     *
19471     * @see #setTag(Object)
19472     * @see #getTag(int)
19473     */
19474    public void setTag(int key, final Object tag) {
19475        // If the package id is 0x00 or 0x01, it's either an undefined package
19476        // or a framework id
19477        if ((key >>> 24) < 2) {
19478            throw new IllegalArgumentException("The key must be an application-specific "
19479                    + "resource id.");
19480        }
19481
19482        setKeyedTag(key, tag);
19483    }
19484
19485    /**
19486     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19487     * framework id.
19488     *
19489     * @hide
19490     */
19491    public void setTagInternal(int key, Object tag) {
19492        if ((key >>> 24) != 0x1) {
19493            throw new IllegalArgumentException("The key must be a framework-specific "
19494                    + "resource id.");
19495        }
19496
19497        setKeyedTag(key, tag);
19498    }
19499
19500    private void setKeyedTag(int key, Object tag) {
19501        if (mKeyedTags == null) {
19502            mKeyedTags = new SparseArray<Object>(2);
19503        }
19504
19505        mKeyedTags.put(key, tag);
19506    }
19507
19508    /**
19509     * Prints information about this view in the log output, with the tag
19510     * {@link #VIEW_LOG_TAG}.
19511     *
19512     * @hide
19513     */
19514    public void debug() {
19515        debug(0);
19516    }
19517
19518    /**
19519     * Prints information about this view in the log output, with the tag
19520     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19521     * indentation defined by the <code>depth</code>.
19522     *
19523     * @param depth the indentation level
19524     *
19525     * @hide
19526     */
19527    protected void debug(int depth) {
19528        String output = debugIndent(depth - 1);
19529
19530        output += "+ " + this;
19531        int id = getId();
19532        if (id != -1) {
19533            output += " (id=" + id + ")";
19534        }
19535        Object tag = getTag();
19536        if (tag != null) {
19537            output += " (tag=" + tag + ")";
19538        }
19539        Log.d(VIEW_LOG_TAG, output);
19540
19541        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19542            output = debugIndent(depth) + " FOCUSED";
19543            Log.d(VIEW_LOG_TAG, output);
19544        }
19545
19546        output = debugIndent(depth);
19547        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19548                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19549                + "} ";
19550        Log.d(VIEW_LOG_TAG, output);
19551
19552        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19553                || mPaddingBottom != 0) {
19554            output = debugIndent(depth);
19555            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19556                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19557            Log.d(VIEW_LOG_TAG, output);
19558        }
19559
19560        output = debugIndent(depth);
19561        output += "mMeasureWidth=" + mMeasuredWidth +
19562                " mMeasureHeight=" + mMeasuredHeight;
19563        Log.d(VIEW_LOG_TAG, output);
19564
19565        output = debugIndent(depth);
19566        if (mLayoutParams == null) {
19567            output += "BAD! no layout params";
19568        } else {
19569            output = mLayoutParams.debug(output);
19570        }
19571        Log.d(VIEW_LOG_TAG, output);
19572
19573        output = debugIndent(depth);
19574        output += "flags={";
19575        output += View.printFlags(mViewFlags);
19576        output += "}";
19577        Log.d(VIEW_LOG_TAG, output);
19578
19579        output = debugIndent(depth);
19580        output += "privateFlags={";
19581        output += View.printPrivateFlags(mPrivateFlags);
19582        output += "}";
19583        Log.d(VIEW_LOG_TAG, output);
19584    }
19585
19586    /**
19587     * Creates a string of whitespaces used for indentation.
19588     *
19589     * @param depth the indentation level
19590     * @return a String containing (depth * 2 + 3) * 2 white spaces
19591     *
19592     * @hide
19593     */
19594    protected static String debugIndent(int depth) {
19595        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19596        for (int i = 0; i < (depth * 2) + 3; i++) {
19597            spaces.append(' ').append(' ');
19598        }
19599        return spaces.toString();
19600    }
19601
19602    /**
19603     * <p>Return the offset of the widget's text baseline from the widget's top
19604     * boundary. If this widget does not support baseline alignment, this
19605     * method returns -1. </p>
19606     *
19607     * @return the offset of the baseline within the widget's bounds or -1
19608     *         if baseline alignment is not supported
19609     */
19610    @ViewDebug.ExportedProperty(category = "layout")
19611    public int getBaseline() {
19612        return -1;
19613    }
19614
19615    /**
19616     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19617     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19618     * a layout pass.
19619     *
19620     * @return whether the view hierarchy is currently undergoing a layout pass
19621     */
19622    public boolean isInLayout() {
19623        ViewRootImpl viewRoot = getViewRootImpl();
19624        return (viewRoot != null && viewRoot.isInLayout());
19625    }
19626
19627    /**
19628     * Call this when something has changed which has invalidated the
19629     * layout of this view. This will schedule a layout pass of the view
19630     * tree. This should not be called while the view hierarchy is currently in a layout
19631     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19632     * end of the current layout pass (and then layout will run again) or after the current
19633     * frame is drawn and the next layout occurs.
19634     *
19635     * <p>Subclasses which override this method should call the superclass method to
19636     * handle possible request-during-layout errors correctly.</p>
19637     */
19638    @CallSuper
19639    public void requestLayout() {
19640        if (mMeasureCache != null) mMeasureCache.clear();
19641
19642        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19643            // Only trigger request-during-layout logic if this is the view requesting it,
19644            // not the views in its parent hierarchy
19645            ViewRootImpl viewRoot = getViewRootImpl();
19646            if (viewRoot != null && viewRoot.isInLayout()) {
19647                if (!viewRoot.requestLayoutDuringLayout(this)) {
19648                    return;
19649                }
19650            }
19651            mAttachInfo.mViewRequestingLayout = this;
19652        }
19653
19654        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19655        mPrivateFlags |= PFLAG_INVALIDATED;
19656
19657        if (mParent != null && !mParent.isLayoutRequested()) {
19658            mParent.requestLayout();
19659        }
19660        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19661            mAttachInfo.mViewRequestingLayout = null;
19662        }
19663    }
19664
19665    /**
19666     * Forces this view to be laid out during the next layout pass.
19667     * This method does not call requestLayout() or forceLayout()
19668     * on the parent.
19669     */
19670    public void forceLayout() {
19671        if (mMeasureCache != null) mMeasureCache.clear();
19672
19673        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19674        mPrivateFlags |= PFLAG_INVALIDATED;
19675    }
19676
19677    /**
19678     * <p>
19679     * This is called to find out how big a view should be. The parent
19680     * supplies constraint information in the width and height parameters.
19681     * </p>
19682     *
19683     * <p>
19684     * The actual measurement work of a view is performed in
19685     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19686     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19687     * </p>
19688     *
19689     *
19690     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19691     *        parent
19692     * @param heightMeasureSpec Vertical space requirements as imposed by the
19693     *        parent
19694     *
19695     * @see #onMeasure(int, int)
19696     */
19697    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19698        boolean optical = isLayoutModeOptical(this);
19699        if (optical != isLayoutModeOptical(mParent)) {
19700            Insets insets = getOpticalInsets();
19701            int oWidth  = insets.left + insets.right;
19702            int oHeight = insets.top  + insets.bottom;
19703            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19704            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19705        }
19706
19707        // Suppress sign extension for the low bytes
19708        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19709        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19710
19711        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19712
19713        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19714        // already measured as the correct size. In API 23 and below, this
19715        // extra pass is required to make LinearLayout re-distribute weight.
19716        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19717                || heightMeasureSpec != mOldHeightMeasureSpec;
19718        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19719                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19720        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19721                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19722        final boolean needsLayout = specChanged
19723                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19724
19725        if (forceLayout || needsLayout) {
19726            // first clears the measured dimension flag
19727            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19728
19729            resolveRtlPropertiesIfNeeded();
19730
19731            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19732            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19733                // measure ourselves, this should set the measured dimension flag back
19734                onMeasure(widthMeasureSpec, heightMeasureSpec);
19735                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19736            } else {
19737                long value = mMeasureCache.valueAt(cacheIndex);
19738                // Casting a long to int drops the high 32 bits, no mask needed
19739                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19740                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19741            }
19742
19743            // flag not set, setMeasuredDimension() was not invoked, we raise
19744            // an exception to warn the developer
19745            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19746                throw new IllegalStateException("View with id " + getId() + ": "
19747                        + getClass().getName() + "#onMeasure() did not set the"
19748                        + " measured dimension by calling"
19749                        + " setMeasuredDimension()");
19750            }
19751
19752            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19753        }
19754
19755        mOldWidthMeasureSpec = widthMeasureSpec;
19756        mOldHeightMeasureSpec = heightMeasureSpec;
19757
19758        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19759                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19760    }
19761
19762    /**
19763     * <p>
19764     * Measure the view and its content to determine the measured width and the
19765     * measured height. This method is invoked by {@link #measure(int, int)} and
19766     * should be overridden by subclasses to provide accurate and efficient
19767     * measurement of their contents.
19768     * </p>
19769     *
19770     * <p>
19771     * <strong>CONTRACT:</strong> When overriding this method, you
19772     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19773     * measured width and height of this view. Failure to do so will trigger an
19774     * <code>IllegalStateException</code>, thrown by
19775     * {@link #measure(int, int)}. Calling the superclass'
19776     * {@link #onMeasure(int, int)} is a valid use.
19777     * </p>
19778     *
19779     * <p>
19780     * The base class implementation of measure defaults to the background size,
19781     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19782     * override {@link #onMeasure(int, int)} to provide better measurements of
19783     * their content.
19784     * </p>
19785     *
19786     * <p>
19787     * If this method is overridden, it is the subclass's responsibility to make
19788     * sure the measured height and width are at least the view's minimum height
19789     * and width ({@link #getSuggestedMinimumHeight()} and
19790     * {@link #getSuggestedMinimumWidth()}).
19791     * </p>
19792     *
19793     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19794     *                         The requirements are encoded with
19795     *                         {@link android.view.View.MeasureSpec}.
19796     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19797     *                         The requirements are encoded with
19798     *                         {@link android.view.View.MeasureSpec}.
19799     *
19800     * @see #getMeasuredWidth()
19801     * @see #getMeasuredHeight()
19802     * @see #setMeasuredDimension(int, int)
19803     * @see #getSuggestedMinimumHeight()
19804     * @see #getSuggestedMinimumWidth()
19805     * @see android.view.View.MeasureSpec#getMode(int)
19806     * @see android.view.View.MeasureSpec#getSize(int)
19807     */
19808    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19809        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19810                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19811    }
19812
19813    /**
19814     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19815     * measured width and measured height. Failing to do so will trigger an
19816     * exception at measurement time.</p>
19817     *
19818     * @param measuredWidth The measured width of this view.  May be a complex
19819     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19820     * {@link #MEASURED_STATE_TOO_SMALL}.
19821     * @param measuredHeight The measured height of this view.  May be a complex
19822     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19823     * {@link #MEASURED_STATE_TOO_SMALL}.
19824     */
19825    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19826        boolean optical = isLayoutModeOptical(this);
19827        if (optical != isLayoutModeOptical(mParent)) {
19828            Insets insets = getOpticalInsets();
19829            int opticalWidth  = insets.left + insets.right;
19830            int opticalHeight = insets.top  + insets.bottom;
19831
19832            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19833            measuredHeight += optical ? opticalHeight : -opticalHeight;
19834        }
19835        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19836    }
19837
19838    /**
19839     * Sets the measured dimension without extra processing for things like optical bounds.
19840     * Useful for reapplying consistent values that have already been cooked with adjustments
19841     * for optical bounds, etc. such as those from the measurement cache.
19842     *
19843     * @param measuredWidth The measured width of this view.  May be a complex
19844     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19845     * {@link #MEASURED_STATE_TOO_SMALL}.
19846     * @param measuredHeight The measured height of this view.  May be a complex
19847     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19848     * {@link #MEASURED_STATE_TOO_SMALL}.
19849     */
19850    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19851        mMeasuredWidth = measuredWidth;
19852        mMeasuredHeight = measuredHeight;
19853
19854        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19855    }
19856
19857    /**
19858     * Merge two states as returned by {@link #getMeasuredState()}.
19859     * @param curState The current state as returned from a view or the result
19860     * of combining multiple views.
19861     * @param newState The new view state to combine.
19862     * @return Returns a new integer reflecting the combination of the two
19863     * states.
19864     */
19865    public static int combineMeasuredStates(int curState, int newState) {
19866        return curState | newState;
19867    }
19868
19869    /**
19870     * Version of {@link #resolveSizeAndState(int, int, int)}
19871     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19872     */
19873    public static int resolveSize(int size, int measureSpec) {
19874        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19875    }
19876
19877    /**
19878     * Utility to reconcile a desired size and state, with constraints imposed
19879     * by a MeasureSpec. Will take the desired size, unless a different size
19880     * is imposed by the constraints. The returned value is a compound integer,
19881     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
19882     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
19883     * resulting size is smaller than the size the view wants to be.
19884     *
19885     * @param size How big the view wants to be.
19886     * @param measureSpec Constraints imposed by the parent.
19887     * @param childMeasuredState Size information bit mask for the view's
19888     *                           children.
19889     * @return Size information bit mask as defined by
19890     *         {@link #MEASURED_SIZE_MASK} and
19891     *         {@link #MEASURED_STATE_TOO_SMALL}.
19892     */
19893    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
19894        final int specMode = MeasureSpec.getMode(measureSpec);
19895        final int specSize = MeasureSpec.getSize(measureSpec);
19896        final int result;
19897        switch (specMode) {
19898            case MeasureSpec.AT_MOST:
19899                if (specSize < size) {
19900                    result = specSize | MEASURED_STATE_TOO_SMALL;
19901                } else {
19902                    result = size;
19903                }
19904                break;
19905            case MeasureSpec.EXACTLY:
19906                result = specSize;
19907                break;
19908            case MeasureSpec.UNSPECIFIED:
19909            default:
19910                result = size;
19911        }
19912        return result | (childMeasuredState & MEASURED_STATE_MASK);
19913    }
19914
19915    /**
19916     * Utility to return a default size. Uses the supplied size if the
19917     * MeasureSpec imposed no constraints. Will get larger if allowed
19918     * by the MeasureSpec.
19919     *
19920     * @param size Default size for this view
19921     * @param measureSpec Constraints imposed by the parent
19922     * @return The size this view should be.
19923     */
19924    public static int getDefaultSize(int size, int measureSpec) {
19925        int result = size;
19926        int specMode = MeasureSpec.getMode(measureSpec);
19927        int specSize = MeasureSpec.getSize(measureSpec);
19928
19929        switch (specMode) {
19930        case MeasureSpec.UNSPECIFIED:
19931            result = size;
19932            break;
19933        case MeasureSpec.AT_MOST:
19934        case MeasureSpec.EXACTLY:
19935            result = specSize;
19936            break;
19937        }
19938        return result;
19939    }
19940
19941    /**
19942     * Returns the suggested minimum height that the view should use. This
19943     * returns the maximum of the view's minimum height
19944     * and the background's minimum height
19945     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19946     * <p>
19947     * When being used in {@link #onMeasure(int, int)}, the caller should still
19948     * ensure the returned height is within the requirements of the parent.
19949     *
19950     * @return The suggested minimum height of the view.
19951     */
19952    protected int getSuggestedMinimumHeight() {
19953        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19954
19955    }
19956
19957    /**
19958     * Returns the suggested minimum width that the view should use. This
19959     * returns the maximum of the view's minimum width
19960     * and the background's minimum width
19961     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19962     * <p>
19963     * When being used in {@link #onMeasure(int, int)}, the caller should still
19964     * ensure the returned width is within the requirements of the parent.
19965     *
19966     * @return The suggested minimum width of the view.
19967     */
19968    protected int getSuggestedMinimumWidth() {
19969        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19970    }
19971
19972    /**
19973     * Returns the minimum height of the view.
19974     *
19975     * @return the minimum height the view will try to be.
19976     *
19977     * @see #setMinimumHeight(int)
19978     *
19979     * @attr ref android.R.styleable#View_minHeight
19980     */
19981    public int getMinimumHeight() {
19982        return mMinHeight;
19983    }
19984
19985    /**
19986     * Sets the minimum height of the view. It is not guaranteed the view will
19987     * be able to achieve this minimum height (for example, if its parent layout
19988     * constrains it with less available height).
19989     *
19990     * @param minHeight The minimum height the view will try to be.
19991     *
19992     * @see #getMinimumHeight()
19993     *
19994     * @attr ref android.R.styleable#View_minHeight
19995     */
19996    @RemotableViewMethod
19997    public void setMinimumHeight(int minHeight) {
19998        mMinHeight = minHeight;
19999        requestLayout();
20000    }
20001
20002    /**
20003     * Returns the minimum width of the view.
20004     *
20005     * @return the minimum width the view will try to be.
20006     *
20007     * @see #setMinimumWidth(int)
20008     *
20009     * @attr ref android.R.styleable#View_minWidth
20010     */
20011    public int getMinimumWidth() {
20012        return mMinWidth;
20013    }
20014
20015    /**
20016     * Sets the minimum width of the view. It is not guaranteed the view will
20017     * be able to achieve this minimum width (for example, if its parent layout
20018     * constrains it with less available width).
20019     *
20020     * @param minWidth The minimum width the view will try to be.
20021     *
20022     * @see #getMinimumWidth()
20023     *
20024     * @attr ref android.R.styleable#View_minWidth
20025     */
20026    public void setMinimumWidth(int minWidth) {
20027        mMinWidth = minWidth;
20028        requestLayout();
20029
20030    }
20031
20032    /**
20033     * Get the animation currently associated with this view.
20034     *
20035     * @return The animation that is currently playing or
20036     *         scheduled to play for this view.
20037     */
20038    public Animation getAnimation() {
20039        return mCurrentAnimation;
20040    }
20041
20042    /**
20043     * Start the specified animation now.
20044     *
20045     * @param animation the animation to start now
20046     */
20047    public void startAnimation(Animation animation) {
20048        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20049        setAnimation(animation);
20050        invalidateParentCaches();
20051        invalidate(true);
20052    }
20053
20054    /**
20055     * Cancels any animations for this view.
20056     */
20057    public void clearAnimation() {
20058        if (mCurrentAnimation != null) {
20059            mCurrentAnimation.detach();
20060        }
20061        mCurrentAnimation = null;
20062        invalidateParentIfNeeded();
20063    }
20064
20065    /**
20066     * Sets the next animation to play for this view.
20067     * If you want the animation to play immediately, use
20068     * {@link #startAnimation(android.view.animation.Animation)} instead.
20069     * This method provides allows fine-grained
20070     * control over the start time and invalidation, but you
20071     * must make sure that 1) the animation has a start time set, and
20072     * 2) the view's parent (which controls animations on its children)
20073     * will be invalidated when the animation is supposed to
20074     * start.
20075     *
20076     * @param animation The next animation, or null.
20077     */
20078    public void setAnimation(Animation animation) {
20079        mCurrentAnimation = animation;
20080
20081        if (animation != null) {
20082            // If the screen is off assume the animation start time is now instead of
20083            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20084            // would cause the animation to start when the screen turns back on
20085            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20086                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20087                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20088            }
20089            animation.reset();
20090        }
20091    }
20092
20093    /**
20094     * Invoked by a parent ViewGroup to notify the start of the animation
20095     * currently associated with this view. If you override this method,
20096     * always call super.onAnimationStart();
20097     *
20098     * @see #setAnimation(android.view.animation.Animation)
20099     * @see #getAnimation()
20100     */
20101    @CallSuper
20102    protected void onAnimationStart() {
20103        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20104    }
20105
20106    /**
20107     * Invoked by a parent ViewGroup to notify the end of the animation
20108     * currently associated with this view. If you override this method,
20109     * always call super.onAnimationEnd();
20110     *
20111     * @see #setAnimation(android.view.animation.Animation)
20112     * @see #getAnimation()
20113     */
20114    @CallSuper
20115    protected void onAnimationEnd() {
20116        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20117    }
20118
20119    /**
20120     * Invoked if there is a Transform that involves alpha. Subclass that can
20121     * draw themselves with the specified alpha should return true, and then
20122     * respect that alpha when their onDraw() is called. If this returns false
20123     * then the view may be redirected to draw into an offscreen buffer to
20124     * fulfill the request, which will look fine, but may be slower than if the
20125     * subclass handles it internally. The default implementation returns false.
20126     *
20127     * @param alpha The alpha (0..255) to apply to the view's drawing
20128     * @return true if the view can draw with the specified alpha.
20129     */
20130    protected boolean onSetAlpha(int alpha) {
20131        return false;
20132    }
20133
20134    /**
20135     * This is used by the RootView to perform an optimization when
20136     * the view hierarchy contains one or several SurfaceView.
20137     * SurfaceView is always considered transparent, but its children are not,
20138     * therefore all View objects remove themselves from the global transparent
20139     * region (passed as a parameter to this function).
20140     *
20141     * @param region The transparent region for this ViewAncestor (window).
20142     *
20143     * @return Returns true if the effective visibility of the view at this
20144     * point is opaque, regardless of the transparent region; returns false
20145     * if it is possible for underlying windows to be seen behind the view.
20146     *
20147     * {@hide}
20148     */
20149    public boolean gatherTransparentRegion(Region region) {
20150        final AttachInfo attachInfo = mAttachInfo;
20151        if (region != null && attachInfo != null) {
20152            final int pflags = mPrivateFlags;
20153            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20154                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20155                // remove it from the transparent region.
20156                final int[] location = attachInfo.mTransparentLocation;
20157                getLocationInWindow(location);
20158                region.op(location[0], location[1], location[0] + mRight - mLeft,
20159                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20160            } else {
20161                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20162                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20163                    // the background drawable's non-transparent parts from this transparent region.
20164                    applyDrawableToTransparentRegion(mBackground, region);
20165                }
20166                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20167                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20168                    // Similarly, we remove the foreground drawable's non-transparent parts.
20169                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20170                }
20171            }
20172        }
20173        return true;
20174    }
20175
20176    /**
20177     * Play a sound effect for this view.
20178     *
20179     * <p>The framework will play sound effects for some built in actions, such as
20180     * clicking, but you may wish to play these effects in your widget,
20181     * for instance, for internal navigation.
20182     *
20183     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20184     * {@link #isSoundEffectsEnabled()} is true.
20185     *
20186     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20187     */
20188    public void playSoundEffect(int soundConstant) {
20189        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20190            return;
20191        }
20192        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20193    }
20194
20195    /**
20196     * BZZZTT!!1!
20197     *
20198     * <p>Provide haptic feedback to the user for this view.
20199     *
20200     * <p>The framework will provide haptic feedback for some built in actions,
20201     * such as long presses, but you may wish to provide feedback for your
20202     * own widget.
20203     *
20204     * <p>The feedback will only be performed if
20205     * {@link #isHapticFeedbackEnabled()} is true.
20206     *
20207     * @param feedbackConstant One of the constants defined in
20208     * {@link HapticFeedbackConstants}
20209     */
20210    public boolean performHapticFeedback(int feedbackConstant) {
20211        return performHapticFeedback(feedbackConstant, 0);
20212    }
20213
20214    /**
20215     * BZZZTT!!1!
20216     *
20217     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20218     *
20219     * @param feedbackConstant One of the constants defined in
20220     * {@link HapticFeedbackConstants}
20221     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20222     */
20223    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20224        if (mAttachInfo == null) {
20225            return false;
20226        }
20227        //noinspection SimplifiableIfStatement
20228        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20229                && !isHapticFeedbackEnabled()) {
20230            return false;
20231        }
20232        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20233                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20234    }
20235
20236    /**
20237     * Request that the visibility of the status bar or other screen/window
20238     * decorations be changed.
20239     *
20240     * <p>This method is used to put the over device UI into temporary modes
20241     * where the user's attention is focused more on the application content,
20242     * by dimming or hiding surrounding system affordances.  This is typically
20243     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20244     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20245     * to be placed behind the action bar (and with these flags other system
20246     * affordances) so that smooth transitions between hiding and showing them
20247     * can be done.
20248     *
20249     * <p>Two representative examples of the use of system UI visibility is
20250     * implementing a content browsing application (like a magazine reader)
20251     * and a video playing application.
20252     *
20253     * <p>The first code shows a typical implementation of a View in a content
20254     * browsing application.  In this implementation, the application goes
20255     * into a content-oriented mode by hiding the status bar and action bar,
20256     * and putting the navigation elements into lights out mode.  The user can
20257     * then interact with content while in this mode.  Such an application should
20258     * provide an easy way for the user to toggle out of the mode (such as to
20259     * check information in the status bar or access notifications).  In the
20260     * implementation here, this is done simply by tapping on the content.
20261     *
20262     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20263     *      content}
20264     *
20265     * <p>This second code sample shows a typical implementation of a View
20266     * in a video playing application.  In this situation, while the video is
20267     * playing the application would like to go into a complete full-screen mode,
20268     * to use as much of the display as possible for the video.  When in this state
20269     * the user can not interact with the application; the system intercepts
20270     * touching on the screen to pop the UI out of full screen mode.  See
20271     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20272     *
20273     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20274     *      content}
20275     *
20276     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20277     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20278     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20279     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20280     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20281     */
20282    public void setSystemUiVisibility(int visibility) {
20283        if (visibility != mSystemUiVisibility) {
20284            mSystemUiVisibility = visibility;
20285            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20286                mParent.recomputeViewAttributes(this);
20287            }
20288        }
20289    }
20290
20291    /**
20292     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20293     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20294     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20295     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20296     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20297     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20298     */
20299    public int getSystemUiVisibility() {
20300        return mSystemUiVisibility;
20301    }
20302
20303    /**
20304     * Returns the current system UI visibility that is currently set for
20305     * the entire window.  This is the combination of the
20306     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20307     * views in the window.
20308     */
20309    public int getWindowSystemUiVisibility() {
20310        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20311    }
20312
20313    /**
20314     * Override to find out when the window's requested system UI visibility
20315     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20316     * This is different from the callbacks received through
20317     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20318     * in that this is only telling you about the local request of the window,
20319     * not the actual values applied by the system.
20320     */
20321    public void onWindowSystemUiVisibilityChanged(int visible) {
20322    }
20323
20324    /**
20325     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20326     * the view hierarchy.
20327     */
20328    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20329        onWindowSystemUiVisibilityChanged(visible);
20330    }
20331
20332    /**
20333     * Set a listener to receive callbacks when the visibility of the system bar changes.
20334     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20335     */
20336    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20337        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20338        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20339            mParent.recomputeViewAttributes(this);
20340        }
20341    }
20342
20343    /**
20344     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20345     * the view hierarchy.
20346     */
20347    public void dispatchSystemUiVisibilityChanged(int visibility) {
20348        ListenerInfo li = mListenerInfo;
20349        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20350            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20351                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20352        }
20353    }
20354
20355    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20356        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20357        if (val != mSystemUiVisibility) {
20358            setSystemUiVisibility(val);
20359            return true;
20360        }
20361        return false;
20362    }
20363
20364    /** @hide */
20365    public void setDisabledSystemUiVisibility(int flags) {
20366        if (mAttachInfo != null) {
20367            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20368                mAttachInfo.mDisabledSystemUiVisibility = flags;
20369                if (mParent != null) {
20370                    mParent.recomputeViewAttributes(this);
20371                }
20372            }
20373        }
20374    }
20375
20376    /**
20377     * Creates an image that the system displays during the drag and drop
20378     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20379     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20380     * appearance as the given View. The default also positions the center of the drag shadow
20381     * directly under the touch point. If no View is provided (the constructor with no parameters
20382     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20383     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20384     * default is an invisible drag shadow.
20385     * <p>
20386     * You are not required to use the View you provide to the constructor as the basis of the
20387     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20388     * anything you want as the drag shadow.
20389     * </p>
20390     * <p>
20391     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20392     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20393     *  size and position of the drag shadow. It uses this data to construct a
20394     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20395     *  so that your application can draw the shadow image in the Canvas.
20396     * </p>
20397     *
20398     * <div class="special reference">
20399     * <h3>Developer Guides</h3>
20400     * <p>For a guide to implementing drag and drop features, read the
20401     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20402     * </div>
20403     */
20404    public static class DragShadowBuilder {
20405        private final WeakReference<View> mView;
20406
20407        /**
20408         * Constructs a shadow image builder based on a View. By default, the resulting drag
20409         * shadow will have the same appearance and dimensions as the View, with the touch point
20410         * over the center of the View.
20411         * @param view A View. Any View in scope can be used.
20412         */
20413        public DragShadowBuilder(View view) {
20414            mView = new WeakReference<View>(view);
20415        }
20416
20417        /**
20418         * Construct a shadow builder object with no associated View.  This
20419         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20420         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20421         * to supply the drag shadow's dimensions and appearance without
20422         * reference to any View object. If they are not overridden, then the result is an
20423         * invisible drag shadow.
20424         */
20425        public DragShadowBuilder() {
20426            mView = new WeakReference<View>(null);
20427        }
20428
20429        /**
20430         * Returns the View object that had been passed to the
20431         * {@link #View.DragShadowBuilder(View)}
20432         * constructor.  If that View parameter was {@code null} or if the
20433         * {@link #View.DragShadowBuilder()}
20434         * constructor was used to instantiate the builder object, this method will return
20435         * null.
20436         *
20437         * @return The View object associate with this builder object.
20438         */
20439        @SuppressWarnings({"JavadocReference"})
20440        final public View getView() {
20441            return mView.get();
20442        }
20443
20444        /**
20445         * Provides the metrics for the shadow image. These include the dimensions of
20446         * the shadow image, and the point within that shadow that should
20447         * be centered under the touch location while dragging.
20448         * <p>
20449         * The default implementation sets the dimensions of the shadow to be the
20450         * same as the dimensions of the View itself and centers the shadow under
20451         * the touch point.
20452         * </p>
20453         *
20454         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20455         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20456         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20457         * image.
20458         *
20459         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20460         * shadow image that should be underneath the touch point during the drag and drop
20461         * operation. Your application must set {@link android.graphics.Point#x} to the
20462         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20463         */
20464        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20465            final View view = mView.get();
20466            if (view != null) {
20467                outShadowSize.set(view.getWidth(), view.getHeight());
20468                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20469            } else {
20470                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20471            }
20472        }
20473
20474        /**
20475         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20476         * based on the dimensions it received from the
20477         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20478         *
20479         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20480         */
20481        public void onDrawShadow(Canvas canvas) {
20482            final View view = mView.get();
20483            if (view != null) {
20484                view.draw(canvas);
20485            } else {
20486                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20487            }
20488        }
20489    }
20490
20491    /**
20492     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20493     * startDragAndDrop()} for newer platform versions.
20494     */
20495    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20496                                   Object myLocalState, int flags) {
20497        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20498    }
20499
20500    /**
20501     * Starts a drag and drop operation. When your application calls this method, it passes a
20502     * {@link android.view.View.DragShadowBuilder} object to the system. The
20503     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20504     * to get metrics for the drag shadow, and then calls the object's
20505     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20506     * <p>
20507     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20508     *  drag events to all the View objects in your application that are currently visible. It does
20509     *  this either by calling the View object's drag listener (an implementation of
20510     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20511     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20512     *  Both are passed a {@link android.view.DragEvent} object that has a
20513     *  {@link android.view.DragEvent#getAction()} value of
20514     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20515     * </p>
20516     * <p>
20517     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20518     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20519     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20520     * to the View the user selected for dragging.
20521     * </p>
20522     * @param data A {@link android.content.ClipData} object pointing to the data to be
20523     * transferred by the drag and drop operation.
20524     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20525     * drag shadow.
20526     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20527     * drop operation. When dispatching drag events to views in the same activity this object
20528     * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other
20529     * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()}
20530     * will return null).
20531     * <p>
20532     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20533     * to the target Views. For example, it can contain flags that differentiate between a
20534     * a copy operation and a move operation.
20535     * </p>
20536     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
20537     * flags, or any combination of the following:
20538     *     <ul>
20539     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
20540     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
20541     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20542     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20543     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
20544     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
20545     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
20546     *     </ul>
20547     * @return {@code true} if the method completes successfully, or
20548     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20549     * do a drag, and so no drag operation is in progress.
20550     */
20551    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20552            Object myLocalState, int flags) {
20553        if (ViewDebug.DEBUG_DRAG) {
20554            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20555        }
20556        if (mAttachInfo == null) {
20557            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
20558            return false;
20559        }
20560        boolean okay = false;
20561
20562        Point shadowSize = new Point();
20563        Point shadowTouchPoint = new Point();
20564        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20565
20566        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20567                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20568            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20569        }
20570
20571        if (ViewDebug.DEBUG_DRAG) {
20572            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20573                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20574        }
20575        if (mAttachInfo.mDragSurface != null) {
20576            mAttachInfo.mDragSurface.release();
20577        }
20578        mAttachInfo.mDragSurface = new Surface();
20579        try {
20580            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20581                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20582            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20583                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20584            if (mAttachInfo.mDragToken != null) {
20585                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20586                try {
20587                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20588                    shadowBuilder.onDrawShadow(canvas);
20589                } finally {
20590                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20591                }
20592
20593                final ViewRootImpl root = getViewRootImpl();
20594
20595                // Cache the local state object for delivery with DragEvents
20596                root.setLocalDragState(myLocalState);
20597
20598                // repurpose 'shadowSize' for the last touch point
20599                root.getLastTouchPoint(shadowSize);
20600
20601                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20602                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20603                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20604                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20605            }
20606        } catch (Exception e) {
20607            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20608            mAttachInfo.mDragSurface.destroy();
20609            mAttachInfo.mDragSurface = null;
20610        }
20611
20612        return okay;
20613    }
20614
20615    /**
20616     * Cancels an ongoing drag and drop operation.
20617     * <p>
20618     * A {@link android.view.DragEvent} object with
20619     * {@link android.view.DragEvent#getAction()} value of
20620     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20621     * {@link android.view.DragEvent#getResult()} value of {@code false}
20622     * will be sent to every
20623     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20624     * even if they are not currently visible.
20625     * </p>
20626     * <p>
20627     * This method can be called on any View in the same window as the View on which
20628     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20629     * was called.
20630     * </p>
20631     */
20632    public final void cancelDragAndDrop() {
20633        if (ViewDebug.DEBUG_DRAG) {
20634            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20635        }
20636        if (mAttachInfo == null) {
20637            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
20638            return;
20639        }
20640        if (mAttachInfo.mDragToken != null) {
20641            try {
20642                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20643            } catch (Exception e) {
20644                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20645            }
20646            mAttachInfo.mDragToken = null;
20647        } else {
20648            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20649        }
20650    }
20651
20652    /**
20653     * Updates the drag shadow for the ongoing drag and drop operation.
20654     *
20655     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20656     * new drag shadow.
20657     */
20658    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20659        if (ViewDebug.DEBUG_DRAG) {
20660            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20661        }
20662        if (mAttachInfo == null) {
20663            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
20664            return;
20665        }
20666        if (mAttachInfo.mDragToken != null) {
20667            try {
20668                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20669                try {
20670                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20671                    shadowBuilder.onDrawShadow(canvas);
20672                } finally {
20673                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20674                }
20675            } catch (Exception e) {
20676                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20677            }
20678        } else {
20679            Log.e(VIEW_LOG_TAG, "No active drag");
20680        }
20681    }
20682
20683    /**
20684     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20685     * between {startX, startY} and the new cursor positon.
20686     * @param startX horizontal coordinate where the move started.
20687     * @param startY vertical coordinate where the move started.
20688     * @return whether moving was started successfully.
20689     * @hide
20690     */
20691    public final boolean startMovingTask(float startX, float startY) {
20692        if (ViewDebug.DEBUG_POSITIONING) {
20693            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20694        }
20695        try {
20696            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20697        } catch (RemoteException e) {
20698            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20699        }
20700        return false;
20701    }
20702
20703    /**
20704     * Handles drag events sent by the system following a call to
20705     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20706     * startDragAndDrop()}.
20707     *<p>
20708     * When the system calls this method, it passes a
20709     * {@link android.view.DragEvent} object. A call to
20710     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20711     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20712     * operation.
20713     * @param event The {@link android.view.DragEvent} sent by the system.
20714     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20715     * in DragEvent, indicating the type of drag event represented by this object.
20716     * @return {@code true} if the method was successful, otherwise {@code false}.
20717     * <p>
20718     *  The method should return {@code true} in response to an action type of
20719     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20720     *  operation.
20721     * </p>
20722     * <p>
20723     *  The method should also return {@code true} in response to an action type of
20724     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20725     *  {@code false} if it didn't.
20726     * </p>
20727     */
20728    public boolean onDragEvent(DragEvent event) {
20729        return false;
20730    }
20731
20732    /**
20733     * Detects if this View is enabled and has a drag event listener.
20734     * If both are true, then it calls the drag event listener with the
20735     * {@link android.view.DragEvent} it received. If the drag event listener returns
20736     * {@code true}, then dispatchDragEvent() returns {@code true}.
20737     * <p>
20738     * For all other cases, the method calls the
20739     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20740     * method and returns its result.
20741     * </p>
20742     * <p>
20743     * This ensures that a drag event is always consumed, even if the View does not have a drag
20744     * event listener. However, if the View has a listener and the listener returns true, then
20745     * onDragEvent() is not called.
20746     * </p>
20747     */
20748    public boolean dispatchDragEvent(DragEvent event) {
20749        ListenerInfo li = mListenerInfo;
20750        //noinspection SimplifiableIfStatement
20751        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20752                && li.mOnDragListener.onDrag(this, event)) {
20753            return true;
20754        }
20755        return onDragEvent(event);
20756    }
20757
20758    boolean canAcceptDrag() {
20759        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20760    }
20761
20762    /**
20763     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20764     * it is ever exposed at all.
20765     * @hide
20766     */
20767    public void onCloseSystemDialogs(String reason) {
20768    }
20769
20770    /**
20771     * Given a Drawable whose bounds have been set to draw into this view,
20772     * update a Region being computed for
20773     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20774     * that any non-transparent parts of the Drawable are removed from the
20775     * given transparent region.
20776     *
20777     * @param dr The Drawable whose transparency is to be applied to the region.
20778     * @param region A Region holding the current transparency information,
20779     * where any parts of the region that are set are considered to be
20780     * transparent.  On return, this region will be modified to have the
20781     * transparency information reduced by the corresponding parts of the
20782     * Drawable that are not transparent.
20783     * {@hide}
20784     */
20785    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20786        if (DBG) {
20787            Log.i("View", "Getting transparent region for: " + this);
20788        }
20789        final Region r = dr.getTransparentRegion();
20790        final Rect db = dr.getBounds();
20791        final AttachInfo attachInfo = mAttachInfo;
20792        if (r != null && attachInfo != null) {
20793            final int w = getRight()-getLeft();
20794            final int h = getBottom()-getTop();
20795            if (db.left > 0) {
20796                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20797                r.op(0, 0, db.left, h, Region.Op.UNION);
20798            }
20799            if (db.right < w) {
20800                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20801                r.op(db.right, 0, w, h, Region.Op.UNION);
20802            }
20803            if (db.top > 0) {
20804                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20805                r.op(0, 0, w, db.top, Region.Op.UNION);
20806            }
20807            if (db.bottom < h) {
20808                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20809                r.op(0, db.bottom, w, h, Region.Op.UNION);
20810            }
20811            final int[] location = attachInfo.mTransparentLocation;
20812            getLocationInWindow(location);
20813            r.translate(location[0], location[1]);
20814            region.op(r, Region.Op.INTERSECT);
20815        } else {
20816            region.op(db, Region.Op.DIFFERENCE);
20817        }
20818    }
20819
20820    private void checkForLongClick(int delayOffset, float x, float y) {
20821        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20822            mHasPerformedLongPress = false;
20823
20824            if (mPendingCheckForLongPress == null) {
20825                mPendingCheckForLongPress = new CheckForLongPress();
20826            }
20827            mPendingCheckForLongPress.setAnchor(x, y);
20828            mPendingCheckForLongPress.rememberWindowAttachCount();
20829            postDelayed(mPendingCheckForLongPress,
20830                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20831        }
20832    }
20833
20834    /**
20835     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20836     * LayoutInflater} class, which provides a full range of options for view inflation.
20837     *
20838     * @param context The Context object for your activity or application.
20839     * @param resource The resource ID to inflate
20840     * @param root A view group that will be the parent.  Used to properly inflate the
20841     * layout_* parameters.
20842     * @see LayoutInflater
20843     */
20844    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20845        LayoutInflater factory = LayoutInflater.from(context);
20846        return factory.inflate(resource, root);
20847    }
20848
20849    /**
20850     * Scroll the view with standard behavior for scrolling beyond the normal
20851     * content boundaries. Views that call this method should override
20852     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20853     * results of an over-scroll operation.
20854     *
20855     * Views can use this method to handle any touch or fling-based scrolling.
20856     *
20857     * @param deltaX Change in X in pixels
20858     * @param deltaY Change in Y in pixels
20859     * @param scrollX Current X scroll value in pixels before applying deltaX
20860     * @param scrollY Current Y scroll value in pixels before applying deltaY
20861     * @param scrollRangeX Maximum content scroll range along the X axis
20862     * @param scrollRangeY Maximum content scroll range along the Y axis
20863     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20864     *          along the X axis.
20865     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20866     *          along the Y axis.
20867     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20868     * @return true if scrolling was clamped to an over-scroll boundary along either
20869     *          axis, false otherwise.
20870     */
20871    @SuppressWarnings({"UnusedParameters"})
20872    protected boolean overScrollBy(int deltaX, int deltaY,
20873            int scrollX, int scrollY,
20874            int scrollRangeX, int scrollRangeY,
20875            int maxOverScrollX, int maxOverScrollY,
20876            boolean isTouchEvent) {
20877        final int overScrollMode = mOverScrollMode;
20878        final boolean canScrollHorizontal =
20879                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
20880        final boolean canScrollVertical =
20881                computeVerticalScrollRange() > computeVerticalScrollExtent();
20882        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
20883                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
20884        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
20885                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
20886
20887        int newScrollX = scrollX + deltaX;
20888        if (!overScrollHorizontal) {
20889            maxOverScrollX = 0;
20890        }
20891
20892        int newScrollY = scrollY + deltaY;
20893        if (!overScrollVertical) {
20894            maxOverScrollY = 0;
20895        }
20896
20897        // Clamp values if at the limits and record
20898        final int left = -maxOverScrollX;
20899        final int right = maxOverScrollX + scrollRangeX;
20900        final int top = -maxOverScrollY;
20901        final int bottom = maxOverScrollY + scrollRangeY;
20902
20903        boolean clampedX = false;
20904        if (newScrollX > right) {
20905            newScrollX = right;
20906            clampedX = true;
20907        } else if (newScrollX < left) {
20908            newScrollX = left;
20909            clampedX = true;
20910        }
20911
20912        boolean clampedY = false;
20913        if (newScrollY > bottom) {
20914            newScrollY = bottom;
20915            clampedY = true;
20916        } else if (newScrollY < top) {
20917            newScrollY = top;
20918            clampedY = true;
20919        }
20920
20921        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
20922
20923        return clampedX || clampedY;
20924    }
20925
20926    /**
20927     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
20928     * respond to the results of an over-scroll operation.
20929     *
20930     * @param scrollX New X scroll value in pixels
20931     * @param scrollY New Y scroll value in pixels
20932     * @param clampedX True if scrollX was clamped to an over-scroll boundary
20933     * @param clampedY True if scrollY was clamped to an over-scroll boundary
20934     */
20935    protected void onOverScrolled(int scrollX, int scrollY,
20936            boolean clampedX, boolean clampedY) {
20937        // Intentionally empty.
20938    }
20939
20940    /**
20941     * Returns the over-scroll mode for this view. The result will be
20942     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20943     * (allow over-scrolling only if the view content is larger than the container),
20944     * or {@link #OVER_SCROLL_NEVER}.
20945     *
20946     * @return This view's over-scroll mode.
20947     */
20948    public int getOverScrollMode() {
20949        return mOverScrollMode;
20950    }
20951
20952    /**
20953     * Set the over-scroll mode for this view. Valid over-scroll modes are
20954     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20955     * (allow over-scrolling only if the view content is larger than the container),
20956     * or {@link #OVER_SCROLL_NEVER}.
20957     *
20958     * Setting the over-scroll mode of a view will have an effect only if the
20959     * view is capable of scrolling.
20960     *
20961     * @param overScrollMode The new over-scroll mode for this view.
20962     */
20963    public void setOverScrollMode(int overScrollMode) {
20964        if (overScrollMode != OVER_SCROLL_ALWAYS &&
20965                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
20966                overScrollMode != OVER_SCROLL_NEVER) {
20967            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
20968        }
20969        mOverScrollMode = overScrollMode;
20970    }
20971
20972    /**
20973     * Enable or disable nested scrolling for this view.
20974     *
20975     * <p>If this property is set to true the view will be permitted to initiate nested
20976     * scrolling operations with a compatible parent view in the current hierarchy. If this
20977     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
20978     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
20979     * the nested scroll.</p>
20980     *
20981     * @param enabled true to enable nested scrolling, false to disable
20982     *
20983     * @see #isNestedScrollingEnabled()
20984     */
20985    public void setNestedScrollingEnabled(boolean enabled) {
20986        if (enabled) {
20987            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
20988        } else {
20989            stopNestedScroll();
20990            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
20991        }
20992    }
20993
20994    /**
20995     * Returns true if nested scrolling is enabled for this view.
20996     *
20997     * <p>If nested scrolling is enabled and this View class implementation supports it,
20998     * this view will act as a nested scrolling child view when applicable, forwarding data
20999     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21000     * parent.</p>
21001     *
21002     * @return true if nested scrolling is enabled
21003     *
21004     * @see #setNestedScrollingEnabled(boolean)
21005     */
21006    public boolean isNestedScrollingEnabled() {
21007        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21008                PFLAG3_NESTED_SCROLLING_ENABLED;
21009    }
21010
21011    /**
21012     * Begin a nestable scroll operation along the given axes.
21013     *
21014     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21015     *
21016     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21017     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21018     * In the case of touch scrolling the nested scroll will be terminated automatically in
21019     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21020     * In the event of programmatic scrolling the caller must explicitly call
21021     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21022     *
21023     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21024     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21025     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21026     *
21027     * <p>At each incremental step of the scroll the caller should invoke
21028     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21029     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21030     * parent at least partially consumed the scroll and the caller should adjust the amount it
21031     * scrolls by.</p>
21032     *
21033     * <p>After applying the remainder of the scroll delta the caller should invoke
21034     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21035     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21036     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21037     * </p>
21038     *
21039     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21040     *             {@link #SCROLL_AXIS_VERTICAL}.
21041     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21042     *         the current gesture.
21043     *
21044     * @see #stopNestedScroll()
21045     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21046     * @see #dispatchNestedScroll(int, int, int, int, int[])
21047     */
21048    public boolean startNestedScroll(int axes) {
21049        if (hasNestedScrollingParent()) {
21050            // Already in progress
21051            return true;
21052        }
21053        if (isNestedScrollingEnabled()) {
21054            ViewParent p = getParent();
21055            View child = this;
21056            while (p != null) {
21057                try {
21058                    if (p.onStartNestedScroll(child, this, axes)) {
21059                        mNestedScrollingParent = p;
21060                        p.onNestedScrollAccepted(child, this, axes);
21061                        return true;
21062                    }
21063                } catch (AbstractMethodError e) {
21064                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21065                            "method onStartNestedScroll", e);
21066                    // Allow the search upward to continue
21067                }
21068                if (p instanceof View) {
21069                    child = (View) p;
21070                }
21071                p = p.getParent();
21072            }
21073        }
21074        return false;
21075    }
21076
21077    /**
21078     * Stop a nested scroll in progress.
21079     *
21080     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21081     *
21082     * @see #startNestedScroll(int)
21083     */
21084    public void stopNestedScroll() {
21085        if (mNestedScrollingParent != null) {
21086            mNestedScrollingParent.onStopNestedScroll(this);
21087            mNestedScrollingParent = null;
21088        }
21089    }
21090
21091    /**
21092     * Returns true if this view has a nested scrolling parent.
21093     *
21094     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21095     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21096     *
21097     * @return whether this view has a nested scrolling parent
21098     */
21099    public boolean hasNestedScrollingParent() {
21100        return mNestedScrollingParent != null;
21101    }
21102
21103    /**
21104     * Dispatch one step of a nested scroll in progress.
21105     *
21106     * <p>Implementations of views that support nested scrolling should call this to report
21107     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21108     * is not currently in progress or nested scrolling is not
21109     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21110     *
21111     * <p>Compatible View implementations should also call
21112     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21113     * consuming a component of the scroll event themselves.</p>
21114     *
21115     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21116     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21117     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21118     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21119     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21120     *                       in local view coordinates of this view from before this operation
21121     *                       to after it completes. View implementations may use this to adjust
21122     *                       expected input coordinate tracking.
21123     * @return true if the event was dispatched, false if it could not be dispatched.
21124     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21125     */
21126    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21127            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21128        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21129            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21130                int startX = 0;
21131                int startY = 0;
21132                if (offsetInWindow != null) {
21133                    getLocationInWindow(offsetInWindow);
21134                    startX = offsetInWindow[0];
21135                    startY = offsetInWindow[1];
21136                }
21137
21138                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21139                        dxUnconsumed, dyUnconsumed);
21140
21141                if (offsetInWindow != null) {
21142                    getLocationInWindow(offsetInWindow);
21143                    offsetInWindow[0] -= startX;
21144                    offsetInWindow[1] -= startY;
21145                }
21146                return true;
21147            } else if (offsetInWindow != null) {
21148                // No motion, no dispatch. Keep offsetInWindow up to date.
21149                offsetInWindow[0] = 0;
21150                offsetInWindow[1] = 0;
21151            }
21152        }
21153        return false;
21154    }
21155
21156    /**
21157     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21158     *
21159     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21160     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21161     * scrolling operation to consume some or all of the scroll operation before the child view
21162     * consumes it.</p>
21163     *
21164     * @param dx Horizontal scroll distance in pixels
21165     * @param dy Vertical scroll distance in pixels
21166     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21167     *                 and consumed[1] the consumed dy.
21168     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21169     *                       in local view coordinates of this view from before this operation
21170     *                       to after it completes. View implementations may use this to adjust
21171     *                       expected input coordinate tracking.
21172     * @return true if the parent consumed some or all of the scroll delta
21173     * @see #dispatchNestedScroll(int, int, int, int, int[])
21174     */
21175    public boolean dispatchNestedPreScroll(int dx, int dy,
21176            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21177        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21178            if (dx != 0 || dy != 0) {
21179                int startX = 0;
21180                int startY = 0;
21181                if (offsetInWindow != null) {
21182                    getLocationInWindow(offsetInWindow);
21183                    startX = offsetInWindow[0];
21184                    startY = offsetInWindow[1];
21185                }
21186
21187                if (consumed == null) {
21188                    if (mTempNestedScrollConsumed == null) {
21189                        mTempNestedScrollConsumed = new int[2];
21190                    }
21191                    consumed = mTempNestedScrollConsumed;
21192                }
21193                consumed[0] = 0;
21194                consumed[1] = 0;
21195                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21196
21197                if (offsetInWindow != null) {
21198                    getLocationInWindow(offsetInWindow);
21199                    offsetInWindow[0] -= startX;
21200                    offsetInWindow[1] -= startY;
21201                }
21202                return consumed[0] != 0 || consumed[1] != 0;
21203            } else if (offsetInWindow != null) {
21204                offsetInWindow[0] = 0;
21205                offsetInWindow[1] = 0;
21206            }
21207        }
21208        return false;
21209    }
21210
21211    /**
21212     * Dispatch a fling to a nested scrolling parent.
21213     *
21214     * <p>This method should be used to indicate that a nested scrolling child has detected
21215     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21216     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21217     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21218     * along a scrollable axis.</p>
21219     *
21220     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21221     * its own content, it can use this method to delegate the fling to its nested scrolling
21222     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21223     *
21224     * @param velocityX Horizontal fling velocity in pixels per second
21225     * @param velocityY Vertical fling velocity in pixels per second
21226     * @param consumed true if the child consumed the fling, false otherwise
21227     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21228     */
21229    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21230        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21231            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21232        }
21233        return false;
21234    }
21235
21236    /**
21237     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21238     *
21239     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21240     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21241     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21242     * before the child view consumes it. If this method returns <code>true</code>, a nested
21243     * parent view consumed the fling and this view should not scroll as a result.</p>
21244     *
21245     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21246     * the fling at a time. If a parent view consumed the fling this method will return false.
21247     * Custom view implementations should account for this in two ways:</p>
21248     *
21249     * <ul>
21250     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21251     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21252     *     position regardless.</li>
21253     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21254     *     even to settle back to a valid idle position.</li>
21255     * </ul>
21256     *
21257     * <p>Views should also not offer fling velocities to nested parent views along an axis
21258     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21259     * should not offer a horizontal fling velocity to its parents since scrolling along that
21260     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21261     *
21262     * @param velocityX Horizontal fling velocity in pixels per second
21263     * @param velocityY Vertical fling velocity in pixels per second
21264     * @return true if a nested scrolling parent consumed the fling
21265     */
21266    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21267        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21268            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21269        }
21270        return false;
21271    }
21272
21273    /**
21274     * Gets a scale factor that determines the distance the view should scroll
21275     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21276     * @return The vertical scroll scale factor.
21277     * @hide
21278     */
21279    protected float getVerticalScrollFactor() {
21280        if (mVerticalScrollFactor == 0) {
21281            TypedValue outValue = new TypedValue();
21282            if (!mContext.getTheme().resolveAttribute(
21283                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21284                throw new IllegalStateException(
21285                        "Expected theme to define listPreferredItemHeight.");
21286            }
21287            mVerticalScrollFactor = outValue.getDimension(
21288                    mContext.getResources().getDisplayMetrics());
21289        }
21290        return mVerticalScrollFactor;
21291    }
21292
21293    /**
21294     * Gets a scale factor that determines the distance the view should scroll
21295     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21296     * @return The horizontal scroll scale factor.
21297     * @hide
21298     */
21299    protected float getHorizontalScrollFactor() {
21300        // TODO: Should use something else.
21301        return getVerticalScrollFactor();
21302    }
21303
21304    /**
21305     * Return the value specifying the text direction or policy that was set with
21306     * {@link #setTextDirection(int)}.
21307     *
21308     * @return the defined text direction. It can be one of:
21309     *
21310     * {@link #TEXT_DIRECTION_INHERIT},
21311     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21312     * {@link #TEXT_DIRECTION_ANY_RTL},
21313     * {@link #TEXT_DIRECTION_LTR},
21314     * {@link #TEXT_DIRECTION_RTL},
21315     * {@link #TEXT_DIRECTION_LOCALE},
21316     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21317     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21318     *
21319     * @attr ref android.R.styleable#View_textDirection
21320     *
21321     * @hide
21322     */
21323    @ViewDebug.ExportedProperty(category = "text", mapping = {
21324            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21325            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21326            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21327            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21328            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21329            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21330            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21331            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21332    })
21333    public int getRawTextDirection() {
21334        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21335    }
21336
21337    /**
21338     * Set the text direction.
21339     *
21340     * @param textDirection the direction to set. Should be one of:
21341     *
21342     * {@link #TEXT_DIRECTION_INHERIT},
21343     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21344     * {@link #TEXT_DIRECTION_ANY_RTL},
21345     * {@link #TEXT_DIRECTION_LTR},
21346     * {@link #TEXT_DIRECTION_RTL},
21347     * {@link #TEXT_DIRECTION_LOCALE}
21348     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21349     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21350     *
21351     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21352     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21353     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21354     *
21355     * @attr ref android.R.styleable#View_textDirection
21356     */
21357    public void setTextDirection(int textDirection) {
21358        if (getRawTextDirection() != textDirection) {
21359            // Reset the current text direction and the resolved one
21360            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21361            resetResolvedTextDirection();
21362            // Set the new text direction
21363            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21364            // Do resolution
21365            resolveTextDirection();
21366            // Notify change
21367            onRtlPropertiesChanged(getLayoutDirection());
21368            // Refresh
21369            requestLayout();
21370            invalidate(true);
21371        }
21372    }
21373
21374    /**
21375     * Return the resolved text direction.
21376     *
21377     * @return the resolved text direction. Returns one of:
21378     *
21379     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21380     * {@link #TEXT_DIRECTION_ANY_RTL},
21381     * {@link #TEXT_DIRECTION_LTR},
21382     * {@link #TEXT_DIRECTION_RTL},
21383     * {@link #TEXT_DIRECTION_LOCALE},
21384     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21385     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21386     *
21387     * @attr ref android.R.styleable#View_textDirection
21388     */
21389    @ViewDebug.ExportedProperty(category = "text", mapping = {
21390            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21391            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21392            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21393            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21394            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21395            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21396            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21397            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21398    })
21399    public int getTextDirection() {
21400        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21401    }
21402
21403    /**
21404     * Resolve the text direction.
21405     *
21406     * @return true if resolution has been done, false otherwise.
21407     *
21408     * @hide
21409     */
21410    public boolean resolveTextDirection() {
21411        // Reset any previous text direction resolution
21412        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21413
21414        if (hasRtlSupport()) {
21415            // Set resolved text direction flag depending on text direction flag
21416            final int textDirection = getRawTextDirection();
21417            switch(textDirection) {
21418                case TEXT_DIRECTION_INHERIT:
21419                    if (!canResolveTextDirection()) {
21420                        // We cannot do the resolution if there is no parent, so use the default one
21421                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21422                        // Resolution will need to happen again later
21423                        return false;
21424                    }
21425
21426                    // Parent has not yet resolved, so we still return the default
21427                    try {
21428                        if (!mParent.isTextDirectionResolved()) {
21429                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21430                            // Resolution will need to happen again later
21431                            return false;
21432                        }
21433                    } catch (AbstractMethodError e) {
21434                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21435                                " does not fully implement ViewParent", e);
21436                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21437                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21438                        return true;
21439                    }
21440
21441                    // Set current resolved direction to the same value as the parent's one
21442                    int parentResolvedDirection;
21443                    try {
21444                        parentResolvedDirection = mParent.getTextDirection();
21445                    } catch (AbstractMethodError e) {
21446                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21447                                " does not fully implement ViewParent", e);
21448                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21449                    }
21450                    switch (parentResolvedDirection) {
21451                        case TEXT_DIRECTION_FIRST_STRONG:
21452                        case TEXT_DIRECTION_ANY_RTL:
21453                        case TEXT_DIRECTION_LTR:
21454                        case TEXT_DIRECTION_RTL:
21455                        case TEXT_DIRECTION_LOCALE:
21456                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21457                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21458                            mPrivateFlags2 |=
21459                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21460                            break;
21461                        default:
21462                            // Default resolved direction is "first strong" heuristic
21463                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21464                    }
21465                    break;
21466                case TEXT_DIRECTION_FIRST_STRONG:
21467                case TEXT_DIRECTION_ANY_RTL:
21468                case TEXT_DIRECTION_LTR:
21469                case TEXT_DIRECTION_RTL:
21470                case TEXT_DIRECTION_LOCALE:
21471                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21472                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21473                    // Resolved direction is the same as text direction
21474                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21475                    break;
21476                default:
21477                    // Default resolved direction is "first strong" heuristic
21478                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21479            }
21480        } else {
21481            // Default resolved direction is "first strong" heuristic
21482            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21483        }
21484
21485        // Set to resolved
21486        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21487        return true;
21488    }
21489
21490    /**
21491     * Check if text direction resolution can be done.
21492     *
21493     * @return true if text direction resolution can be done otherwise return false.
21494     */
21495    public boolean canResolveTextDirection() {
21496        switch (getRawTextDirection()) {
21497            case TEXT_DIRECTION_INHERIT:
21498                if (mParent != null) {
21499                    try {
21500                        return mParent.canResolveTextDirection();
21501                    } catch (AbstractMethodError e) {
21502                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21503                                " does not fully implement ViewParent", e);
21504                    }
21505                }
21506                return false;
21507
21508            default:
21509                return true;
21510        }
21511    }
21512
21513    /**
21514     * Reset resolved text direction. Text direction will be resolved during a call to
21515     * {@link #onMeasure(int, int)}.
21516     *
21517     * @hide
21518     */
21519    public void resetResolvedTextDirection() {
21520        // Reset any previous text direction resolution
21521        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21522        // Set to default value
21523        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21524    }
21525
21526    /**
21527     * @return true if text direction is inherited.
21528     *
21529     * @hide
21530     */
21531    public boolean isTextDirectionInherited() {
21532        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21533    }
21534
21535    /**
21536     * @return true if text direction is resolved.
21537     */
21538    public boolean isTextDirectionResolved() {
21539        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21540    }
21541
21542    /**
21543     * Return the value specifying the text alignment or policy that was set with
21544     * {@link #setTextAlignment(int)}.
21545     *
21546     * @return the defined text alignment. It can be one of:
21547     *
21548     * {@link #TEXT_ALIGNMENT_INHERIT},
21549     * {@link #TEXT_ALIGNMENT_GRAVITY},
21550     * {@link #TEXT_ALIGNMENT_CENTER},
21551     * {@link #TEXT_ALIGNMENT_TEXT_START},
21552     * {@link #TEXT_ALIGNMENT_TEXT_END},
21553     * {@link #TEXT_ALIGNMENT_VIEW_START},
21554     * {@link #TEXT_ALIGNMENT_VIEW_END}
21555     *
21556     * @attr ref android.R.styleable#View_textAlignment
21557     *
21558     * @hide
21559     */
21560    @ViewDebug.ExportedProperty(category = "text", mapping = {
21561            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21562            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21563            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21564            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21565            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21566            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21567            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21568    })
21569    @TextAlignment
21570    public int getRawTextAlignment() {
21571        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21572    }
21573
21574    /**
21575     * Set the text alignment.
21576     *
21577     * @param textAlignment The text alignment to set. Should be one of
21578     *
21579     * {@link #TEXT_ALIGNMENT_INHERIT},
21580     * {@link #TEXT_ALIGNMENT_GRAVITY},
21581     * {@link #TEXT_ALIGNMENT_CENTER},
21582     * {@link #TEXT_ALIGNMENT_TEXT_START},
21583     * {@link #TEXT_ALIGNMENT_TEXT_END},
21584     * {@link #TEXT_ALIGNMENT_VIEW_START},
21585     * {@link #TEXT_ALIGNMENT_VIEW_END}
21586     *
21587     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21588     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21589     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21590     *
21591     * @attr ref android.R.styleable#View_textAlignment
21592     */
21593    public void setTextAlignment(@TextAlignment int textAlignment) {
21594        if (textAlignment != getRawTextAlignment()) {
21595            // Reset the current and resolved text alignment
21596            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21597            resetResolvedTextAlignment();
21598            // Set the new text alignment
21599            mPrivateFlags2 |=
21600                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21601            // Do resolution
21602            resolveTextAlignment();
21603            // Notify change
21604            onRtlPropertiesChanged(getLayoutDirection());
21605            // Refresh
21606            requestLayout();
21607            invalidate(true);
21608        }
21609    }
21610
21611    /**
21612     * Return the resolved text alignment.
21613     *
21614     * @return the resolved text alignment. Returns one of:
21615     *
21616     * {@link #TEXT_ALIGNMENT_GRAVITY},
21617     * {@link #TEXT_ALIGNMENT_CENTER},
21618     * {@link #TEXT_ALIGNMENT_TEXT_START},
21619     * {@link #TEXT_ALIGNMENT_TEXT_END},
21620     * {@link #TEXT_ALIGNMENT_VIEW_START},
21621     * {@link #TEXT_ALIGNMENT_VIEW_END}
21622     *
21623     * @attr ref android.R.styleable#View_textAlignment
21624     */
21625    @ViewDebug.ExportedProperty(category = "text", mapping = {
21626            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21627            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21628            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21629            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21630            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21631            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21632            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21633    })
21634    @TextAlignment
21635    public int getTextAlignment() {
21636        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21637                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21638    }
21639
21640    /**
21641     * Resolve the text alignment.
21642     *
21643     * @return true if resolution has been done, false otherwise.
21644     *
21645     * @hide
21646     */
21647    public boolean resolveTextAlignment() {
21648        // Reset any previous text alignment resolution
21649        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21650
21651        if (hasRtlSupport()) {
21652            // Set resolved text alignment flag depending on text alignment flag
21653            final int textAlignment = getRawTextAlignment();
21654            switch (textAlignment) {
21655                case TEXT_ALIGNMENT_INHERIT:
21656                    // Check if we can resolve the text alignment
21657                    if (!canResolveTextAlignment()) {
21658                        // We cannot do the resolution if there is no parent so use the default
21659                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21660                        // Resolution will need to happen again later
21661                        return false;
21662                    }
21663
21664                    // Parent has not yet resolved, so we still return the default
21665                    try {
21666                        if (!mParent.isTextAlignmentResolved()) {
21667                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21668                            // Resolution will need to happen again later
21669                            return false;
21670                        }
21671                    } catch (AbstractMethodError e) {
21672                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21673                                " does not fully implement ViewParent", e);
21674                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21675                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21676                        return true;
21677                    }
21678
21679                    int parentResolvedTextAlignment;
21680                    try {
21681                        parentResolvedTextAlignment = mParent.getTextAlignment();
21682                    } catch (AbstractMethodError e) {
21683                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21684                                " does not fully implement ViewParent", e);
21685                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21686                    }
21687                    switch (parentResolvedTextAlignment) {
21688                        case TEXT_ALIGNMENT_GRAVITY:
21689                        case TEXT_ALIGNMENT_TEXT_START:
21690                        case TEXT_ALIGNMENT_TEXT_END:
21691                        case TEXT_ALIGNMENT_CENTER:
21692                        case TEXT_ALIGNMENT_VIEW_START:
21693                        case TEXT_ALIGNMENT_VIEW_END:
21694                            // Resolved text alignment is the same as the parent resolved
21695                            // text alignment
21696                            mPrivateFlags2 |=
21697                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21698                            break;
21699                        default:
21700                            // Use default resolved text alignment
21701                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21702                    }
21703                    break;
21704                case TEXT_ALIGNMENT_GRAVITY:
21705                case TEXT_ALIGNMENT_TEXT_START:
21706                case TEXT_ALIGNMENT_TEXT_END:
21707                case TEXT_ALIGNMENT_CENTER:
21708                case TEXT_ALIGNMENT_VIEW_START:
21709                case TEXT_ALIGNMENT_VIEW_END:
21710                    // Resolved text alignment is the same as text alignment
21711                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21712                    break;
21713                default:
21714                    // Use default resolved text alignment
21715                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21716            }
21717        } else {
21718            // Use default resolved text alignment
21719            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21720        }
21721
21722        // Set the resolved
21723        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21724        return true;
21725    }
21726
21727    /**
21728     * Check if text alignment resolution can be done.
21729     *
21730     * @return true if text alignment resolution can be done otherwise return false.
21731     */
21732    public boolean canResolveTextAlignment() {
21733        switch (getRawTextAlignment()) {
21734            case TEXT_DIRECTION_INHERIT:
21735                if (mParent != null) {
21736                    try {
21737                        return mParent.canResolveTextAlignment();
21738                    } catch (AbstractMethodError e) {
21739                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21740                                " does not fully implement ViewParent", e);
21741                    }
21742                }
21743                return false;
21744
21745            default:
21746                return true;
21747        }
21748    }
21749
21750    /**
21751     * Reset resolved text alignment. Text alignment will be resolved during a call to
21752     * {@link #onMeasure(int, int)}.
21753     *
21754     * @hide
21755     */
21756    public void resetResolvedTextAlignment() {
21757        // Reset any previous text alignment resolution
21758        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21759        // Set to default
21760        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21761    }
21762
21763    /**
21764     * @return true if text alignment is inherited.
21765     *
21766     * @hide
21767     */
21768    public boolean isTextAlignmentInherited() {
21769        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21770    }
21771
21772    /**
21773     * @return true if text alignment is resolved.
21774     */
21775    public boolean isTextAlignmentResolved() {
21776        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21777    }
21778
21779    /**
21780     * Generate a value suitable for use in {@link #setId(int)}.
21781     * This value will not collide with ID values generated at build time by aapt for R.id.
21782     *
21783     * @return a generated ID value
21784     */
21785    public static int generateViewId() {
21786        for (;;) {
21787            final int result = sNextGeneratedId.get();
21788            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21789            int newValue = result + 1;
21790            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21791            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21792                return result;
21793            }
21794        }
21795    }
21796
21797    /**
21798     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21799     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21800     *                           a normal View or a ViewGroup with
21801     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21802     * @hide
21803     */
21804    public void captureTransitioningViews(List<View> transitioningViews) {
21805        if (getVisibility() == View.VISIBLE) {
21806            transitioningViews.add(this);
21807        }
21808    }
21809
21810    /**
21811     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21812     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21813     * @hide
21814     */
21815    public void findNamedViews(Map<String, View> namedElements) {
21816        if (getVisibility() == VISIBLE || mGhostView != null) {
21817            String transitionName = getTransitionName();
21818            if (transitionName != null) {
21819                namedElements.put(transitionName, this);
21820            }
21821        }
21822    }
21823
21824    /**
21825     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21826     * The default implementation does not care the location or event types, but some subclasses
21827     * may use it (such as WebViews).
21828     * @param event The MotionEvent from a mouse
21829     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
21830     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
21831     * @see PointerIcon
21832     */
21833    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
21834        final float x = event.getX(pointerIndex);
21835        final float y = event.getY(pointerIndex);
21836        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21837            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
21838        }
21839        return mPointerIcon;
21840    }
21841
21842    /**
21843     * Set the pointer icon for the current view.
21844     * Passing {@code null} will restore the pointer icon to its default value.
21845     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21846     */
21847    public void setPointerIcon(PointerIcon pointerIcon) {
21848        mPointerIcon = pointerIcon;
21849        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21850            return;
21851        }
21852        try {
21853            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21854        } catch (RemoteException e) {
21855        }
21856    }
21857
21858    /**
21859     * Gets the pointer icon for the current view.
21860     */
21861    public PointerIcon getPointerIcon() {
21862        return mPointerIcon;
21863    }
21864
21865    //
21866    // Properties
21867    //
21868    /**
21869     * A Property wrapper around the <code>alpha</code> functionality handled by the
21870     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21871     */
21872    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21873        @Override
21874        public void setValue(View object, float value) {
21875            object.setAlpha(value);
21876        }
21877
21878        @Override
21879        public Float get(View object) {
21880            return object.getAlpha();
21881        }
21882    };
21883
21884    /**
21885     * A Property wrapper around the <code>translationX</code> functionality handled by the
21886     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
21887     */
21888    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
21889        @Override
21890        public void setValue(View object, float value) {
21891            object.setTranslationX(value);
21892        }
21893
21894                @Override
21895        public Float get(View object) {
21896            return object.getTranslationX();
21897        }
21898    };
21899
21900    /**
21901     * A Property wrapper around the <code>translationY</code> functionality handled by the
21902     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
21903     */
21904    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
21905        @Override
21906        public void setValue(View object, float value) {
21907            object.setTranslationY(value);
21908        }
21909
21910        @Override
21911        public Float get(View object) {
21912            return object.getTranslationY();
21913        }
21914    };
21915
21916    /**
21917     * A Property wrapper around the <code>translationZ</code> functionality handled by the
21918     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
21919     */
21920    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
21921        @Override
21922        public void setValue(View object, float value) {
21923            object.setTranslationZ(value);
21924        }
21925
21926        @Override
21927        public Float get(View object) {
21928            return object.getTranslationZ();
21929        }
21930    };
21931
21932    /**
21933     * A Property wrapper around the <code>x</code> functionality handled by the
21934     * {@link View#setX(float)} and {@link View#getX()} methods.
21935     */
21936    public static final Property<View, Float> X = new FloatProperty<View>("x") {
21937        @Override
21938        public void setValue(View object, float value) {
21939            object.setX(value);
21940        }
21941
21942        @Override
21943        public Float get(View object) {
21944            return object.getX();
21945        }
21946    };
21947
21948    /**
21949     * A Property wrapper around the <code>y</code> functionality handled by the
21950     * {@link View#setY(float)} and {@link View#getY()} methods.
21951     */
21952    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
21953        @Override
21954        public void setValue(View object, float value) {
21955            object.setY(value);
21956        }
21957
21958        @Override
21959        public Float get(View object) {
21960            return object.getY();
21961        }
21962    };
21963
21964    /**
21965     * A Property wrapper around the <code>z</code> functionality handled by the
21966     * {@link View#setZ(float)} and {@link View#getZ()} methods.
21967     */
21968    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
21969        @Override
21970        public void setValue(View object, float value) {
21971            object.setZ(value);
21972        }
21973
21974        @Override
21975        public Float get(View object) {
21976            return object.getZ();
21977        }
21978    };
21979
21980    /**
21981     * A Property wrapper around the <code>rotation</code> functionality handled by the
21982     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
21983     */
21984    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
21985        @Override
21986        public void setValue(View object, float value) {
21987            object.setRotation(value);
21988        }
21989
21990        @Override
21991        public Float get(View object) {
21992            return object.getRotation();
21993        }
21994    };
21995
21996    /**
21997     * A Property wrapper around the <code>rotationX</code> functionality handled by the
21998     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
21999     */
22000    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22001        @Override
22002        public void setValue(View object, float value) {
22003            object.setRotationX(value);
22004        }
22005
22006        @Override
22007        public Float get(View object) {
22008            return object.getRotationX();
22009        }
22010    };
22011
22012    /**
22013     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22014     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22015     */
22016    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22017        @Override
22018        public void setValue(View object, float value) {
22019            object.setRotationY(value);
22020        }
22021
22022        @Override
22023        public Float get(View object) {
22024            return object.getRotationY();
22025        }
22026    };
22027
22028    /**
22029     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22030     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22031     */
22032    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22033        @Override
22034        public void setValue(View object, float value) {
22035            object.setScaleX(value);
22036        }
22037
22038        @Override
22039        public Float get(View object) {
22040            return object.getScaleX();
22041        }
22042    };
22043
22044    /**
22045     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22046     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22047     */
22048    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22049        @Override
22050        public void setValue(View object, float value) {
22051            object.setScaleY(value);
22052        }
22053
22054        @Override
22055        public Float get(View object) {
22056            return object.getScaleY();
22057        }
22058    };
22059
22060    /**
22061     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22062     * Each MeasureSpec represents a requirement for either the width or the height.
22063     * A MeasureSpec is comprised of a size and a mode. There are three possible
22064     * modes:
22065     * <dl>
22066     * <dt>UNSPECIFIED</dt>
22067     * <dd>
22068     * The parent has not imposed any constraint on the child. It can be whatever size
22069     * it wants.
22070     * </dd>
22071     *
22072     * <dt>EXACTLY</dt>
22073     * <dd>
22074     * The parent has determined an exact size for the child. The child is going to be
22075     * given those bounds regardless of how big it wants to be.
22076     * </dd>
22077     *
22078     * <dt>AT_MOST</dt>
22079     * <dd>
22080     * The child can be as large as it wants up to the specified size.
22081     * </dd>
22082     * </dl>
22083     *
22084     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22085     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22086     */
22087    public static class MeasureSpec {
22088        private static final int MODE_SHIFT = 30;
22089        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22090
22091        /** @hide */
22092        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22093        @Retention(RetentionPolicy.SOURCE)
22094        public @interface MeasureSpecMode {}
22095
22096        /**
22097         * Measure specification mode: The parent has not imposed any constraint
22098         * on the child. It can be whatever size it wants.
22099         */
22100        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22101
22102        /**
22103         * Measure specification mode: The parent has determined an exact size
22104         * for the child. The child is going to be given those bounds regardless
22105         * of how big it wants to be.
22106         */
22107        public static final int EXACTLY     = 1 << MODE_SHIFT;
22108
22109        /**
22110         * Measure specification mode: The child can be as large as it wants up
22111         * to the specified size.
22112         */
22113        public static final int AT_MOST     = 2 << MODE_SHIFT;
22114
22115        /**
22116         * Creates a measure specification based on the supplied size and mode.
22117         *
22118         * The mode must always be one of the following:
22119         * <ul>
22120         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22121         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22122         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22123         * </ul>
22124         *
22125         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22126         * implementation was such that the order of arguments did not matter
22127         * and overflow in either value could impact the resulting MeasureSpec.
22128         * {@link android.widget.RelativeLayout} was affected by this bug.
22129         * Apps targeting API levels greater than 17 will get the fixed, more strict
22130         * behavior.</p>
22131         *
22132         * @param size the size of the measure specification
22133         * @param mode the mode of the measure specification
22134         * @return the measure specification based on size and mode
22135         */
22136        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22137                                          @MeasureSpecMode int mode) {
22138            if (sUseBrokenMakeMeasureSpec) {
22139                return size + mode;
22140            } else {
22141                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22142            }
22143        }
22144
22145        /**
22146         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22147         * will automatically get a size of 0. Older apps expect this.
22148         *
22149         * @hide internal use only for compatibility with system widgets and older apps
22150         */
22151        public static int makeSafeMeasureSpec(int size, int mode) {
22152            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22153                return 0;
22154            }
22155            return makeMeasureSpec(size, mode);
22156        }
22157
22158        /**
22159         * Extracts the mode from the supplied measure specification.
22160         *
22161         * @param measureSpec the measure specification to extract the mode from
22162         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22163         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22164         *         {@link android.view.View.MeasureSpec#EXACTLY}
22165         */
22166        @MeasureSpecMode
22167        public static int getMode(int measureSpec) {
22168            //noinspection ResourceType
22169            return (measureSpec & MODE_MASK);
22170        }
22171
22172        /**
22173         * Extracts the size from the supplied measure specification.
22174         *
22175         * @param measureSpec the measure specification to extract the size from
22176         * @return the size in pixels defined in the supplied measure specification
22177         */
22178        public static int getSize(int measureSpec) {
22179            return (measureSpec & ~MODE_MASK);
22180        }
22181
22182        static int adjust(int measureSpec, int delta) {
22183            final int mode = getMode(measureSpec);
22184            int size = getSize(measureSpec);
22185            if (mode == UNSPECIFIED) {
22186                // No need to adjust size for UNSPECIFIED mode.
22187                return makeMeasureSpec(size, UNSPECIFIED);
22188            }
22189            size += delta;
22190            if (size < 0) {
22191                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22192                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22193                size = 0;
22194            }
22195            return makeMeasureSpec(size, mode);
22196        }
22197
22198        /**
22199         * Returns a String representation of the specified measure
22200         * specification.
22201         *
22202         * @param measureSpec the measure specification to convert to a String
22203         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22204         */
22205        public static String toString(int measureSpec) {
22206            int mode = getMode(measureSpec);
22207            int size = getSize(measureSpec);
22208
22209            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22210
22211            if (mode == UNSPECIFIED)
22212                sb.append("UNSPECIFIED ");
22213            else if (mode == EXACTLY)
22214                sb.append("EXACTLY ");
22215            else if (mode == AT_MOST)
22216                sb.append("AT_MOST ");
22217            else
22218                sb.append(mode).append(" ");
22219
22220            sb.append(size);
22221            return sb.toString();
22222        }
22223    }
22224
22225    private final class CheckForLongPress implements Runnable {
22226        private int mOriginalWindowAttachCount;
22227        private float mX;
22228        private float mY;
22229
22230        @Override
22231        public void run() {
22232            if (isPressed() && (mParent != null)
22233                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22234                if (performLongClick(mX, mY)) {
22235                    mHasPerformedLongPress = true;
22236                }
22237            }
22238        }
22239
22240        public void setAnchor(float x, float y) {
22241            mX = x;
22242            mY = y;
22243        }
22244
22245        public void rememberWindowAttachCount() {
22246            mOriginalWindowAttachCount = mWindowAttachCount;
22247        }
22248    }
22249
22250    private final class CheckForTap implements Runnable {
22251        public float x;
22252        public float y;
22253
22254        @Override
22255        public void run() {
22256            mPrivateFlags &= ~PFLAG_PREPRESSED;
22257            setPressed(true, x, y);
22258            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22259        }
22260    }
22261
22262    private final class PerformClick implements Runnable {
22263        @Override
22264        public void run() {
22265            performClick();
22266        }
22267    }
22268
22269    /**
22270     * This method returns a ViewPropertyAnimator object, which can be used to animate
22271     * specific properties on this View.
22272     *
22273     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22274     */
22275    public ViewPropertyAnimator animate() {
22276        if (mAnimator == null) {
22277            mAnimator = new ViewPropertyAnimator(this);
22278        }
22279        return mAnimator;
22280    }
22281
22282    /**
22283     * Sets the name of the View to be used to identify Views in Transitions.
22284     * Names should be unique in the View hierarchy.
22285     *
22286     * @param transitionName The name of the View to uniquely identify it for Transitions.
22287     */
22288    public final void setTransitionName(String transitionName) {
22289        mTransitionName = transitionName;
22290    }
22291
22292    /**
22293     * Returns the name of the View to be used to identify Views in Transitions.
22294     * Names should be unique in the View hierarchy.
22295     *
22296     * <p>This returns null if the View has not been given a name.</p>
22297     *
22298     * @return The name used of the View to be used to identify Views in Transitions or null
22299     * if no name has been given.
22300     */
22301    @ViewDebug.ExportedProperty
22302    public String getTransitionName() {
22303        return mTransitionName;
22304    }
22305
22306    /**
22307     * @hide
22308     */
22309    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22310        // Do nothing.
22311    }
22312
22313    /**
22314     * Interface definition for a callback to be invoked when a hardware key event is
22315     * dispatched to this view. The callback will be invoked before the key event is
22316     * given to the view. This is only useful for hardware keyboards; a software input
22317     * method has no obligation to trigger this listener.
22318     */
22319    public interface OnKeyListener {
22320        /**
22321         * Called when a hardware key is dispatched to a view. This allows listeners to
22322         * get a chance to respond before the target view.
22323         * <p>Key presses in software keyboards will generally NOT trigger this method,
22324         * although some may elect to do so in some situations. Do not assume a
22325         * software input method has to be key-based; even if it is, it may use key presses
22326         * in a different way than you expect, so there is no way to reliably catch soft
22327         * input key presses.
22328         *
22329         * @param v The view the key has been dispatched to.
22330         * @param keyCode The code for the physical key that was pressed
22331         * @param event The KeyEvent object containing full information about
22332         *        the event.
22333         * @return True if the listener has consumed the event, false otherwise.
22334         */
22335        boolean onKey(View v, int keyCode, KeyEvent event);
22336    }
22337
22338    /**
22339     * Interface definition for a callback to be invoked when a touch event is
22340     * dispatched to this view. The callback will be invoked before the touch
22341     * event is given to the view.
22342     */
22343    public interface OnTouchListener {
22344        /**
22345         * Called when a touch event is dispatched to a view. This allows listeners to
22346         * get a chance to respond before the target view.
22347         *
22348         * @param v The view the touch event has been dispatched to.
22349         * @param event The MotionEvent object containing full information about
22350         *        the event.
22351         * @return True if the listener has consumed the event, false otherwise.
22352         */
22353        boolean onTouch(View v, MotionEvent event);
22354    }
22355
22356    /**
22357     * Interface definition for a callback to be invoked when a hover event is
22358     * dispatched to this view. The callback will be invoked before the hover
22359     * event is given to the view.
22360     */
22361    public interface OnHoverListener {
22362        /**
22363         * Called when a hover event is dispatched to a view. This allows listeners to
22364         * get a chance to respond before the target view.
22365         *
22366         * @param v The view the hover event has been dispatched to.
22367         * @param event The MotionEvent object containing full information about
22368         *        the event.
22369         * @return True if the listener has consumed the event, false otherwise.
22370         */
22371        boolean onHover(View v, MotionEvent event);
22372    }
22373
22374    /**
22375     * Interface definition for a callback to be invoked when a generic motion event is
22376     * dispatched to this view. The callback will be invoked before the generic motion
22377     * event is given to the view.
22378     */
22379    public interface OnGenericMotionListener {
22380        /**
22381         * Called when a generic motion event is dispatched to a view. This allows listeners to
22382         * get a chance to respond before the target view.
22383         *
22384         * @param v The view the generic motion event has been dispatched to.
22385         * @param event The MotionEvent object containing full information about
22386         *        the event.
22387         * @return True if the listener has consumed the event, false otherwise.
22388         */
22389        boolean onGenericMotion(View v, MotionEvent event);
22390    }
22391
22392    /**
22393     * Interface definition for a callback to be invoked when a view has been clicked and held.
22394     */
22395    public interface OnLongClickListener {
22396        /**
22397         * Called when a view has been clicked and held.
22398         *
22399         * @param v The view that was clicked and held.
22400         *
22401         * @return true if the callback consumed the long click, false otherwise.
22402         */
22403        boolean onLongClick(View v);
22404    }
22405
22406    /**
22407     * Interface definition for a callback to be invoked when a drag is being dispatched
22408     * to this view.  The callback will be invoked before the hosting view's own
22409     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22410     * onDrag(event) behavior, it should return 'false' from this callback.
22411     *
22412     * <div class="special reference">
22413     * <h3>Developer Guides</h3>
22414     * <p>For a guide to implementing drag and drop features, read the
22415     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22416     * </div>
22417     */
22418    public interface OnDragListener {
22419        /**
22420         * Called when a drag event is dispatched to a view. This allows listeners
22421         * to get a chance to override base View behavior.
22422         *
22423         * @param v The View that received the drag event.
22424         * @param event The {@link android.view.DragEvent} object for the drag event.
22425         * @return {@code true} if the drag event was handled successfully, or {@code false}
22426         * if the drag event was not handled. Note that {@code false} will trigger the View
22427         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22428         */
22429        boolean onDrag(View v, DragEvent event);
22430    }
22431
22432    /**
22433     * Interface definition for a callback to be invoked when the focus state of
22434     * a view changed.
22435     */
22436    public interface OnFocusChangeListener {
22437        /**
22438         * Called when the focus state of a view has changed.
22439         *
22440         * @param v The view whose state has changed.
22441         * @param hasFocus The new focus state of v.
22442         */
22443        void onFocusChange(View v, boolean hasFocus);
22444    }
22445
22446    /**
22447     * Interface definition for a callback to be invoked when a view is clicked.
22448     */
22449    public interface OnClickListener {
22450        /**
22451         * Called when a view has been clicked.
22452         *
22453         * @param v The view that was clicked.
22454         */
22455        void onClick(View v);
22456    }
22457
22458    /**
22459     * Interface definition for a callback to be invoked when a view is context clicked.
22460     */
22461    public interface OnContextClickListener {
22462        /**
22463         * Called when a view is context clicked.
22464         *
22465         * @param v The view that has been context clicked.
22466         * @return true if the callback consumed the context click, false otherwise.
22467         */
22468        boolean onContextClick(View v);
22469    }
22470
22471    /**
22472     * Interface definition for a callback to be invoked when the context menu
22473     * for this view is being built.
22474     */
22475    public interface OnCreateContextMenuListener {
22476        /**
22477         * Called when the context menu for this view is being built. It is not
22478         * safe to hold onto the menu after this method returns.
22479         *
22480         * @param menu The context menu that is being built
22481         * @param v The view for which the context menu is being built
22482         * @param menuInfo Extra information about the item for which the
22483         *            context menu should be shown. This information will vary
22484         *            depending on the class of v.
22485         */
22486        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22487    }
22488
22489    /**
22490     * Interface definition for a callback to be invoked when the status bar changes
22491     * visibility.  This reports <strong>global</strong> changes to the system UI
22492     * state, not what the application is requesting.
22493     *
22494     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22495     */
22496    public interface OnSystemUiVisibilityChangeListener {
22497        /**
22498         * Called when the status bar changes visibility because of a call to
22499         * {@link View#setSystemUiVisibility(int)}.
22500         *
22501         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22502         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22503         * This tells you the <strong>global</strong> state of these UI visibility
22504         * flags, not what your app is currently applying.
22505         */
22506        public void onSystemUiVisibilityChange(int visibility);
22507    }
22508
22509    /**
22510     * Interface definition for a callback to be invoked when this view is attached
22511     * or detached from its window.
22512     */
22513    public interface OnAttachStateChangeListener {
22514        /**
22515         * Called when the view is attached to a window.
22516         * @param v The view that was attached
22517         */
22518        public void onViewAttachedToWindow(View v);
22519        /**
22520         * Called when the view is detached from a window.
22521         * @param v The view that was detached
22522         */
22523        public void onViewDetachedFromWindow(View v);
22524    }
22525
22526    /**
22527     * Listener for applying window insets on a view in a custom way.
22528     *
22529     * <p>Apps may choose to implement this interface if they want to apply custom policy
22530     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22531     * is set, its
22532     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22533     * method will be called instead of the View's own
22534     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22535     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22536     * the View's normal behavior as part of its own.</p>
22537     */
22538    public interface OnApplyWindowInsetsListener {
22539        /**
22540         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22541         * on a View, this listener method will be called instead of the view's own
22542         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22543         *
22544         * @param v The view applying window insets
22545         * @param insets The insets to apply
22546         * @return The insets supplied, minus any insets that were consumed
22547         */
22548        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22549    }
22550
22551    private final class UnsetPressedState implements Runnable {
22552        @Override
22553        public void run() {
22554            setPressed(false);
22555        }
22556    }
22557
22558    /**
22559     * Base class for derived classes that want to save and restore their own
22560     * state in {@link android.view.View#onSaveInstanceState()}.
22561     */
22562    public static class BaseSavedState extends AbsSavedState {
22563        String mStartActivityRequestWhoSaved;
22564
22565        /**
22566         * Constructor used when reading from a parcel. Reads the state of the superclass.
22567         *
22568         * @param source parcel to read from
22569         */
22570        public BaseSavedState(Parcel source) {
22571            this(source, null);
22572        }
22573
22574        /**
22575         * Constructor used when reading from a parcel using a given class loader.
22576         * Reads the state of the superclass.
22577         *
22578         * @param source parcel to read from
22579         * @param loader ClassLoader to use for reading
22580         */
22581        public BaseSavedState(Parcel source, ClassLoader loader) {
22582            super(source, loader);
22583            mStartActivityRequestWhoSaved = source.readString();
22584        }
22585
22586        /**
22587         * Constructor called by derived classes when creating their SavedState objects
22588         *
22589         * @param superState The state of the superclass of this view
22590         */
22591        public BaseSavedState(Parcelable superState) {
22592            super(superState);
22593        }
22594
22595        @Override
22596        public void writeToParcel(Parcel out, int flags) {
22597            super.writeToParcel(out, flags);
22598            out.writeString(mStartActivityRequestWhoSaved);
22599        }
22600
22601        public static final Parcelable.Creator<BaseSavedState> CREATOR
22602                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
22603            @Override
22604            public BaseSavedState createFromParcel(Parcel in) {
22605                return new BaseSavedState(in);
22606            }
22607
22608            @Override
22609            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
22610                return new BaseSavedState(in, loader);
22611            }
22612
22613            @Override
22614            public BaseSavedState[] newArray(int size) {
22615                return new BaseSavedState[size];
22616            }
22617        };
22618    }
22619
22620    /**
22621     * A set of information given to a view when it is attached to its parent
22622     * window.
22623     */
22624    final static class AttachInfo {
22625        interface Callbacks {
22626            void playSoundEffect(int effectId);
22627            boolean performHapticFeedback(int effectId, boolean always);
22628        }
22629
22630        /**
22631         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22632         * to a Handler. This class contains the target (View) to invalidate and
22633         * the coordinates of the dirty rectangle.
22634         *
22635         * For performance purposes, this class also implements a pool of up to
22636         * POOL_LIMIT objects that get reused. This reduces memory allocations
22637         * whenever possible.
22638         */
22639        static class InvalidateInfo {
22640            private static final int POOL_LIMIT = 10;
22641
22642            private static final SynchronizedPool<InvalidateInfo> sPool =
22643                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22644
22645            View target;
22646
22647            int left;
22648            int top;
22649            int right;
22650            int bottom;
22651
22652            public static InvalidateInfo obtain() {
22653                InvalidateInfo instance = sPool.acquire();
22654                return (instance != null) ? instance : new InvalidateInfo();
22655            }
22656
22657            public void recycle() {
22658                target = null;
22659                sPool.release(this);
22660            }
22661        }
22662
22663        final IWindowSession mSession;
22664
22665        final IWindow mWindow;
22666
22667        final IBinder mWindowToken;
22668
22669        final Display mDisplay;
22670
22671        final Callbacks mRootCallbacks;
22672
22673        IWindowId mIWindowId;
22674        WindowId mWindowId;
22675
22676        /**
22677         * The top view of the hierarchy.
22678         */
22679        View mRootView;
22680
22681        IBinder mPanelParentWindowToken;
22682
22683        boolean mHardwareAccelerated;
22684        boolean mHardwareAccelerationRequested;
22685        ThreadedRenderer mHardwareRenderer;
22686        List<RenderNode> mPendingAnimatingRenderNodes;
22687
22688        /**
22689         * The state of the display to which the window is attached, as reported
22690         * by {@link Display#getState()}.  Note that the display state constants
22691         * declared by {@link Display} do not exactly line up with the screen state
22692         * constants declared by {@link View} (there are more display states than
22693         * screen states).
22694         */
22695        int mDisplayState = Display.STATE_UNKNOWN;
22696
22697        /**
22698         * Scale factor used by the compatibility mode
22699         */
22700        float mApplicationScale;
22701
22702        /**
22703         * Indicates whether the application is in compatibility mode
22704         */
22705        boolean mScalingRequired;
22706
22707        /**
22708         * Left position of this view's window
22709         */
22710        int mWindowLeft;
22711
22712        /**
22713         * Top position of this view's window
22714         */
22715        int mWindowTop;
22716
22717        /**
22718         * Indicates whether views need to use 32-bit drawing caches
22719         */
22720        boolean mUse32BitDrawingCache;
22721
22722        /**
22723         * For windows that are full-screen but using insets to layout inside
22724         * of the screen areas, these are the current insets to appear inside
22725         * the overscan area of the display.
22726         */
22727        final Rect mOverscanInsets = new Rect();
22728
22729        /**
22730         * For windows that are full-screen but using insets to layout inside
22731         * of the screen decorations, these are the current insets for the
22732         * content of the window.
22733         */
22734        final Rect mContentInsets = new Rect();
22735
22736        /**
22737         * For windows that are full-screen but using insets to layout inside
22738         * of the screen decorations, these are the current insets for the
22739         * actual visible parts of the window.
22740         */
22741        final Rect mVisibleInsets = new Rect();
22742
22743        /**
22744         * For windows that are full-screen but using insets to layout inside
22745         * of the screen decorations, these are the current insets for the
22746         * stable system windows.
22747         */
22748        final Rect mStableInsets = new Rect();
22749
22750        /**
22751         * For windows that include areas that are not covered by real surface these are the outsets
22752         * for real surface.
22753         */
22754        final Rect mOutsets = new Rect();
22755
22756        /**
22757         * In multi-window we force show the navigation bar. Because we don't want that the surface
22758         * size changes in this mode, we instead have a flag whether the navigation bar size should
22759         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22760         */
22761        boolean mAlwaysConsumeNavBar;
22762
22763        /**
22764         * The internal insets given by this window.  This value is
22765         * supplied by the client (through
22766         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22767         * be given to the window manager when changed to be used in laying
22768         * out windows behind it.
22769         */
22770        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22771                = new ViewTreeObserver.InternalInsetsInfo();
22772
22773        /**
22774         * Set to true when mGivenInternalInsets is non-empty.
22775         */
22776        boolean mHasNonEmptyGivenInternalInsets;
22777
22778        /**
22779         * All views in the window's hierarchy that serve as scroll containers,
22780         * used to determine if the window can be resized or must be panned
22781         * to adjust for a soft input area.
22782         */
22783        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22784
22785        final KeyEvent.DispatcherState mKeyDispatchState
22786                = new KeyEvent.DispatcherState();
22787
22788        /**
22789         * Indicates whether the view's window currently has the focus.
22790         */
22791        boolean mHasWindowFocus;
22792
22793        /**
22794         * The current visibility of the window.
22795         */
22796        int mWindowVisibility;
22797
22798        /**
22799         * Indicates the time at which drawing started to occur.
22800         */
22801        long mDrawingTime;
22802
22803        /**
22804         * Indicates whether or not ignoring the DIRTY_MASK flags.
22805         */
22806        boolean mIgnoreDirtyState;
22807
22808        /**
22809         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22810         * to avoid clearing that flag prematurely.
22811         */
22812        boolean mSetIgnoreDirtyState = false;
22813
22814        /**
22815         * Indicates whether the view's window is currently in touch mode.
22816         */
22817        boolean mInTouchMode;
22818
22819        /**
22820         * Indicates whether the view has requested unbuffered input dispatching for the current
22821         * event stream.
22822         */
22823        boolean mUnbufferedDispatchRequested;
22824
22825        /**
22826         * Indicates that ViewAncestor should trigger a global layout change
22827         * the next time it performs a traversal
22828         */
22829        boolean mRecomputeGlobalAttributes;
22830
22831        /**
22832         * Always report new attributes at next traversal.
22833         */
22834        boolean mForceReportNewAttributes;
22835
22836        /**
22837         * Set during a traveral if any views want to keep the screen on.
22838         */
22839        boolean mKeepScreenOn;
22840
22841        /**
22842         * Set during a traveral if the light center needs to be updated.
22843         */
22844        boolean mNeedsUpdateLightCenter;
22845
22846        /**
22847         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22848         */
22849        int mSystemUiVisibility;
22850
22851        /**
22852         * Hack to force certain system UI visibility flags to be cleared.
22853         */
22854        int mDisabledSystemUiVisibility;
22855
22856        /**
22857         * Last global system UI visibility reported by the window manager.
22858         */
22859        int mGlobalSystemUiVisibility;
22860
22861        /**
22862         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22863         * attached.
22864         */
22865        boolean mHasSystemUiListeners;
22866
22867        /**
22868         * Set if the window has requested to extend into the overscan region
22869         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22870         */
22871        boolean mOverscanRequested;
22872
22873        /**
22874         * Set if the visibility of any views has changed.
22875         */
22876        boolean mViewVisibilityChanged;
22877
22878        /**
22879         * Set to true if a view has been scrolled.
22880         */
22881        boolean mViewScrollChanged;
22882
22883        /**
22884         * Set to true if high contrast mode enabled
22885         */
22886        boolean mHighContrastText;
22887
22888        /**
22889         * Set to true if a pointer event is currently being handled.
22890         */
22891        boolean mHandlingPointerEvent;
22892
22893        /**
22894         * Global to the view hierarchy used as a temporary for dealing with
22895         * x/y points in the transparent region computations.
22896         */
22897        final int[] mTransparentLocation = new int[2];
22898
22899        /**
22900         * Global to the view hierarchy used as a temporary for dealing with
22901         * x/y points in the ViewGroup.invalidateChild implementation.
22902         */
22903        final int[] mInvalidateChildLocation = new int[2];
22904
22905        /**
22906         * Global to the view hierarchy used as a temporary for dealng with
22907         * computing absolute on-screen location.
22908         */
22909        final int[] mTmpLocation = new int[2];
22910
22911        /**
22912         * Global to the view hierarchy used as a temporary for dealing with
22913         * x/y location when view is transformed.
22914         */
22915        final float[] mTmpTransformLocation = new float[2];
22916
22917        /**
22918         * The view tree observer used to dispatch global events like
22919         * layout, pre-draw, touch mode change, etc.
22920         */
22921        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
22922
22923        /**
22924         * A Canvas used by the view hierarchy to perform bitmap caching.
22925         */
22926        Canvas mCanvas;
22927
22928        /**
22929         * The view root impl.
22930         */
22931        final ViewRootImpl mViewRootImpl;
22932
22933        /**
22934         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
22935         * handler can be used to pump events in the UI events queue.
22936         */
22937        final Handler mHandler;
22938
22939        /**
22940         * Temporary for use in computing invalidate rectangles while
22941         * calling up the hierarchy.
22942         */
22943        final Rect mTmpInvalRect = new Rect();
22944
22945        /**
22946         * Temporary for use in computing hit areas with transformed views
22947         */
22948        final RectF mTmpTransformRect = new RectF();
22949
22950        /**
22951         * Temporary for use in computing hit areas with transformed views
22952         */
22953        final RectF mTmpTransformRect1 = new RectF();
22954
22955        /**
22956         * Temporary list of rectanges.
22957         */
22958        final List<RectF> mTmpRectList = new ArrayList<>();
22959
22960        /**
22961         * Temporary for use in transforming invalidation rect
22962         */
22963        final Matrix mTmpMatrix = new Matrix();
22964
22965        /**
22966         * Temporary for use in transforming invalidation rect
22967         */
22968        final Transformation mTmpTransformation = new Transformation();
22969
22970        /**
22971         * Temporary for use in querying outlines from OutlineProviders
22972         */
22973        final Outline mTmpOutline = new Outline();
22974
22975        /**
22976         * Temporary list for use in collecting focusable descendents of a view.
22977         */
22978        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
22979
22980        /**
22981         * The id of the window for accessibility purposes.
22982         */
22983        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
22984
22985        /**
22986         * Flags related to accessibility processing.
22987         *
22988         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
22989         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
22990         */
22991        int mAccessibilityFetchFlags;
22992
22993        /**
22994         * The drawable for highlighting accessibility focus.
22995         */
22996        Drawable mAccessibilityFocusDrawable;
22997
22998        /**
22999         * Show where the margins, bounds and layout bounds are for each view.
23000         */
23001        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23002
23003        /**
23004         * Point used to compute visible regions.
23005         */
23006        final Point mPoint = new Point();
23007
23008        /**
23009         * Used to track which View originated a requestLayout() call, used when
23010         * requestLayout() is called during layout.
23011         */
23012        View mViewRequestingLayout;
23013
23014        /**
23015         * Used to track views that need (at least) a partial relayout at their current size
23016         * during the next traversal.
23017         */
23018        List<View> mPartialLayoutViews = new ArrayList<>();
23019
23020        /**
23021         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23022         * modification. Lazily assigned during ViewRootImpl layout.
23023         */
23024        List<View> mEmptyPartialLayoutViews;
23025
23026        /**
23027         * Used to track the identity of the current drag operation.
23028         */
23029        IBinder mDragToken;
23030
23031        /**
23032         * The drag shadow surface for the current drag operation.
23033         */
23034        public Surface mDragSurface;
23035
23036        /**
23037         * Creates a new set of attachment information with the specified
23038         * events handler and thread.
23039         *
23040         * @param handler the events handler the view must use
23041         */
23042        AttachInfo(IWindowSession session, IWindow window, Display display,
23043                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
23044            mSession = session;
23045            mWindow = window;
23046            mWindowToken = window.asBinder();
23047            mDisplay = display;
23048            mViewRootImpl = viewRootImpl;
23049            mHandler = handler;
23050            mRootCallbacks = effectPlayer;
23051        }
23052    }
23053
23054    /**
23055     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23056     * is supported. This avoids keeping too many unused fields in most
23057     * instances of View.</p>
23058     */
23059    private static class ScrollabilityCache implements Runnable {
23060
23061        /**
23062         * Scrollbars are not visible
23063         */
23064        public static final int OFF = 0;
23065
23066        /**
23067         * Scrollbars are visible
23068         */
23069        public static final int ON = 1;
23070
23071        /**
23072         * Scrollbars are fading away
23073         */
23074        public static final int FADING = 2;
23075
23076        public boolean fadeScrollBars;
23077
23078        public int fadingEdgeLength;
23079        public int scrollBarDefaultDelayBeforeFade;
23080        public int scrollBarFadeDuration;
23081
23082        public int scrollBarSize;
23083        public ScrollBarDrawable scrollBar;
23084        public float[] interpolatorValues;
23085        public View host;
23086
23087        public final Paint paint;
23088        public final Matrix matrix;
23089        public Shader shader;
23090
23091        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23092
23093        private static final float[] OPAQUE = { 255 };
23094        private static final float[] TRANSPARENT = { 0.0f };
23095
23096        /**
23097         * When fading should start. This time moves into the future every time
23098         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23099         */
23100        public long fadeStartTime;
23101
23102
23103        /**
23104         * The current state of the scrollbars: ON, OFF, or FADING
23105         */
23106        public int state = OFF;
23107
23108        private int mLastColor;
23109
23110        public final Rect mScrollBarBounds = new Rect();
23111
23112        public static final int NOT_DRAGGING = 0;
23113        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23114        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23115        public int mScrollBarDraggingState = NOT_DRAGGING;
23116
23117        public float mScrollBarDraggingPos = 0;
23118
23119        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23120            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23121            scrollBarSize = configuration.getScaledScrollBarSize();
23122            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23123            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23124
23125            paint = new Paint();
23126            matrix = new Matrix();
23127            // use use a height of 1, and then wack the matrix each time we
23128            // actually use it.
23129            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23130            paint.setShader(shader);
23131            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23132
23133            this.host = host;
23134        }
23135
23136        public void setFadeColor(int color) {
23137            if (color != mLastColor) {
23138                mLastColor = color;
23139
23140                if (color != 0) {
23141                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23142                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23143                    paint.setShader(shader);
23144                    // Restore the default transfer mode (src_over)
23145                    paint.setXfermode(null);
23146                } else {
23147                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23148                    paint.setShader(shader);
23149                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23150                }
23151            }
23152        }
23153
23154        public void run() {
23155            long now = AnimationUtils.currentAnimationTimeMillis();
23156            if (now >= fadeStartTime) {
23157
23158                // the animation fades the scrollbars out by changing
23159                // the opacity (alpha) from fully opaque to fully
23160                // transparent
23161                int nextFrame = (int) now;
23162                int framesCount = 0;
23163
23164                Interpolator interpolator = scrollBarInterpolator;
23165
23166                // Start opaque
23167                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23168
23169                // End transparent
23170                nextFrame += scrollBarFadeDuration;
23171                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23172
23173                state = FADING;
23174
23175                // Kick off the fade animation
23176                host.invalidate(true);
23177            }
23178        }
23179    }
23180
23181    /**
23182     * Resuable callback for sending
23183     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23184     */
23185    private class SendViewScrolledAccessibilityEvent implements Runnable {
23186        public volatile boolean mIsPending;
23187
23188        public void run() {
23189            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23190            mIsPending = false;
23191        }
23192    }
23193
23194    /**
23195     * <p>
23196     * This class represents a delegate that can be registered in a {@link View}
23197     * to enhance accessibility support via composition rather via inheritance.
23198     * It is specifically targeted to widget developers that extend basic View
23199     * classes i.e. classes in package android.view, that would like their
23200     * applications to be backwards compatible.
23201     * </p>
23202     * <div class="special reference">
23203     * <h3>Developer Guides</h3>
23204     * <p>For more information about making applications accessible, read the
23205     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23206     * developer guide.</p>
23207     * </div>
23208     * <p>
23209     * A scenario in which a developer would like to use an accessibility delegate
23210     * is overriding a method introduced in a later API version then the minimal API
23211     * version supported by the application. For example, the method
23212     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23213     * in API version 4 when the accessibility APIs were first introduced. If a
23214     * developer would like his application to run on API version 4 devices (assuming
23215     * all other APIs used by the application are version 4 or lower) and take advantage
23216     * of this method, instead of overriding the method which would break the application's
23217     * backwards compatibility, he can override the corresponding method in this
23218     * delegate and register the delegate in the target View if the API version of
23219     * the system is high enough i.e. the API version is same or higher to the API
23220     * version that introduced
23221     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23222     * </p>
23223     * <p>
23224     * Here is an example implementation:
23225     * </p>
23226     * <code><pre><p>
23227     * if (Build.VERSION.SDK_INT >= 14) {
23228     *     // If the API version is equal of higher than the version in
23229     *     // which onInitializeAccessibilityNodeInfo was introduced we
23230     *     // register a delegate with a customized implementation.
23231     *     View view = findViewById(R.id.view_id);
23232     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23233     *         public void onInitializeAccessibilityNodeInfo(View host,
23234     *                 AccessibilityNodeInfo info) {
23235     *             // Let the default implementation populate the info.
23236     *             super.onInitializeAccessibilityNodeInfo(host, info);
23237     *             // Set some other information.
23238     *             info.setEnabled(host.isEnabled());
23239     *         }
23240     *     });
23241     * }
23242     * </code></pre></p>
23243     * <p>
23244     * This delegate contains methods that correspond to the accessibility methods
23245     * in View. If a delegate has been specified the implementation in View hands
23246     * off handling to the corresponding method in this delegate. The default
23247     * implementation the delegate methods behaves exactly as the corresponding
23248     * method in View for the case of no accessibility delegate been set. Hence,
23249     * to customize the behavior of a View method, clients can override only the
23250     * corresponding delegate method without altering the behavior of the rest
23251     * accessibility related methods of the host view.
23252     * </p>
23253     * <p>
23254     * <strong>Note:</strong> On platform versions prior to
23255     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23256     * views in the {@code android.widget.*} package are called <i>before</i>
23257     * host methods. This prevents certain properties such as class name from
23258     * being modified by overriding
23259     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23260     * as any changes will be overwritten by the host class.
23261     * <p>
23262     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23263     * methods are called <i>after</i> host methods, which all properties to be
23264     * modified without being overwritten by the host class.
23265     */
23266    public static class AccessibilityDelegate {
23267
23268        /**
23269         * Sends an accessibility event of the given type. If accessibility is not
23270         * enabled this method has no effect.
23271         * <p>
23272         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23273         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23274         * been set.
23275         * </p>
23276         *
23277         * @param host The View hosting the delegate.
23278         * @param eventType The type of the event to send.
23279         *
23280         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23281         */
23282        public void sendAccessibilityEvent(View host, int eventType) {
23283            host.sendAccessibilityEventInternal(eventType);
23284        }
23285
23286        /**
23287         * Performs the specified accessibility action on the view. For
23288         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23289         * <p>
23290         * The default implementation behaves as
23291         * {@link View#performAccessibilityAction(int, Bundle)
23292         *  View#performAccessibilityAction(int, Bundle)} for the case of
23293         *  no accessibility delegate been set.
23294         * </p>
23295         *
23296         * @param action The action to perform.
23297         * @return Whether the action was performed.
23298         *
23299         * @see View#performAccessibilityAction(int, Bundle)
23300         *      View#performAccessibilityAction(int, Bundle)
23301         */
23302        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23303            return host.performAccessibilityActionInternal(action, args);
23304        }
23305
23306        /**
23307         * Sends an accessibility event. This method behaves exactly as
23308         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23309         * empty {@link AccessibilityEvent} and does not perform a check whether
23310         * accessibility is enabled.
23311         * <p>
23312         * The default implementation behaves as
23313         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23314         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23315         * the case of no accessibility delegate been set.
23316         * </p>
23317         *
23318         * @param host The View hosting the delegate.
23319         * @param event The event to send.
23320         *
23321         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23322         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23323         */
23324        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23325            host.sendAccessibilityEventUncheckedInternal(event);
23326        }
23327
23328        /**
23329         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23330         * to its children for adding their text content to the event.
23331         * <p>
23332         * The default implementation behaves as
23333         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23334         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23335         * the case of no accessibility delegate been set.
23336         * </p>
23337         *
23338         * @param host The View hosting the delegate.
23339         * @param event The event.
23340         * @return True if the event population was completed.
23341         *
23342         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23343         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23344         */
23345        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23346            return host.dispatchPopulateAccessibilityEventInternal(event);
23347        }
23348
23349        /**
23350         * Gives a chance to the host View to populate the accessibility event with its
23351         * text content.
23352         * <p>
23353         * The default implementation behaves as
23354         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23355         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23356         * the case of no accessibility delegate been set.
23357         * </p>
23358         *
23359         * @param host The View hosting the delegate.
23360         * @param event The accessibility event which to populate.
23361         *
23362         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23363         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23364         */
23365        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23366            host.onPopulateAccessibilityEventInternal(event);
23367        }
23368
23369        /**
23370         * Initializes an {@link AccessibilityEvent} with information about the
23371         * the host View which is the event source.
23372         * <p>
23373         * The default implementation behaves as
23374         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23375         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23376         * the case of no accessibility delegate been set.
23377         * </p>
23378         *
23379         * @param host The View hosting the delegate.
23380         * @param event The event to initialize.
23381         *
23382         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23383         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23384         */
23385        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23386            host.onInitializeAccessibilityEventInternal(event);
23387        }
23388
23389        /**
23390         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23391         * <p>
23392         * The default implementation behaves as
23393         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23394         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23395         * the case of no accessibility delegate been set.
23396         * </p>
23397         *
23398         * @param host The View hosting the delegate.
23399         * @param info The instance to initialize.
23400         *
23401         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23402         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23403         */
23404        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23405            host.onInitializeAccessibilityNodeInfoInternal(info);
23406        }
23407
23408        /**
23409         * Called when a child of the host View has requested sending an
23410         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23411         * to augment the event.
23412         * <p>
23413         * The default implementation behaves as
23414         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23415         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23416         * the case of no accessibility delegate been set.
23417         * </p>
23418         *
23419         * @param host The View hosting the delegate.
23420         * @param child The child which requests sending the event.
23421         * @param event The event to be sent.
23422         * @return True if the event should be sent
23423         *
23424         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23425         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23426         */
23427        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23428                AccessibilityEvent event) {
23429            return host.onRequestSendAccessibilityEventInternal(child, event);
23430        }
23431
23432        /**
23433         * Gets the provider for managing a virtual view hierarchy rooted at this View
23434         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23435         * that explore the window content.
23436         * <p>
23437         * The default implementation behaves as
23438         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23439         * the case of no accessibility delegate been set.
23440         * </p>
23441         *
23442         * @return The provider.
23443         *
23444         * @see AccessibilityNodeProvider
23445         */
23446        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23447            return null;
23448        }
23449
23450        /**
23451         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23452         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23453         * This method is responsible for obtaining an accessibility node info from a
23454         * pool of reusable instances and calling
23455         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23456         * view to initialize the former.
23457         * <p>
23458         * <strong>Note:</strong> The client is responsible for recycling the obtained
23459         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23460         * creation.
23461         * </p>
23462         * <p>
23463         * The default implementation behaves as
23464         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23465         * the case of no accessibility delegate been set.
23466         * </p>
23467         * @return A populated {@link AccessibilityNodeInfo}.
23468         *
23469         * @see AccessibilityNodeInfo
23470         *
23471         * @hide
23472         */
23473        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23474            return host.createAccessibilityNodeInfoInternal();
23475        }
23476    }
23477
23478    private class MatchIdPredicate implements Predicate<View> {
23479        public int mId;
23480
23481        @Override
23482        public boolean apply(View view) {
23483            return (view.mID == mId);
23484        }
23485    }
23486
23487    private class MatchLabelForPredicate implements Predicate<View> {
23488        private int mLabeledId;
23489
23490        @Override
23491        public boolean apply(View view) {
23492            return (view.mLabelForId == mLabeledId);
23493        }
23494    }
23495
23496    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23497        private int mChangeTypes = 0;
23498        private boolean mPosted;
23499        private boolean mPostedWithDelay;
23500        private long mLastEventTimeMillis;
23501
23502        @Override
23503        public void run() {
23504            mPosted = false;
23505            mPostedWithDelay = false;
23506            mLastEventTimeMillis = SystemClock.uptimeMillis();
23507            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23508                final AccessibilityEvent event = AccessibilityEvent.obtain();
23509                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23510                event.setContentChangeTypes(mChangeTypes);
23511                sendAccessibilityEventUnchecked(event);
23512            }
23513            mChangeTypes = 0;
23514        }
23515
23516        public void runOrPost(int changeType) {
23517            mChangeTypes |= changeType;
23518
23519            // If this is a live region or the child of a live region, collect
23520            // all events from this frame and send them on the next frame.
23521            if (inLiveRegion()) {
23522                // If we're already posted with a delay, remove that.
23523                if (mPostedWithDelay) {
23524                    removeCallbacks(this);
23525                    mPostedWithDelay = false;
23526                }
23527                // Only post if we're not already posted.
23528                if (!mPosted) {
23529                    post(this);
23530                    mPosted = true;
23531                }
23532                return;
23533            }
23534
23535            if (mPosted) {
23536                return;
23537            }
23538
23539            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23540            final long minEventIntevalMillis =
23541                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23542            if (timeSinceLastMillis >= minEventIntevalMillis) {
23543                removeCallbacks(this);
23544                run();
23545            } else {
23546                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23547                mPostedWithDelay = true;
23548            }
23549        }
23550    }
23551
23552    private boolean inLiveRegion() {
23553        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23554            return true;
23555        }
23556
23557        ViewParent parent = getParent();
23558        while (parent instanceof View) {
23559            if (((View) parent).getAccessibilityLiveRegion()
23560                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23561                return true;
23562            }
23563            parent = parent.getParent();
23564        }
23565
23566        return false;
23567    }
23568
23569    /**
23570     * Dump all private flags in readable format, useful for documentation and
23571     * sanity checking.
23572     */
23573    private static void dumpFlags() {
23574        final HashMap<String, String> found = Maps.newHashMap();
23575        try {
23576            for (Field field : View.class.getDeclaredFields()) {
23577                final int modifiers = field.getModifiers();
23578                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23579                    if (field.getType().equals(int.class)) {
23580                        final int value = field.getInt(null);
23581                        dumpFlag(found, field.getName(), value);
23582                    } else if (field.getType().equals(int[].class)) {
23583                        final int[] values = (int[]) field.get(null);
23584                        for (int i = 0; i < values.length; i++) {
23585                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23586                        }
23587                    }
23588                }
23589            }
23590        } catch (IllegalAccessException e) {
23591            throw new RuntimeException(e);
23592        }
23593
23594        final ArrayList<String> keys = Lists.newArrayList();
23595        keys.addAll(found.keySet());
23596        Collections.sort(keys);
23597        for (String key : keys) {
23598            Log.d(VIEW_LOG_TAG, found.get(key));
23599        }
23600    }
23601
23602    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23603        // Sort flags by prefix, then by bits, always keeping unique keys
23604        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23605        final int prefix = name.indexOf('_');
23606        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23607        final String output = bits + " " + name;
23608        found.put(key, output);
23609    }
23610
23611    /** {@hide} */
23612    public void encode(@NonNull ViewHierarchyEncoder stream) {
23613        stream.beginObject(this);
23614        encodeProperties(stream);
23615        stream.endObject();
23616    }
23617
23618    /** {@hide} */
23619    @CallSuper
23620    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23621        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23622        if (resolveId instanceof String) {
23623            stream.addProperty("id", (String) resolveId);
23624        } else {
23625            stream.addProperty("id", mID);
23626        }
23627
23628        stream.addProperty("misc:transformation.alpha",
23629                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23630        stream.addProperty("misc:transitionName", getTransitionName());
23631
23632        // layout
23633        stream.addProperty("layout:left", mLeft);
23634        stream.addProperty("layout:right", mRight);
23635        stream.addProperty("layout:top", mTop);
23636        stream.addProperty("layout:bottom", mBottom);
23637        stream.addProperty("layout:width", getWidth());
23638        stream.addProperty("layout:height", getHeight());
23639        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23640        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23641        stream.addProperty("layout:hasTransientState", hasTransientState());
23642        stream.addProperty("layout:baseline", getBaseline());
23643
23644        // layout params
23645        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23646        if (layoutParams != null) {
23647            stream.addPropertyKey("layoutParams");
23648            layoutParams.encode(stream);
23649        }
23650
23651        // scrolling
23652        stream.addProperty("scrolling:scrollX", mScrollX);
23653        stream.addProperty("scrolling:scrollY", mScrollY);
23654
23655        // padding
23656        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23657        stream.addProperty("padding:paddingRight", mPaddingRight);
23658        stream.addProperty("padding:paddingTop", mPaddingTop);
23659        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23660        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23661        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23662        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23663        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23664        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23665
23666        // measurement
23667        stream.addProperty("measurement:minHeight", mMinHeight);
23668        stream.addProperty("measurement:minWidth", mMinWidth);
23669        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23670        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23671
23672        // drawing
23673        stream.addProperty("drawing:elevation", getElevation());
23674        stream.addProperty("drawing:translationX", getTranslationX());
23675        stream.addProperty("drawing:translationY", getTranslationY());
23676        stream.addProperty("drawing:translationZ", getTranslationZ());
23677        stream.addProperty("drawing:rotation", getRotation());
23678        stream.addProperty("drawing:rotationX", getRotationX());
23679        stream.addProperty("drawing:rotationY", getRotationY());
23680        stream.addProperty("drawing:scaleX", getScaleX());
23681        stream.addProperty("drawing:scaleY", getScaleY());
23682        stream.addProperty("drawing:pivotX", getPivotX());
23683        stream.addProperty("drawing:pivotY", getPivotY());
23684        stream.addProperty("drawing:opaque", isOpaque());
23685        stream.addProperty("drawing:alpha", getAlpha());
23686        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23687        stream.addProperty("drawing:shadow", hasShadow());
23688        stream.addProperty("drawing:solidColor", getSolidColor());
23689        stream.addProperty("drawing:layerType", mLayerType);
23690        stream.addProperty("drawing:willNotDraw", willNotDraw());
23691        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23692        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23693        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23694        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23695
23696        // focus
23697        stream.addProperty("focus:hasFocus", hasFocus());
23698        stream.addProperty("focus:isFocused", isFocused());
23699        stream.addProperty("focus:isFocusable", isFocusable());
23700        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23701
23702        stream.addProperty("misc:clickable", isClickable());
23703        stream.addProperty("misc:pressed", isPressed());
23704        stream.addProperty("misc:selected", isSelected());
23705        stream.addProperty("misc:touchMode", isInTouchMode());
23706        stream.addProperty("misc:hovered", isHovered());
23707        stream.addProperty("misc:activated", isActivated());
23708
23709        stream.addProperty("misc:visibility", getVisibility());
23710        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23711        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23712
23713        stream.addProperty("misc:enabled", isEnabled());
23714        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23715        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23716
23717        // theme attributes
23718        Resources.Theme theme = getContext().getTheme();
23719        if (theme != null) {
23720            stream.addPropertyKey("theme");
23721            theme.encode(stream);
23722        }
23723
23724        // view attribute information
23725        int n = mAttributes != null ? mAttributes.length : 0;
23726        stream.addProperty("meta:__attrCount__", n/2);
23727        for (int i = 0; i < n; i += 2) {
23728            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23729        }
23730
23731        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23732
23733        // text
23734        stream.addProperty("text:textDirection", getTextDirection());
23735        stream.addProperty("text:textAlignment", getTextAlignment());
23736
23737        // accessibility
23738        CharSequence contentDescription = getContentDescription();
23739        stream.addProperty("accessibility:contentDescription",
23740                contentDescription == null ? "" : contentDescription.toString());
23741        stream.addProperty("accessibility:labelFor", getLabelFor());
23742        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23743    }
23744}
23745