View.java revision cfa6dade73070ef27683303ae88c2b7479ae6b03
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.IntRange;
28import android.annotation.LayoutRes;
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.annotation.Size;
32import android.annotation.UiThread;
33import android.content.ClipData;
34import android.content.Context;
35import android.content.ContextWrapper;
36import android.content.Intent;
37import android.content.res.ColorStateList;
38import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Insets;
44import android.graphics.Interpolator;
45import android.graphics.LinearGradient;
46import android.graphics.Matrix;
47import android.graphics.Outline;
48import android.graphics.Paint;
49import android.graphics.PixelFormat;
50import android.graphics.Point;
51import android.graphics.PorterDuff;
52import android.graphics.PorterDuffXfermode;
53import android.graphics.Rect;
54import android.graphics.RectF;
55import android.graphics.Region;
56import android.graphics.Shader;
57import android.graphics.drawable.ColorDrawable;
58import android.graphics.drawable.Drawable;
59import android.hardware.display.DisplayManagerGlobal;
60import android.os.Build.VERSION_CODES;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Parcel;
65import android.os.Parcelable;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.SystemProperties;
69import android.os.Trace;
70import android.text.TextUtils;
71import android.util.AttributeSet;
72import android.util.FloatProperty;
73import android.util.LayoutDirection;
74import android.util.Log;
75import android.util.LongSparseLongArray;
76import android.util.Pools.SynchronizedPool;
77import android.util.Property;
78import android.util.SparseArray;
79import android.util.StateSet;
80import android.util.SuperNotCalledException;
81import android.util.TypedValue;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.AccessibilityIterators.TextSegmentIterator;
86import android.view.AccessibilityIterators.WordTextSegmentIterator;
87import android.view.accessibility.AccessibilityEvent;
88import android.view.accessibility.AccessibilityEventSource;
89import android.view.accessibility.AccessibilityManager;
90import android.view.accessibility.AccessibilityNodeInfo;
91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
92import android.view.accessibility.AccessibilityNodeProvider;
93import android.view.animation.Animation;
94import android.view.animation.AnimationUtils;
95import android.view.animation.Transformation;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputConnection;
98import android.view.inputmethod.InputMethodManager;
99import android.widget.Checkable;
100import android.widget.FrameLayout;
101import android.widget.ScrollBarDrawable;
102import static android.os.Build.VERSION_CODES.*;
103import static java.lang.Math.max;
104
105import com.android.internal.R;
106import com.android.internal.util.Predicate;
107import com.android.internal.view.menu.MenuBuilder;
108import com.android.internal.widget.ScrollBarUtils;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.NullPointerException;
113import java.lang.annotation.Retention;
114import java.lang.annotation.RetentionPolicy;
115import java.lang.ref.WeakReference;
116import java.lang.reflect.Field;
117import java.lang.reflect.InvocationTargetException;
118import java.lang.reflect.Method;
119import java.lang.reflect.Modifier;
120import java.util.ArrayList;
121import java.util.Arrays;
122import java.util.Collections;
123import java.util.HashMap;
124import java.util.List;
125import java.util.Locale;
126import java.util.Map;
127import java.util.concurrent.CopyOnWriteArrayList;
128import java.util.concurrent.atomic.AtomicInteger;
129
130/**
131 * <p>
132 * This class represents the basic building block for user interface components. A View
133 * occupies a rectangular area on the screen and is responsible for drawing and
134 * event handling. View is the base class for <em>widgets</em>, which are
135 * used to create interactive UI components (buttons, text fields, etc.). The
136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
137 * are invisible containers that hold other Views (or other ViewGroups) and define
138 * their layout properties.
139 * </p>
140 *
141 * <div class="special reference">
142 * <h3>Developer Guides</h3>
143 * <p>For information about using this class to develop your application's user interface,
144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
145 * </div>
146 *
147 * <a name="Using"></a>
148 * <h3>Using Views</h3>
149 * <p>
150 * All of the views in a window are arranged in a single tree. You can add views
151 * either from code or by specifying a tree of views in one or more XML layout
152 * files. There are many specialized subclasses of views that act as controls or
153 * are capable of displaying text, images, or other content.
154 * </p>
155 * <p>
156 * Once you have created a tree of views, there are typically a few types of
157 * common operations you may wish to perform:
158 * <ul>
159 * <li><strong>Set properties:</strong> for example setting the text of a
160 * {@link android.widget.TextView}. The available properties and the methods
161 * that set them will vary among the different subclasses of views. Note that
162 * properties that are known at build time can be set in the XML layout
163 * files.</li>
164 * <li><strong>Set focus:</strong> The framework will handled moving focus in
165 * response to user input. To force focus to a specific view, call
166 * {@link #requestFocus}.</li>
167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
168 * that will be notified when something interesting happens to the view. For
169 * example, all views will let you set a listener to be notified when the view
170 * gains or loses focus. You can register such a listener using
171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
172 * Other view subclasses offer more specialized listeners. For example, a Button
173 * exposes a listener to notify clients when the button is clicked.</li>
174 * <li><strong>Set visibility:</strong> You can hide or show views using
175 * {@link #setVisibility(int)}.</li>
176 * </ul>
177 * </p>
178 * <p><em>
179 * Note: The Android framework is responsible for measuring, laying out and
180 * drawing views. You should not call methods that perform these actions on
181 * views yourself unless you are actually implementing a
182 * {@link android.view.ViewGroup}.
183 * </em></p>
184 *
185 * <a name="Lifecycle"></a>
186 * <h3>Implementing a Custom View</h3>
187 *
188 * <p>
189 * To implement a custom view, you will usually begin by providing overrides for
190 * some of the standard methods that the framework calls on all views. You do
191 * not need to override all of these methods. In fact, you can start by just
192 * overriding {@link #onDraw(android.graphics.Canvas)}.
193 * <table border="2" width="85%" align="center" cellpadding="5">
194 *     <thead>
195 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
196 *     </thead>
197 *
198 *     <tbody>
199 *     <tr>
200 *         <td rowspan="2">Creation</td>
201 *         <td>Constructors</td>
202 *         <td>There is a form of the constructor that are called when the view
203 *         is created from code and a form that is called when the view is
204 *         inflated from a layout file. The second form should parse and apply
205 *         any attributes defined in the layout file.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onFinishInflate()}</code></td>
210 *         <td>Called after a view and all of its children has been inflated
211 *         from XML.</td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td rowspan="3">Layout</td>
216 *         <td><code>{@link #onMeasure(int, int)}</code></td>
217 *         <td>Called to determine the size requirements for this view and all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
223 *         <td>Called when this view should assign a size and position to all
224 *         of its children.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
229 *         <td>Called when the size of this view has changed.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td>Drawing</td>
235 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
236 *         <td>Called when the view should render its content.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="4">Event processing</td>
242 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
243 *         <td>Called when a new hardware key event occurs.
244 *         </td>
245 *     </tr>
246 *     <tr>
247 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
248 *         <td>Called when a hardware key up event occurs.
249 *         </td>
250 *     </tr>
251 *     <tr>
252 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
253 *         <td>Called when a trackball motion event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
258 *         <td>Called when a touch screen motion event occurs.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td rowspan="2">Focus</td>
264 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
265 *         <td>Called when the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
271 *         <td>Called when the window containing the view gains or loses focus.
272 *         </td>
273 *     </tr>
274 *
275 *     <tr>
276 *         <td rowspan="3">Attaching</td>
277 *         <td><code>{@link #onAttachedToWindow()}</code></td>
278 *         <td>Called when the view is attached to a window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onDetachedFromWindow}</code></td>
284 *         <td>Called when the view is detached from its window.
285 *         </td>
286 *     </tr>
287 *
288 *     <tr>
289 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
290 *         <td>Called when the visibility of the window containing the view
291 *         has changed.
292 *         </td>
293 *     </tr>
294 *     </tbody>
295 *
296 * </table>
297 * </p>
298 *
299 * <a name="IDs"></a>
300 * <h3>IDs</h3>
301 * Views may have an integer id associated with them. These ids are typically
302 * assigned in the layout XML files, and are used to find specific views within
303 * the view tree. A common pattern is to:
304 * <ul>
305 * <li>Define a Button in the layout file and assign it a unique ID.
306 * <pre>
307 * &lt;Button
308 *     android:id="@+id/my_button"
309 *     android:layout_width="wrap_content"
310 *     android:layout_height="wrap_content"
311 *     android:text="@string/my_button_text"/&gt;
312 * </pre></li>
313 * <li>From the onCreate method of an Activity, find the Button
314 * <pre class="prettyprint">
315 *      Button myButton = (Button) findViewById(R.id.my_button);
316 * </pre></li>
317 * </ul>
318 * <p>
319 * View IDs need not be unique throughout the tree, but it is good practice to
320 * ensure that they are at least unique within the part of the tree you are
321 * searching.
322 * </p>
323 *
324 * <a name="Position"></a>
325 * <h3>Position</h3>
326 * <p>
327 * The geometry of a view is that of a rectangle. A view has a location,
328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
329 * two dimensions, expressed as a width and a height. The unit for location
330 * and dimensions is the pixel.
331 * </p>
332 *
333 * <p>
334 * It is possible to retrieve the location of a view by invoking the methods
335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
336 * coordinate of the rectangle representing the view. The latter returns the
337 * top, or Y, coordinate of the rectangle representing the view. These methods
338 * both return the location of the view relative to its parent. For instance,
339 * when getLeft() returns 20, that means the view is located 20 pixels to the
340 * right of the left edge of its direct parent.
341 * </p>
342 *
343 * <p>
344 * In addition, several convenience methods are offered to avoid unnecessary
345 * computations, namely {@link #getRight()} and {@link #getBottom()}.
346 * These methods return the coordinates of the right and bottom edges of the
347 * rectangle representing the view. For instance, calling {@link #getRight()}
348 * is similar to the following computation: <code>getLeft() + getWidth()</code>
349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
350 * </p>
351 *
352 * <a name="SizePaddingMargins"></a>
353 * <h3>Size, padding and margins</h3>
354 * <p>
355 * The size of a view is expressed with a width and a height. A view actually
356 * possess two pairs of width and height values.
357 * </p>
358 *
359 * <p>
360 * The first pair is known as <em>measured width</em> and
361 * <em>measured height</em>. These dimensions define how big a view wants to be
362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
364 * and {@link #getMeasuredHeight()}.
365 * </p>
366 *
367 * <p>
368 * The second pair is simply known as <em>width</em> and <em>height</em>, or
369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
370 * dimensions define the actual size of the view on screen, at drawing time and
371 * after layout. These values may, but do not have to, be different from the
372 * measured width and height. The width and height can be obtained by calling
373 * {@link #getWidth()} and {@link #getHeight()}.
374 * </p>
375 *
376 * <p>
377 * To measure its dimensions, a view takes into account its padding. The padding
378 * is expressed in pixels for the left, top, right and bottom parts of the view.
379 * Padding can be used to offset the content of the view by a specific amount of
380 * pixels. For instance, a left padding of 2 will push the view's content by
381 * 2 pixels to the right of the left edge. Padding can be set using the
382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
385 * {@link #getPaddingEnd()}.
386 * </p>
387 *
388 * <p>
389 * Even though a view can define a padding, it does not provide any support for
390 * margins. However, view groups provide such a support. Refer to
391 * {@link android.view.ViewGroup} and
392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
393 * </p>
394 *
395 * <a name="Layout"></a>
396 * <h3>Layout</h3>
397 * <p>
398 * Layout is a two pass process: a measure pass and a layout pass. The measuring
399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
400 * of the view tree. Each view pushes dimension specifications down the tree
401 * during the recursion. At the end of the measure pass, every view has stored
402 * its measurements. The second pass happens in
403 * {@link #layout(int,int,int,int)} and is also top-down. During
404 * this pass each parent is responsible for positioning all of its children
405 * using the sizes computed in the measure pass.
406 * </p>
407 *
408 * <p>
409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
410 * {@link #getMeasuredHeight()} values must be set, along with those for all of
411 * that view's descendants. A view's measured width and measured height values
412 * must respect the constraints imposed by the view's parents. This guarantees
413 * that at the end of the measure pass, all parents accept all of their
414 * children's measurements. A parent view may call measure() more than once on
415 * its children. For example, the parent may measure each child once with
416 * unspecified dimensions to find out how big they want to be, then call
417 * measure() on them again with actual numbers if the sum of all the children's
418 * unconstrained sizes is too big or too small.
419 * </p>
420 *
421 * <p>
422 * The measure pass uses two classes to communicate dimensions. The
423 * {@link MeasureSpec} class is used by views to tell their parents how they
424 * want to be measured and positioned. The base LayoutParams class just
425 * describes how big the view wants to be for both width and height. For each
426 * dimension, it can specify one of:
427 * <ul>
428 * <li> an exact number
429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
430 * (minus padding)
431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
432 * enclose its content (plus padding).
433 * </ul>
434 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
436 * an X and Y value.
437 * </p>
438 *
439 * <p>
440 * MeasureSpecs are used to push requirements down the tree from parent to
441 * child. A MeasureSpec can be in one of three modes:
442 * <ul>
443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
444 * of a child view. For example, a LinearLayout may call measure() on its child
445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
446 * tall the child view wants to be given a width of 240 pixels.
447 * <li>EXACTLY: This is used by the parent to impose an exact size on the
448 * child. The child must use this size, and guarantee that all of its
449 * descendants will fit within this size.
450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
451 * child. The child must guarantee that it and all of its descendants will fit
452 * within this size.
453 * </ul>
454 * </p>
455 *
456 * <p>
457 * To initiate a layout, call {@link #requestLayout}. This method is typically
458 * called by a view on itself when it believes that is can no longer fit within
459 * its current bounds.
460 * </p>
461 *
462 * <a name="Drawing"></a>
463 * <h3>Drawing</h3>
464 * <p>
465 * Drawing is handled by walking the tree and recording the drawing commands of
466 * any View that needs to update. After this, the drawing commands of the
467 * entire tree are issued to screen, clipped to the newly damaged area.
468 * </p>
469 *
470 * <p>
471 * The tree is largely recorded and drawn in order, with parents drawn before
472 * (i.e., behind) their children, with siblings drawn in the order they appear
473 * in the tree. If you set a background drawable for a View, then the View will
474 * draw it before calling back to its <code>onDraw()</code> method. The child
475 * drawing order can be overridden with
476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
478 * </p>
479 *
480 * <p>
481 * To force a view to draw, call {@link #invalidate()}.
482 * </p>
483 *
484 * <a name="EventHandlingThreading"></a>
485 * <h3>Event Handling and Threading</h3>
486 * <p>
487 * The basic cycle of a view is as follows:
488 * <ol>
489 * <li>An event comes in and is dispatched to the appropriate view. The view
490 * handles the event and notifies any listeners.</li>
491 * <li>If in the course of processing the event, the view's bounds may need
492 * to be changed, the view will call {@link #requestLayout()}.</li>
493 * <li>Similarly, if in the course of processing the event the view's appearance
494 * may need to be changed, the view will call {@link #invalidate()}.</li>
495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
496 * the framework will take care of measuring, laying out, and drawing the tree
497 * as appropriate.</li>
498 * </ol>
499 * </p>
500 *
501 * <p><em>Note: The entire view tree is single threaded. You must always be on
502 * the UI thread when calling any method on any view.</em>
503 * If you are doing work on other threads and want to update the state of a view
504 * from that thread, you should use a {@link Handler}.
505 * </p>
506 *
507 * <a name="FocusHandling"></a>
508 * <h3>Focus Handling</h3>
509 * <p>
510 * The framework will handle routine focus movement in response to user input.
511 * This includes changing the focus as views are removed or hidden, or as new
512 * views become available. Views indicate their willingness to take focus
513 * through the {@link #isFocusable} method. To change whether a view can take
514 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
516 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
517 * </p>
518 * <p>
519 * Focus movement is based on an algorithm which finds the nearest neighbor in a
520 * given direction. In rare cases, the default algorithm may not match the
521 * intended behavior of the developer. In these situations, you can provide
522 * explicit overrides by using these XML attributes in the layout file:
523 * <pre>
524 * nextFocusDown
525 * nextFocusLeft
526 * nextFocusRight
527 * nextFocusUp
528 * </pre>
529 * </p>
530 *
531 *
532 * <p>
533 * To get a particular view to take focus, call {@link #requestFocus()}.
534 * </p>
535 *
536 * <a name="TouchMode"></a>
537 * <h3>Touch Mode</h3>
538 * <p>
539 * When a user is navigating a user interface via directional keys such as a D-pad, it is
540 * necessary to give focus to actionable items such as buttons so the user can see
541 * what will take input.  If the device has touch capabilities, however, and the user
542 * begins interacting with the interface by touching it, it is no longer necessary to
543 * always highlight, or give focus to, a particular view.  This motivates a mode
544 * for interaction named 'touch mode'.
545 * </p>
546 * <p>
547 * For a touch capable device, once the user touches the screen, the device
548 * will enter touch mode.  From this point onward, only views for which
549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
550 * Other views that are touchable, like buttons, will not take focus when touched; they will
551 * only fire the on click listeners.
552 * </p>
553 * <p>
554 * Any time a user hits a directional key, such as a D-pad direction, the view device will
555 * exit touch mode, and find a view to take focus, so that the user may resume interacting
556 * with the user interface without touching the screen again.
557 * </p>
558 * <p>
559 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
560 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
561 * </p>
562 *
563 * <a name="Scrolling"></a>
564 * <h3>Scrolling</h3>
565 * <p>
566 * The framework provides basic support for views that wish to internally
567 * scroll their content. This includes keeping track of the X and Y scroll
568 * offset as well as mechanisms for drawing scrollbars. See
569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
570 * {@link #awakenScrollBars()} for more details.
571 * </p>
572 *
573 * <a name="Tags"></a>
574 * <h3>Tags</h3>
575 * <p>
576 * Unlike IDs, tags are not used to identify views. Tags are essentially an
577 * extra piece of information that can be associated with a view. They are most
578 * often used as a convenience to store data related to views in the views
579 * themselves rather than by putting them in a separate structure.
580 * </p>
581 * <p>
582 * Tags may be specified with character sequence values in layout XML as either
583 * a single tag using the {@link android.R.styleable#View_tag android:tag}
584 * attribute or multiple tags using the {@code <tag>} child element:
585 * <pre>
586 *     &ltView ...
587 *           android:tag="@string/mytag_value" /&gt;
588 *     &ltView ...&gt;
589 *         &lttag android:id="@+id/mytag"
590 *              android:value="@string/mytag_value" /&gt;
591 *     &lt/View>
592 * </pre>
593 * </p>
594 * <p>
595 * Tags may also be specified with arbitrary objects from code using
596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
597 * </p>
598 *
599 * <a name="Themes"></a>
600 * <h3>Themes</h3>
601 * <p>
602 * By default, Views are created using the theme of the Context object supplied
603 * to their constructor; however, a different theme may be specified by using
604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
606 * code.
607 * </p>
608 * <p>
609 * When the {@link android.R.styleable#View_theme android:theme} attribute is
610 * used in XML, the specified theme is applied on top of the inflation
611 * context's theme (see {@link LayoutInflater}) and used for the view itself as
612 * well as any child elements.
613 * </p>
614 * <p>
615 * In the following example, both views will be created using the Material dark
616 * color scheme; however, because an overlay theme is used which only defines a
617 * subset of attributes, the value of
618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
619 * the inflation context's theme (e.g. the Activity theme) will be preserved.
620 * <pre>
621 *     &ltLinearLayout
622 *             ...
623 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
624 *         &ltView ...&gt;
625 *     &lt/LinearLayout&gt;
626 * </pre>
627 * </p>
628 *
629 * <a name="Properties"></a>
630 * <h3>Properties</h3>
631 * <p>
632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
634 * available both in the {@link Property} form as well as in similarly-named setter/getter
635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
636 * be used to set persistent state associated with these rendering-related properties on the view.
637 * The properties and methods can also be used in conjunction with
638 * {@link android.animation.Animator Animator}-based animations, described more in the
639 * <a href="#Animation">Animation</a> section.
640 * </p>
641 *
642 * <a name="Animation"></a>
643 * <h3>Animation</h3>
644 * <p>
645 * Starting with Android 3.0, the preferred way of animating views is to use the
646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
651 * makes animating these View properties particularly easy and efficient.
652 * </p>
653 * <p>
654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
655 * You can attach an {@link Animation} object to a view using
656 * {@link #setAnimation(Animation)} or
657 * {@link #startAnimation(Animation)}. The animation can alter the scale,
658 * rotation, translation and alpha of a view over time. If the animation is
659 * attached to a view that has children, the animation will affect the entire
660 * subtree rooted by that node. When an animation is started, the framework will
661 * take care of redrawing the appropriate views until the animation completes.
662 * </p>
663 *
664 * <a name="Security"></a>
665 * <h3>Security</h3>
666 * <p>
667 * Sometimes it is essential that an application be able to verify that an action
668 * is being performed with the full knowledge and consent of the user, such as
669 * granting a permission request, making a purchase or clicking on an advertisement.
670 * Unfortunately, a malicious application could try to spoof the user into
671 * performing these actions, unaware, by concealing the intended purpose of the view.
672 * As a remedy, the framework offers a touch filtering mechanism that can be used to
673 * improve the security of views that provide access to sensitive functionality.
674 * </p><p>
675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
676 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
677 * will discard touches that are received whenever the view's window is obscured by
678 * another visible window.  As a result, the view will not receive touches whenever a
679 * toast, dialog or other window appears above the view's window.
680 * </p><p>
681 * For more fine-grained control over security, consider overriding the
682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
684 * </p>
685 *
686 * @attr ref android.R.styleable#View_alpha
687 * @attr ref android.R.styleable#View_background
688 * @attr ref android.R.styleable#View_clickable
689 * @attr ref android.R.styleable#View_contentDescription
690 * @attr ref android.R.styleable#View_drawingCacheQuality
691 * @attr ref android.R.styleable#View_duplicateParentState
692 * @attr ref android.R.styleable#View_id
693 * @attr ref android.R.styleable#View_requiresFadingEdge
694 * @attr ref android.R.styleable#View_fadeScrollbars
695 * @attr ref android.R.styleable#View_fadingEdgeLength
696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
697 * @attr ref android.R.styleable#View_fitsSystemWindows
698 * @attr ref android.R.styleable#View_isScrollContainer
699 * @attr ref android.R.styleable#View_focusable
700 * @attr ref android.R.styleable#View_focusableInTouchMode
701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
702 * @attr ref android.R.styleable#View_keepScreenOn
703 * @attr ref android.R.styleable#View_layerType
704 * @attr ref android.R.styleable#View_layoutDirection
705 * @attr ref android.R.styleable#View_longClickable
706 * @attr ref android.R.styleable#View_minHeight
707 * @attr ref android.R.styleable#View_minWidth
708 * @attr ref android.R.styleable#View_nextFocusDown
709 * @attr ref android.R.styleable#View_nextFocusLeft
710 * @attr ref android.R.styleable#View_nextFocusRight
711 * @attr ref android.R.styleable#View_nextFocusUp
712 * @attr ref android.R.styleable#View_onClick
713 * @attr ref android.R.styleable#View_padding
714 * @attr ref android.R.styleable#View_paddingBottom
715 * @attr ref android.R.styleable#View_paddingLeft
716 * @attr ref android.R.styleable#View_paddingRight
717 * @attr ref android.R.styleable#View_paddingTop
718 * @attr ref android.R.styleable#View_paddingStart
719 * @attr ref android.R.styleable#View_paddingEnd
720 * @attr ref android.R.styleable#View_saveEnabled
721 * @attr ref android.R.styleable#View_rotation
722 * @attr ref android.R.styleable#View_rotationX
723 * @attr ref android.R.styleable#View_rotationY
724 * @attr ref android.R.styleable#View_scaleX
725 * @attr ref android.R.styleable#View_scaleY
726 * @attr ref android.R.styleable#View_scrollX
727 * @attr ref android.R.styleable#View_scrollY
728 * @attr ref android.R.styleable#View_scrollbarSize
729 * @attr ref android.R.styleable#View_scrollbarStyle
730 * @attr ref android.R.styleable#View_scrollbars
731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
732 * @attr ref android.R.styleable#View_scrollbarFadeDuration
733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbVertical
736 * @attr ref android.R.styleable#View_scrollbarTrackVertical
737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
739 * @attr ref android.R.styleable#View_stateListAnimator
740 * @attr ref android.R.styleable#View_transitionName
741 * @attr ref android.R.styleable#View_soundEffectsEnabled
742 * @attr ref android.R.styleable#View_tag
743 * @attr ref android.R.styleable#View_textAlignment
744 * @attr ref android.R.styleable#View_textDirection
745 * @attr ref android.R.styleable#View_transformPivotX
746 * @attr ref android.R.styleable#View_transformPivotY
747 * @attr ref android.R.styleable#View_translationX
748 * @attr ref android.R.styleable#View_translationY
749 * @attr ref android.R.styleable#View_translationZ
750 * @attr ref android.R.styleable#View_visibility
751 * @attr ref android.R.styleable#View_theme
752 *
753 * @see android.view.ViewGroup
754 */
755@UiThread
756public class View implements Drawable.Callback, KeyEvent.Callback,
757        AccessibilityEventSource {
758    private static final boolean DBG = false;
759
760    /**
761     * The logging tag used by this class with android.util.Log.
762     */
763    protected static final String VIEW_LOG_TAG = "View";
764
765    /**
766     * When set to true, apps will draw debugging information about their layouts.
767     *
768     * @hide
769     */
770    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
771
772    /**
773     * When set to true, this view will save its attribute data.
774     *
775     * @hide
776     */
777    public static boolean mDebugViewAttributes = false;
778
779    /**
780     * Used to mark a View that has no ID.
781     */
782    public static final int NO_ID = -1;
783
784    /**
785     * Signals that compatibility booleans have been initialized according to
786     * target SDK versions.
787     */
788    private static boolean sCompatibilityDone = false;
789
790    /**
791     * Use the old (broken) way of building MeasureSpecs.
792     */
793    private static boolean sUseBrokenMakeMeasureSpec = false;
794
795    /**
796     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
797     */
798    static boolean sUseZeroUnspecifiedMeasureSpec = false;
799
800    /**
801     * Ignore any optimizations using the measure cache.
802     */
803    private static boolean sIgnoreMeasureCache = false;
804
805    /**
806     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
807     */
808    private static boolean sAlwaysRemeasureExactly = false;
809
810    /**
811     * Relax constraints around whether setLayoutParams() must be called after
812     * modifying the layout params.
813     */
814    private static boolean sLayoutParamsAlwaysChanged = false;
815
816    /**
817     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
818     * without throwing
819     */
820    static boolean sTextureViewIgnoresDrawableSetters = false;
821
822    /**
823     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
824     * calling setFlags.
825     */
826    private static final int NOT_FOCUSABLE = 0x00000000;
827
828    /**
829     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
830     * setFlags.
831     */
832    private static final int FOCUSABLE = 0x00000001;
833
834    /**
835     * Mask for use with setFlags indicating bits used for focus.
836     */
837    private static final int FOCUSABLE_MASK = 0x00000001;
838
839    /**
840     * This view will adjust its padding to fit sytem windows (e.g. status bar)
841     */
842    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
843
844    /** @hide */
845    @IntDef({VISIBLE, INVISIBLE, GONE})
846    @Retention(RetentionPolicy.SOURCE)
847    public @interface Visibility {}
848
849    /**
850     * This view is visible.
851     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
852     * android:visibility}.
853     */
854    public static final int VISIBLE = 0x00000000;
855
856    /**
857     * This view is invisible, but it still takes up space for layout purposes.
858     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
859     * android:visibility}.
860     */
861    public static final int INVISIBLE = 0x00000004;
862
863    /**
864     * This view is invisible, and it doesn't take any space for layout
865     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
866     * android:visibility}.
867     */
868    public static final int GONE = 0x00000008;
869
870    /**
871     * Mask for use with setFlags indicating bits used for visibility.
872     * {@hide}
873     */
874    static final int VISIBILITY_MASK = 0x0000000C;
875
876    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
877
878    /**
879     * This view is enabled. Interpretation varies by subclass.
880     * Use with ENABLED_MASK when calling setFlags.
881     * {@hide}
882     */
883    static final int ENABLED = 0x00000000;
884
885    /**
886     * This view is disabled. Interpretation varies by subclass.
887     * Use with ENABLED_MASK when calling setFlags.
888     * {@hide}
889     */
890    static final int DISABLED = 0x00000020;
891
892   /**
893    * Mask for use with setFlags indicating bits used for indicating whether
894    * this view is enabled
895    * {@hide}
896    */
897    static final int ENABLED_MASK = 0x00000020;
898
899    /**
900     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
901     * called and further optimizations will be performed. It is okay to have
902     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
903     * {@hide}
904     */
905    static final int WILL_NOT_DRAW = 0x00000080;
906
907    /**
908     * Mask for use with setFlags indicating bits used for indicating whether
909     * this view is will draw
910     * {@hide}
911     */
912    static final int DRAW_MASK = 0x00000080;
913
914    /**
915     * <p>This view doesn't show scrollbars.</p>
916     * {@hide}
917     */
918    static final int SCROLLBARS_NONE = 0x00000000;
919
920    /**
921     * <p>This view shows horizontal scrollbars.</p>
922     * {@hide}
923     */
924    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
925
926    /**
927     * <p>This view shows vertical scrollbars.</p>
928     * {@hide}
929     */
930    static final int SCROLLBARS_VERTICAL = 0x00000200;
931
932    /**
933     * <p>Mask for use with setFlags indicating bits used for indicating which
934     * scrollbars are enabled.</p>
935     * {@hide}
936     */
937    static final int SCROLLBARS_MASK = 0x00000300;
938
939    /**
940     * Indicates that the view should filter touches when its window is obscured.
941     * Refer to the class comments for more information about this security feature.
942     * {@hide}
943     */
944    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
945
946    /**
947     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
948     * that they are optional and should be skipped if the window has
949     * requested system UI flags that ignore those insets for layout.
950     */
951    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
952
953    /**
954     * <p>This view doesn't show fading edges.</p>
955     * {@hide}
956     */
957    static final int FADING_EDGE_NONE = 0x00000000;
958
959    /**
960     * <p>This view shows horizontal fading edges.</p>
961     * {@hide}
962     */
963    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
964
965    /**
966     * <p>This view shows vertical fading edges.</p>
967     * {@hide}
968     */
969    static final int FADING_EDGE_VERTICAL = 0x00002000;
970
971    /**
972     * <p>Mask for use with setFlags indicating bits used for indicating which
973     * fading edges are enabled.</p>
974     * {@hide}
975     */
976    static final int FADING_EDGE_MASK = 0x00003000;
977
978    /**
979     * <p>Indicates this view can be clicked. When clickable, a View reacts
980     * to clicks by notifying the OnClickListener.<p>
981     * {@hide}
982     */
983    static final int CLICKABLE = 0x00004000;
984
985    /**
986     * <p>Indicates this view is caching its drawing into a bitmap.</p>
987     * {@hide}
988     */
989    static final int DRAWING_CACHE_ENABLED = 0x00008000;
990
991    /**
992     * <p>Indicates that no icicle should be saved for this view.<p>
993     * {@hide}
994     */
995    static final int SAVE_DISABLED = 0x000010000;
996
997    /**
998     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
999     * property.</p>
1000     * {@hide}
1001     */
1002    static final int SAVE_DISABLED_MASK = 0x000010000;
1003
1004    /**
1005     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1006     * {@hide}
1007     */
1008    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1009
1010    /**
1011     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1012     * {@hide}
1013     */
1014    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1015
1016    /** @hide */
1017    @Retention(RetentionPolicy.SOURCE)
1018    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1019    public @interface DrawingCacheQuality {}
1020
1021    /**
1022     * <p>Enables low quality mode for the drawing cache.</p>
1023     */
1024    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1025
1026    /**
1027     * <p>Enables high quality mode for the drawing cache.</p>
1028     */
1029    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1030
1031    /**
1032     * <p>Enables automatic quality mode for the drawing cache.</p>
1033     */
1034    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1035
1036    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1037            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1038    };
1039
1040    /**
1041     * <p>Mask for use with setFlags indicating bits used for the cache
1042     * quality property.</p>
1043     * {@hide}
1044     */
1045    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1046
1047    /**
1048     * <p>
1049     * Indicates this view can be long clicked. When long clickable, a View
1050     * reacts to long clicks by notifying the OnLongClickListener or showing a
1051     * context menu.
1052     * </p>
1053     * {@hide}
1054     */
1055    static final int LONG_CLICKABLE = 0x00200000;
1056
1057    /**
1058     * <p>Indicates that this view gets its drawable states from its direct parent
1059     * and ignores its original internal states.</p>
1060     *
1061     * @hide
1062     */
1063    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1064
1065    /**
1066     * <p>
1067     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1068     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1069     * OnContextClickListener.
1070     * </p>
1071     * {@hide}
1072     */
1073    static final int CONTEXT_CLICKABLE = 0x00800000;
1074
1075
1076    /** @hide */
1077    @IntDef({
1078        SCROLLBARS_INSIDE_OVERLAY,
1079        SCROLLBARS_INSIDE_INSET,
1080        SCROLLBARS_OUTSIDE_OVERLAY,
1081        SCROLLBARS_OUTSIDE_INSET
1082    })
1083    @Retention(RetentionPolicy.SOURCE)
1084    public @interface ScrollBarStyle {}
1085
1086    /**
1087     * The scrollbar style to display the scrollbars inside the content area,
1088     * without increasing the padding. The scrollbars will be overlaid with
1089     * translucency on the view's content.
1090     */
1091    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1092
1093    /**
1094     * The scrollbar style to display the scrollbars inside the padded area,
1095     * increasing the padding of the view. The scrollbars will not overlap the
1096     * content area of the view.
1097     */
1098    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1099
1100    /**
1101     * The scrollbar style to display the scrollbars at the edge of the view,
1102     * without increasing the padding. The scrollbars will be overlaid with
1103     * translucency.
1104     */
1105    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1106
1107    /**
1108     * The scrollbar style to display the scrollbars at the edge of the view,
1109     * increasing the padding of the view. The scrollbars will only overlap the
1110     * background, if any.
1111     */
1112    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1113
1114    /**
1115     * Mask to check if the scrollbar style is overlay or inset.
1116     * {@hide}
1117     */
1118    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1119
1120    /**
1121     * Mask to check if the scrollbar style is inside or outside.
1122     * {@hide}
1123     */
1124    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1125
1126    /**
1127     * Mask for scrollbar style.
1128     * {@hide}
1129     */
1130    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1131
1132    /**
1133     * View flag indicating that the screen should remain on while the
1134     * window containing this view is visible to the user.  This effectively
1135     * takes care of automatically setting the WindowManager's
1136     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1137     */
1138    public static final int KEEP_SCREEN_ON = 0x04000000;
1139
1140    /**
1141     * View flag indicating whether this view should have sound effects enabled
1142     * for events such as clicking and touching.
1143     */
1144    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1145
1146    /**
1147     * View flag indicating whether this view should have haptic feedback
1148     * enabled for events such as long presses.
1149     */
1150    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1151
1152    /**
1153     * <p>Indicates that the view hierarchy should stop saving state when
1154     * it reaches this view.  If state saving is initiated immediately at
1155     * the view, it will be allowed.
1156     * {@hide}
1157     */
1158    static final int PARENT_SAVE_DISABLED = 0x20000000;
1159
1160    /**
1161     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1162     * {@hide}
1163     */
1164    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1165
1166    /** @hide */
1167    @IntDef(flag = true,
1168            value = {
1169                FOCUSABLES_ALL,
1170                FOCUSABLES_TOUCH_MODE
1171            })
1172    @Retention(RetentionPolicy.SOURCE)
1173    public @interface FocusableMode {}
1174
1175    /**
1176     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1177     * should add all focusable Views regardless if they are focusable in touch mode.
1178     */
1179    public static final int FOCUSABLES_ALL = 0x00000000;
1180
1181    /**
1182     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1183     * should add only Views focusable in touch mode.
1184     */
1185    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1186
1187    /** @hide */
1188    @IntDef({
1189            FOCUS_BACKWARD,
1190            FOCUS_FORWARD,
1191            FOCUS_LEFT,
1192            FOCUS_UP,
1193            FOCUS_RIGHT,
1194            FOCUS_DOWN
1195    })
1196    @Retention(RetentionPolicy.SOURCE)
1197    public @interface FocusDirection {}
1198
1199    /** @hide */
1200    @IntDef({
1201            FOCUS_LEFT,
1202            FOCUS_UP,
1203            FOCUS_RIGHT,
1204            FOCUS_DOWN
1205    })
1206    @Retention(RetentionPolicy.SOURCE)
1207    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1208
1209    /**
1210     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1211     * item.
1212     */
1213    public static final int FOCUS_BACKWARD = 0x00000001;
1214
1215    /**
1216     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1217     * item.
1218     */
1219    public static final int FOCUS_FORWARD = 0x00000002;
1220
1221    /**
1222     * Use with {@link #focusSearch(int)}. Move focus to the left.
1223     */
1224    public static final int FOCUS_LEFT = 0x00000011;
1225
1226    /**
1227     * Use with {@link #focusSearch(int)}. Move focus up.
1228     */
1229    public static final int FOCUS_UP = 0x00000021;
1230
1231    /**
1232     * Use with {@link #focusSearch(int)}. Move focus to the right.
1233     */
1234    public static final int FOCUS_RIGHT = 0x00000042;
1235
1236    /**
1237     * Use with {@link #focusSearch(int)}. Move focus down.
1238     */
1239    public static final int FOCUS_DOWN = 0x00000082;
1240
1241    /**
1242     * Bits of {@link #getMeasuredWidthAndState()} and
1243     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1244     */
1245    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1246
1247    /**
1248     * Bits of {@link #getMeasuredWidthAndState()} and
1249     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1250     */
1251    public static final int MEASURED_STATE_MASK = 0xff000000;
1252
1253    /**
1254     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1255     * for functions that combine both width and height into a single int,
1256     * such as {@link #getMeasuredState()} and the childState argument of
1257     * {@link #resolveSizeAndState(int, int, int)}.
1258     */
1259    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1260
1261    /**
1262     * Bit of {@link #getMeasuredWidthAndState()} and
1263     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1264     * is smaller that the space the view would like to have.
1265     */
1266    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1267
1268    /**
1269     * Base View state sets
1270     */
1271    // Singles
1272    /**
1273     * Indicates the view has no states set. States are used with
1274     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1275     * view depending on its state.
1276     *
1277     * @see android.graphics.drawable.Drawable
1278     * @see #getDrawableState()
1279     */
1280    protected static final int[] EMPTY_STATE_SET;
1281    /**
1282     * Indicates the view is enabled. States are used with
1283     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1284     * view depending on its state.
1285     *
1286     * @see android.graphics.drawable.Drawable
1287     * @see #getDrawableState()
1288     */
1289    protected static final int[] ENABLED_STATE_SET;
1290    /**
1291     * Indicates the view is focused. States are used with
1292     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1293     * view depending on its state.
1294     *
1295     * @see android.graphics.drawable.Drawable
1296     * @see #getDrawableState()
1297     */
1298    protected static final int[] FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is selected. States are used with
1301     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1302     * view depending on its state.
1303     *
1304     * @see android.graphics.drawable.Drawable
1305     * @see #getDrawableState()
1306     */
1307    protected static final int[] SELECTED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed. States are used with
1310     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1311     * view depending on its state.
1312     *
1313     * @see android.graphics.drawable.Drawable
1314     * @see #getDrawableState()
1315     */
1316    protected static final int[] PRESSED_STATE_SET;
1317    /**
1318     * Indicates the view's window has focus. States are used with
1319     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1320     * view depending on its state.
1321     *
1322     * @see android.graphics.drawable.Drawable
1323     * @see #getDrawableState()
1324     */
1325    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1326    // Doubles
1327    /**
1328     * Indicates the view is enabled and has the focus.
1329     *
1330     * @see #ENABLED_STATE_SET
1331     * @see #FOCUSED_STATE_SET
1332     */
1333    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is enabled and selected.
1336     *
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     */
1340    protected static final int[] ENABLED_SELECTED_STATE_SET;
1341    /**
1342     * Indicates the view is enabled and that its window has focus.
1343     *
1344     * @see #ENABLED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1348    /**
1349     * Indicates the view is focused and selected.
1350     *
1351     * @see #FOCUSED_STATE_SET
1352     * @see #SELECTED_STATE_SET
1353     */
1354    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1355    /**
1356     * Indicates the view has the focus and that its window has the focus.
1357     *
1358     * @see #FOCUSED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is selected and that its window has the focus.
1364     *
1365     * @see #SELECTED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1369    // Triples
1370    /**
1371     * Indicates the view is enabled, focused and selected.
1372     *
1373     * @see #ENABLED_STATE_SET
1374     * @see #FOCUSED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     */
1377    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1378    /**
1379     * Indicates the view is enabled, focused and its window has the focus.
1380     *
1381     * @see #ENABLED_STATE_SET
1382     * @see #FOCUSED_STATE_SET
1383     * @see #WINDOW_FOCUSED_STATE_SET
1384     */
1385    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1386    /**
1387     * Indicates the view is enabled, selected and its window has the focus.
1388     *
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     * @see #WINDOW_FOCUSED_STATE_SET
1392     */
1393    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1394    /**
1395     * Indicates the view is focused, selected and its window has the focus.
1396     *
1397     * @see #FOCUSED_STATE_SET
1398     * @see #SELECTED_STATE_SET
1399     * @see #WINDOW_FOCUSED_STATE_SET
1400     */
1401    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1402    /**
1403     * Indicates the view is enabled, focused, selected and its window
1404     * has the focus.
1405     *
1406     * @see #ENABLED_STATE_SET
1407     * @see #FOCUSED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is pressed and its window has the focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed and selected.
1421     *
1422     * @see #PRESSED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     */
1425    protected static final int[] PRESSED_SELECTED_STATE_SET;
1426    /**
1427     * Indicates the view is pressed, selected and its window has the focus.
1428     *
1429     * @see #PRESSED_STATE_SET
1430     * @see #SELECTED_STATE_SET
1431     * @see #WINDOW_FOCUSED_STATE_SET
1432     */
1433    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1434    /**
1435     * Indicates the view is pressed and focused.
1436     *
1437     * @see #PRESSED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1441    /**
1442     * Indicates the view is pressed, focused and its window has the focus.
1443     *
1444     * @see #PRESSED_STATE_SET
1445     * @see #FOCUSED_STATE_SET
1446     * @see #WINDOW_FOCUSED_STATE_SET
1447     */
1448    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1449    /**
1450     * Indicates the view is pressed, focused and selected.
1451     *
1452     * @see #PRESSED_STATE_SET
1453     * @see #SELECTED_STATE_SET
1454     * @see #FOCUSED_STATE_SET
1455     */
1456    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1457    /**
1458     * Indicates the view is pressed, focused, selected and its window has the focus.
1459     *
1460     * @see #PRESSED_STATE_SET
1461     * @see #FOCUSED_STATE_SET
1462     * @see #SELECTED_STATE_SET
1463     * @see #WINDOW_FOCUSED_STATE_SET
1464     */
1465    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1466    /**
1467     * Indicates the view is pressed and enabled.
1468     *
1469     * @see #PRESSED_STATE_SET
1470     * @see #ENABLED_STATE_SET
1471     */
1472    protected static final int[] PRESSED_ENABLED_STATE_SET;
1473    /**
1474     * Indicates the view is pressed, enabled and its window has the focus.
1475     *
1476     * @see #PRESSED_STATE_SET
1477     * @see #ENABLED_STATE_SET
1478     * @see #WINDOW_FOCUSED_STATE_SET
1479     */
1480    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1481    /**
1482     * Indicates the view is pressed, enabled and selected.
1483     *
1484     * @see #PRESSED_STATE_SET
1485     * @see #ENABLED_STATE_SET
1486     * @see #SELECTED_STATE_SET
1487     */
1488    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1489    /**
1490     * Indicates the view is pressed, enabled, selected and its window has the
1491     * focus.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #ENABLED_STATE_SET
1495     * @see #SELECTED_STATE_SET
1496     * @see #WINDOW_FOCUSED_STATE_SET
1497     */
1498    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1499    /**
1500     * Indicates the view is pressed, enabled and focused.
1501     *
1502     * @see #PRESSED_STATE_SET
1503     * @see #ENABLED_STATE_SET
1504     * @see #FOCUSED_STATE_SET
1505     */
1506    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1507    /**
1508     * Indicates the view is pressed, enabled, focused and its window has the
1509     * focus.
1510     *
1511     * @see #PRESSED_STATE_SET
1512     * @see #ENABLED_STATE_SET
1513     * @see #FOCUSED_STATE_SET
1514     * @see #WINDOW_FOCUSED_STATE_SET
1515     */
1516    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1517    /**
1518     * Indicates the view is pressed, enabled, focused and selected.
1519     *
1520     * @see #PRESSED_STATE_SET
1521     * @see #ENABLED_STATE_SET
1522     * @see #SELECTED_STATE_SET
1523     * @see #FOCUSED_STATE_SET
1524     */
1525    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1526    /**
1527     * Indicates the view is pressed, enabled, focused, selected and its window
1528     * has the focus.
1529     *
1530     * @see #PRESSED_STATE_SET
1531     * @see #ENABLED_STATE_SET
1532     * @see #SELECTED_STATE_SET
1533     * @see #FOCUSED_STATE_SET
1534     * @see #WINDOW_FOCUSED_STATE_SET
1535     */
1536    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1537
1538    static {
1539        EMPTY_STATE_SET = StateSet.get(0);
1540
1541        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1542
1543        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1544        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1545                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1546
1547        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1548        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1549                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1550        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1551                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1552        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1553                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1554                        | StateSet.VIEW_STATE_FOCUSED);
1555
1556        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1557        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1558                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1559        ENABLED_SELECTED_STATE_SET = StateSet.get(
1560                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1561        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1562                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1563                        | StateSet.VIEW_STATE_ENABLED);
1564        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1565                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1566        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1567                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1568                        | StateSet.VIEW_STATE_ENABLED);
1569        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1571                        | StateSet.VIEW_STATE_ENABLED);
1572        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1573                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1574                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1575
1576        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1577        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1578                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1579        PRESSED_SELECTED_STATE_SET = StateSet.get(
1580                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1581        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1582                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1583                        | StateSet.VIEW_STATE_PRESSED);
1584        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1585                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1586        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1587                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1588                        | StateSet.VIEW_STATE_PRESSED);
1589        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1591                        | StateSet.VIEW_STATE_PRESSED);
1592        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1593                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1594                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1595        PRESSED_ENABLED_STATE_SET = StateSet.get(
1596                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1597        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1598                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1599                        | StateSet.VIEW_STATE_PRESSED);
1600        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1601                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1602                        | StateSet.VIEW_STATE_PRESSED);
1603        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1604                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1605                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1606        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1607                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1608                        | StateSet.VIEW_STATE_PRESSED);
1609        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1610                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1611                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1612        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1614                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1615        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1616                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1617                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1618                        | StateSet.VIEW_STATE_PRESSED);
1619    }
1620
1621    /**
1622     * Accessibility event types that are dispatched for text population.
1623     */
1624    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1625            AccessibilityEvent.TYPE_VIEW_CLICKED
1626            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1627            | AccessibilityEvent.TYPE_VIEW_SELECTED
1628            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1629            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1630            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1631            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1632            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1633            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1634            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1635            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1636
1637    /**
1638     * Temporary Rect currently for use in setBackground().  This will probably
1639     * be extended in the future to hold our own class with more than just
1640     * a Rect. :)
1641     */
1642    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1643
1644    /**
1645     * Map used to store views' tags.
1646     */
1647    private SparseArray<Object> mKeyedTags;
1648
1649    /**
1650     * The next available accessibility id.
1651     */
1652    private static int sNextAccessibilityViewId;
1653
1654    /**
1655     * The animation currently associated with this view.
1656     * @hide
1657     */
1658    protected Animation mCurrentAnimation = null;
1659
1660    /**
1661     * Width as measured during measure pass.
1662     * {@hide}
1663     */
1664    @ViewDebug.ExportedProperty(category = "measurement")
1665    int mMeasuredWidth;
1666
1667    /**
1668     * Height as measured during measure pass.
1669     * {@hide}
1670     */
1671    @ViewDebug.ExportedProperty(category = "measurement")
1672    int mMeasuredHeight;
1673
1674    /**
1675     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1676     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1677     * its display list. This flag, used only when hw accelerated, allows us to clear the
1678     * flag while retaining this information until it's needed (at getDisplayList() time and
1679     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1680     *
1681     * {@hide}
1682     */
1683    boolean mRecreateDisplayList = false;
1684
1685    /**
1686     * The view's identifier.
1687     * {@hide}
1688     *
1689     * @see #setId(int)
1690     * @see #getId()
1691     */
1692    @IdRes
1693    @ViewDebug.ExportedProperty(resolveId = true)
1694    int mID = NO_ID;
1695
1696    /**
1697     * The stable ID of this view for accessibility purposes.
1698     */
1699    int mAccessibilityViewId = NO_ID;
1700
1701    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1702
1703    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1704
1705    /**
1706     * The view's tag.
1707     * {@hide}
1708     *
1709     * @see #setTag(Object)
1710     * @see #getTag()
1711     */
1712    protected Object mTag = null;
1713
1714    // for mPrivateFlags:
1715    /** {@hide} */
1716    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1717    /** {@hide} */
1718    static final int PFLAG_FOCUSED                     = 0x00000002;
1719    /** {@hide} */
1720    static final int PFLAG_SELECTED                    = 0x00000004;
1721    /** {@hide} */
1722    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1723    /** {@hide} */
1724    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1725    /** {@hide} */
1726    static final int PFLAG_DRAWN                       = 0x00000020;
1727    /**
1728     * When this flag is set, this view is running an animation on behalf of its
1729     * children and should therefore not cancel invalidate requests, even if they
1730     * lie outside of this view's bounds.
1731     *
1732     * {@hide}
1733     */
1734    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1735    /** {@hide} */
1736    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1737    /** {@hide} */
1738    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1739    /** {@hide} */
1740    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1741    /** {@hide} */
1742    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1743    /** {@hide} */
1744    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1745    /** {@hide} */
1746    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1747
1748    private static final int PFLAG_PRESSED             = 0x00004000;
1749
1750    /** {@hide} */
1751    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1752    /**
1753     * Flag used to indicate that this view should be drawn once more (and only once
1754     * more) after its animation has completed.
1755     * {@hide}
1756     */
1757    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1758
1759    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1760
1761    /**
1762     * Indicates that the View returned true when onSetAlpha() was called and that
1763     * the alpha must be restored.
1764     * {@hide}
1765     */
1766    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1767
1768    /**
1769     * Set by {@link #setScrollContainer(boolean)}.
1770     */
1771    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1772
1773    /**
1774     * Set by {@link #setScrollContainer(boolean)}.
1775     */
1776    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1777
1778    /**
1779     * View flag indicating whether this view was invalidated (fully or partially.)
1780     *
1781     * @hide
1782     */
1783    static final int PFLAG_DIRTY                       = 0x00200000;
1784
1785    /**
1786     * View flag indicating whether this view was invalidated by an opaque
1787     * invalidate request.
1788     *
1789     * @hide
1790     */
1791    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1792
1793    /**
1794     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1795     *
1796     * @hide
1797     */
1798    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1799
1800    /**
1801     * Indicates whether the background is opaque.
1802     *
1803     * @hide
1804     */
1805    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1806
1807    /**
1808     * Indicates whether the scrollbars are opaque.
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1813
1814    /**
1815     * Indicates whether the view is opaque.
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1820
1821    /**
1822     * Indicates a prepressed state;
1823     * the short time between ACTION_DOWN and recognizing
1824     * a 'real' press. Prepressed is used to recognize quick taps
1825     * even when they are shorter than ViewConfiguration.getTapTimeout().
1826     *
1827     * @hide
1828     */
1829    private static final int PFLAG_PREPRESSED          = 0x02000000;
1830
1831    /**
1832     * Indicates whether the view is temporarily detached.
1833     *
1834     * @hide
1835     */
1836    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1837
1838    /**
1839     * Indicates that we should awaken scroll bars once attached
1840     *
1841     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1842     * during window attachment and it is no longer needed. Feel free to repurpose it.
1843     *
1844     * @hide
1845     */
1846    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1847
1848    /**
1849     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1850     * @hide
1851     */
1852    private static final int PFLAG_HOVERED             = 0x10000000;
1853
1854    /**
1855     * no longer needed, should be reused
1856     */
1857    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1858
1859    /** {@hide} */
1860    static final int PFLAG_ACTIVATED                   = 0x40000000;
1861
1862    /**
1863     * Indicates that this view was specifically invalidated, not just dirtied because some
1864     * child view was invalidated. The flag is used to determine when we need to recreate
1865     * a view's display list (as opposed to just returning a reference to its existing
1866     * display list).
1867     *
1868     * @hide
1869     */
1870    static final int PFLAG_INVALIDATED                 = 0x80000000;
1871
1872    /**
1873     * Masks for mPrivateFlags2, as generated by dumpFlags():
1874     *
1875     * |-------|-------|-------|-------|
1876     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1877     *                                1  PFLAG2_DRAG_HOVERED
1878     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1879     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1880     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1881     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1882     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1883     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1884     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1885     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1886     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1887     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1888     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1889     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1890     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1891     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1892     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1893     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1894     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1895     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1896     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1897     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1898     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1899     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1900     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1901     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1902     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1903     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1904     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1905     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1906     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1907     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1908     *    1                              PFLAG2_PADDING_RESOLVED
1909     *   1                               PFLAG2_DRAWABLE_RESOLVED
1910     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1911     * |-------|-------|-------|-------|
1912     */
1913
1914    /**
1915     * Indicates that this view has reported that it can accept the current drag's content.
1916     * Cleared when the drag operation concludes.
1917     * @hide
1918     */
1919    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1920
1921    /**
1922     * Indicates that this view is currently directly under the drag location in a
1923     * drag-and-drop operation involving content that it can accept.  Cleared when
1924     * the drag exits the view, or when the drag operation concludes.
1925     * @hide
1926     */
1927    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1928
1929    /** @hide */
1930    @IntDef({
1931        LAYOUT_DIRECTION_LTR,
1932        LAYOUT_DIRECTION_RTL,
1933        LAYOUT_DIRECTION_INHERIT,
1934        LAYOUT_DIRECTION_LOCALE
1935    })
1936    @Retention(RetentionPolicy.SOURCE)
1937    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1938    public @interface LayoutDir {}
1939
1940    /** @hide */
1941    @IntDef({
1942        LAYOUT_DIRECTION_LTR,
1943        LAYOUT_DIRECTION_RTL
1944    })
1945    @Retention(RetentionPolicy.SOURCE)
1946    public @interface ResolvedLayoutDir {}
1947
1948    /**
1949     * A flag to indicate that the layout direction of this view has not been defined yet.
1950     * @hide
1951     */
1952    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1953
1954    /**
1955     * Horizontal layout direction of this view is from Left to Right.
1956     * Use with {@link #setLayoutDirection}.
1957     */
1958    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1959
1960    /**
1961     * Horizontal layout direction of this view is from Right to Left.
1962     * Use with {@link #setLayoutDirection}.
1963     */
1964    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1965
1966    /**
1967     * Horizontal layout direction of this view is inherited from its parent.
1968     * Use with {@link #setLayoutDirection}.
1969     */
1970    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1971
1972    /**
1973     * Horizontal layout direction of this view is from deduced from the default language
1974     * script for the locale. Use with {@link #setLayoutDirection}.
1975     */
1976    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1977
1978    /**
1979     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1980     * @hide
1981     */
1982    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1983
1984    /**
1985     * Mask for use with private flags indicating bits used for horizontal layout direction.
1986     * @hide
1987     */
1988    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1989
1990    /**
1991     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1992     * right-to-left direction.
1993     * @hide
1994     */
1995    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1996
1997    /**
1998     * Indicates whether the view horizontal layout direction has been resolved.
1999     * @hide
2000     */
2001    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2002
2003    /**
2004     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2005     * @hide
2006     */
2007    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2008            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2009
2010    /*
2011     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2012     * flag value.
2013     * @hide
2014     */
2015    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2016            LAYOUT_DIRECTION_LTR,
2017            LAYOUT_DIRECTION_RTL,
2018            LAYOUT_DIRECTION_INHERIT,
2019            LAYOUT_DIRECTION_LOCALE
2020    };
2021
2022    /**
2023     * Default horizontal layout direction.
2024     */
2025    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2026
2027    /**
2028     * Default horizontal layout direction.
2029     * @hide
2030     */
2031    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2032
2033    /**
2034     * Text direction is inherited through {@link ViewGroup}
2035     */
2036    public static final int TEXT_DIRECTION_INHERIT = 0;
2037
2038    /**
2039     * Text direction is using "first strong algorithm". The first strong directional character
2040     * determines the paragraph direction. If there is no strong directional character, the
2041     * paragraph direction is the view's resolved layout direction.
2042     */
2043    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2044
2045    /**
2046     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2047     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2048     * If there are neither, the paragraph direction is the view's resolved layout direction.
2049     */
2050    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2051
2052    /**
2053     * Text direction is forced to LTR.
2054     */
2055    public static final int TEXT_DIRECTION_LTR = 3;
2056
2057    /**
2058     * Text direction is forced to RTL.
2059     */
2060    public static final int TEXT_DIRECTION_RTL = 4;
2061
2062    /**
2063     * Text direction is coming from the system Locale.
2064     */
2065    public static final int TEXT_DIRECTION_LOCALE = 5;
2066
2067    /**
2068     * Text direction is using "first strong algorithm". The first strong directional character
2069     * determines the paragraph direction. If there is no strong directional character, the
2070     * paragraph direction is LTR.
2071     */
2072    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2073
2074    /**
2075     * Text direction is using "first strong algorithm". The first strong directional character
2076     * determines the paragraph direction. If there is no strong directional character, the
2077     * paragraph direction is RTL.
2078     */
2079    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2080
2081    /**
2082     * Default text direction is inherited
2083     */
2084    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2085
2086    /**
2087     * Default resolved text direction
2088     * @hide
2089     */
2090    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2091
2092    /**
2093     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2094     * @hide
2095     */
2096    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2097
2098    /**
2099     * Mask for use with private flags indicating bits used for text direction.
2100     * @hide
2101     */
2102    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2103            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2104
2105    /**
2106     * Array of text direction flags for mapping attribute "textDirection" to correct
2107     * flag value.
2108     * @hide
2109     */
2110    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2111            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2112            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2113            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2114            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2115            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2116            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2117            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2118            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2119    };
2120
2121    /**
2122     * Indicates whether the view text direction has been resolved.
2123     * @hide
2124     */
2125    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2126            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2127
2128    /**
2129     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2130     * @hide
2131     */
2132    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2133
2134    /**
2135     * Mask for use with private flags indicating bits used for resolved text direction.
2136     * @hide
2137     */
2138    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2139            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2140
2141    /**
2142     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2143     * @hide
2144     */
2145    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2146            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2147
2148    /** @hide */
2149    @IntDef({
2150        TEXT_ALIGNMENT_INHERIT,
2151        TEXT_ALIGNMENT_GRAVITY,
2152        TEXT_ALIGNMENT_CENTER,
2153        TEXT_ALIGNMENT_TEXT_START,
2154        TEXT_ALIGNMENT_TEXT_END,
2155        TEXT_ALIGNMENT_VIEW_START,
2156        TEXT_ALIGNMENT_VIEW_END
2157    })
2158    @Retention(RetentionPolicy.SOURCE)
2159    public @interface TextAlignment {}
2160
2161    /**
2162     * Default text alignment. The text alignment of this View is inherited from its parent.
2163     * Use with {@link #setTextAlignment(int)}
2164     */
2165    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2166
2167    /**
2168     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2169     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2170     *
2171     * Use with {@link #setTextAlignment(int)}
2172     */
2173    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2174
2175    /**
2176     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2177     *
2178     * Use with {@link #setTextAlignment(int)}
2179     */
2180    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2181
2182    /**
2183     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2184     *
2185     * Use with {@link #setTextAlignment(int)}
2186     */
2187    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2188
2189    /**
2190     * Center the paragraph, e.g. ALIGN_CENTER.
2191     *
2192     * Use with {@link #setTextAlignment(int)}
2193     */
2194    public static final int TEXT_ALIGNMENT_CENTER = 4;
2195
2196    /**
2197     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2198     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2199     *
2200     * Use with {@link #setTextAlignment(int)}
2201     */
2202    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2203
2204    /**
2205     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2206     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2207     *
2208     * Use with {@link #setTextAlignment(int)}
2209     */
2210    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2211
2212    /**
2213     * Default text alignment is inherited
2214     */
2215    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2216
2217    /**
2218     * Default resolved text alignment
2219     * @hide
2220     */
2221    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2222
2223    /**
2224      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2225      * @hide
2226      */
2227    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2228
2229    /**
2230      * Mask for use with private flags indicating bits used for text alignment.
2231      * @hide
2232      */
2233    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2234
2235    /**
2236     * Array of text direction flags for mapping attribute "textAlignment" to correct
2237     * flag value.
2238     * @hide
2239     */
2240    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2241            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2242            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2243            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2244            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2245            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2246            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2247            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2248    };
2249
2250    /**
2251     * Indicates whether the view text alignment has been resolved.
2252     * @hide
2253     */
2254    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2255
2256    /**
2257     * Bit shift to get the resolved text alignment.
2258     * @hide
2259     */
2260    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2261
2262    /**
2263     * Mask for use with private flags indicating bits used for text alignment.
2264     * @hide
2265     */
2266    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2267            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2268
2269    /**
2270     * Indicates whether if the view text alignment has been resolved to gravity
2271     */
2272    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2273            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2274
2275    // Accessiblity constants for mPrivateFlags2
2276
2277    /**
2278     * Shift for the bits in {@link #mPrivateFlags2} related to the
2279     * "importantForAccessibility" attribute.
2280     */
2281    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2282
2283    /**
2284     * Automatically determine whether a view is important for accessibility.
2285     */
2286    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2287
2288    /**
2289     * The view is important for accessibility.
2290     */
2291    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2292
2293    /**
2294     * The view is not important for accessibility.
2295     */
2296    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2297
2298    /**
2299     * The view is not important for accessibility, nor are any of its
2300     * descendant views.
2301     */
2302    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2303
2304    /**
2305     * The default whether the view is important for accessibility.
2306     */
2307    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2308
2309    /**
2310     * Mask for obtainig the bits which specify how to determine
2311     * whether a view is important for accessibility.
2312     */
2313    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2314        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2315        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2316        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2317
2318    /**
2319     * Shift for the bits in {@link #mPrivateFlags2} related to the
2320     * "accessibilityLiveRegion" attribute.
2321     */
2322    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2323
2324    /**
2325     * Live region mode specifying that accessibility services should not
2326     * automatically announce changes to this view. This is the default live
2327     * region mode for most views.
2328     * <p>
2329     * Use with {@link #setAccessibilityLiveRegion(int)}.
2330     */
2331    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2332
2333    /**
2334     * Live region mode specifying that accessibility services should announce
2335     * changes to this view.
2336     * <p>
2337     * Use with {@link #setAccessibilityLiveRegion(int)}.
2338     */
2339    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2340
2341    /**
2342     * Live region mode specifying that accessibility services should interrupt
2343     * ongoing speech to immediately announce changes to this view.
2344     * <p>
2345     * Use with {@link #setAccessibilityLiveRegion(int)}.
2346     */
2347    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2348
2349    /**
2350     * The default whether the view is important for accessibility.
2351     */
2352    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2353
2354    /**
2355     * Mask for obtaining the bits which specify a view's accessibility live
2356     * region mode.
2357     */
2358    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2359            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2360            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2361
2362    /**
2363     * Flag indicating whether a view has accessibility focus.
2364     */
2365    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2366
2367    /**
2368     * Flag whether the accessibility state of the subtree rooted at this view changed.
2369     */
2370    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2371
2372    /**
2373     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2374     * is used to check whether later changes to the view's transform should invalidate the
2375     * view to force the quickReject test to run again.
2376     */
2377    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2378
2379    /**
2380     * Flag indicating that start/end padding has been resolved into left/right padding
2381     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2382     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2383     * during measurement. In some special cases this is required such as when an adapter-based
2384     * view measures prospective children without attaching them to a window.
2385     */
2386    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2387
2388    /**
2389     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2390     */
2391    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2392
2393    /**
2394     * Indicates that the view is tracking some sort of transient state
2395     * that the app should not need to be aware of, but that the framework
2396     * should take special care to preserve.
2397     */
2398    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2399
2400    /**
2401     * Group of bits indicating that RTL properties resolution is done.
2402     */
2403    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2404            PFLAG2_TEXT_DIRECTION_RESOLVED |
2405            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2406            PFLAG2_PADDING_RESOLVED |
2407            PFLAG2_DRAWABLE_RESOLVED;
2408
2409    // There are a couple of flags left in mPrivateFlags2
2410
2411    /* End of masks for mPrivateFlags2 */
2412
2413    /**
2414     * Masks for mPrivateFlags3, as generated by dumpFlags():
2415     *
2416     * |-------|-------|-------|-------|
2417     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2418     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2419     *                               1   PFLAG3_IS_LAID_OUT
2420     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2421     *                             1     PFLAG3_CALLED_SUPER
2422     *                            1      PFLAG3_APPLYING_INSETS
2423     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2424     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2425     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2426     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2427     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2428     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2429     *                     1             PFLAG3_SCROLL_INDICATOR_START
2430     *                    1              PFLAG3_SCROLL_INDICATOR_END
2431     *                   1               PFLAG3_ASSIST_BLOCKED
2432     *                  1                PFLAG3_POINTER_ICON_NULL
2433     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2434     *           11111111                PFLAG3_POINTER_ICON_MASK
2435     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2436     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2437     * |-------|-------|-------|-------|
2438     */
2439
2440    /**
2441     * Flag indicating that view has a transform animation set on it. This is used to track whether
2442     * an animation is cleared between successive frames, in order to tell the associated
2443     * DisplayList to clear its animation matrix.
2444     */
2445    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2446
2447    /**
2448     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2449     * animation is cleared between successive frames, in order to tell the associated
2450     * DisplayList to restore its alpha value.
2451     */
2452    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2453
2454    /**
2455     * Flag indicating that the view has been through at least one layout since it
2456     * was last attached to a window.
2457     */
2458    static final int PFLAG3_IS_LAID_OUT = 0x4;
2459
2460    /**
2461     * Flag indicating that a call to measure() was skipped and should be done
2462     * instead when layout() is invoked.
2463     */
2464    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2465
2466    /**
2467     * Flag indicating that an overridden method correctly called down to
2468     * the superclass implementation as required by the API spec.
2469     */
2470    static final int PFLAG3_CALLED_SUPER = 0x10;
2471
2472    /**
2473     * Flag indicating that we're in the process of applying window insets.
2474     */
2475    static final int PFLAG3_APPLYING_INSETS = 0x20;
2476
2477    /**
2478     * Flag indicating that we're in the process of fitting system windows using the old method.
2479     */
2480    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2481
2482    /**
2483     * Flag indicating that nested scrolling is enabled for this view.
2484     * The view will optionally cooperate with views up its parent chain to allow for
2485     * integrated nested scrolling along the same axis.
2486     */
2487    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2488
2489    /**
2490     * Flag indicating that the bottom scroll indicator should be displayed
2491     * when this view can scroll up.
2492     */
2493    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2494
2495    /**
2496     * Flag indicating that the bottom scroll indicator should be displayed
2497     * when this view can scroll down.
2498     */
2499    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2500
2501    /**
2502     * Flag indicating that the left scroll indicator should be displayed
2503     * when this view can scroll left.
2504     */
2505    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2506
2507    /**
2508     * Flag indicating that the right scroll indicator should be displayed
2509     * when this view can scroll right.
2510     */
2511    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2512
2513    /**
2514     * Flag indicating that the start scroll indicator should be displayed
2515     * when this view can scroll in the start direction.
2516     */
2517    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2518
2519    /**
2520     * Flag indicating that the end scroll indicator should be displayed
2521     * when this view can scroll in the end direction.
2522     */
2523    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2524
2525    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2526
2527    static final int SCROLL_INDICATORS_NONE = 0x0000;
2528
2529    /**
2530     * Mask for use with setFlags indicating bits used for indicating which
2531     * scroll indicators are enabled.
2532     */
2533    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2534            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2535            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2536            | PFLAG3_SCROLL_INDICATOR_END;
2537
2538    /**
2539     * Left-shift required to translate between public scroll indicator flags
2540     * and internal PFLAGS3 flags. When used as a right-shift, translates
2541     * PFLAGS3 flags to public flags.
2542     */
2543    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2544
2545    /** @hide */
2546    @Retention(RetentionPolicy.SOURCE)
2547    @IntDef(flag = true,
2548            value = {
2549                    SCROLL_INDICATOR_TOP,
2550                    SCROLL_INDICATOR_BOTTOM,
2551                    SCROLL_INDICATOR_LEFT,
2552                    SCROLL_INDICATOR_RIGHT,
2553                    SCROLL_INDICATOR_START,
2554                    SCROLL_INDICATOR_END,
2555            })
2556    public @interface ScrollIndicators {}
2557
2558    /**
2559     * Scroll indicator direction for the top edge of the view.
2560     *
2561     * @see #setScrollIndicators(int)
2562     * @see #setScrollIndicators(int, int)
2563     * @see #getScrollIndicators()
2564     */
2565    public static final int SCROLL_INDICATOR_TOP =
2566            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2567
2568    /**
2569     * Scroll indicator direction for the bottom edge of the view.
2570     *
2571     * @see #setScrollIndicators(int)
2572     * @see #setScrollIndicators(int, int)
2573     * @see #getScrollIndicators()
2574     */
2575    public static final int SCROLL_INDICATOR_BOTTOM =
2576            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2577
2578    /**
2579     * Scroll indicator direction for the left edge of the view.
2580     *
2581     * @see #setScrollIndicators(int)
2582     * @see #setScrollIndicators(int, int)
2583     * @see #getScrollIndicators()
2584     */
2585    public static final int SCROLL_INDICATOR_LEFT =
2586            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2587
2588    /**
2589     * Scroll indicator direction for the right edge of the view.
2590     *
2591     * @see #setScrollIndicators(int)
2592     * @see #setScrollIndicators(int, int)
2593     * @see #getScrollIndicators()
2594     */
2595    public static final int SCROLL_INDICATOR_RIGHT =
2596            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2597
2598    /**
2599     * Scroll indicator direction for the starting edge of the view.
2600     * <p>
2601     * Resolved according to the view's layout direction, see
2602     * {@link #getLayoutDirection()} for more information.
2603     *
2604     * @see #setScrollIndicators(int)
2605     * @see #setScrollIndicators(int, int)
2606     * @see #getScrollIndicators()
2607     */
2608    public static final int SCROLL_INDICATOR_START =
2609            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2610
2611    /**
2612     * Scroll indicator direction for the ending edge of the view.
2613     * <p>
2614     * Resolved according to the view's layout direction, see
2615     * {@link #getLayoutDirection()} for more information.
2616     *
2617     * @see #setScrollIndicators(int)
2618     * @see #setScrollIndicators(int, int)
2619     * @see #getScrollIndicators()
2620     */
2621    public static final int SCROLL_INDICATOR_END =
2622            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2623
2624    /**
2625     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2626     * into this view.<p>
2627     */
2628    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2629
2630    /**
2631     * The mask for use with private flags indicating bits used for pointer icon shapes.
2632     */
2633    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2634
2635    /**
2636     * Left-shift used for pointer icon shape values in private flags.
2637     */
2638    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2639
2640    /**
2641     * Value indicating no specific pointer icons.
2642     */
2643    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2644
2645    /**
2646     * Value indicating {@link PointerIcon.STYLE_NULL}.
2647     */
2648    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2649
2650    /**
2651     * The base value for other pointer icon shapes.
2652     */
2653    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2654
2655    /**
2656     * Whether this view has rendered elements that overlap (see {@link
2657     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2658     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2659     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2660     * determined by whatever {@link #hasOverlappingRendering()} returns.
2661     */
2662    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2663
2664    /**
2665     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2666     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2667     */
2668    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2669
2670    /* End of masks for mPrivateFlags3 */
2671
2672    /**
2673     * Always allow a user to over-scroll this view, provided it is a
2674     * view that can scroll.
2675     *
2676     * @see #getOverScrollMode()
2677     * @see #setOverScrollMode(int)
2678     */
2679    public static final int OVER_SCROLL_ALWAYS = 0;
2680
2681    /**
2682     * Allow a user to over-scroll this view only if the content is large
2683     * enough to meaningfully scroll, provided it is a view that can scroll.
2684     *
2685     * @see #getOverScrollMode()
2686     * @see #setOverScrollMode(int)
2687     */
2688    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2689
2690    /**
2691     * Never allow a user to over-scroll this view.
2692     *
2693     * @see #getOverScrollMode()
2694     * @see #setOverScrollMode(int)
2695     */
2696    public static final int OVER_SCROLL_NEVER = 2;
2697
2698    /**
2699     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2700     * requested the system UI (status bar) to be visible (the default).
2701     *
2702     * @see #setSystemUiVisibility(int)
2703     */
2704    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2705
2706    /**
2707     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2708     * system UI to enter an unobtrusive "low profile" mode.
2709     *
2710     * <p>This is for use in games, book readers, video players, or any other
2711     * "immersive" application where the usual system chrome is deemed too distracting.
2712     *
2713     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2714     *
2715     * @see #setSystemUiVisibility(int)
2716     */
2717    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2718
2719    /**
2720     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2721     * system navigation be temporarily hidden.
2722     *
2723     * <p>This is an even less obtrusive state than that called for by
2724     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2725     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2726     * those to disappear. This is useful (in conjunction with the
2727     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2728     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2729     * window flags) for displaying content using every last pixel on the display.
2730     *
2731     * <p>There is a limitation: because navigation controls are so important, the least user
2732     * interaction will cause them to reappear immediately.  When this happens, both
2733     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2734     * so that both elements reappear at the same time.
2735     *
2736     * @see #setSystemUiVisibility(int)
2737     */
2738    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2739
2740    /**
2741     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2742     * into the normal fullscreen mode so that its content can take over the screen
2743     * while still allowing the user to interact with the application.
2744     *
2745     * <p>This has the same visual effect as
2746     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2747     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2748     * meaning that non-critical screen decorations (such as the status bar) will be
2749     * hidden while the user is in the View's window, focusing the experience on
2750     * that content.  Unlike the window flag, if you are using ActionBar in
2751     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2752     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2753     * hide the action bar.
2754     *
2755     * <p>This approach to going fullscreen is best used over the window flag when
2756     * it is a transient state -- that is, the application does this at certain
2757     * points in its user interaction where it wants to allow the user to focus
2758     * on content, but not as a continuous state.  For situations where the application
2759     * would like to simply stay full screen the entire time (such as a game that
2760     * wants to take over the screen), the
2761     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2762     * is usually a better approach.  The state set here will be removed by the system
2763     * in various situations (such as the user moving to another application) like
2764     * the other system UI states.
2765     *
2766     * <p>When using this flag, the application should provide some easy facility
2767     * for the user to go out of it.  A common example would be in an e-book
2768     * reader, where tapping on the screen brings back whatever screen and UI
2769     * decorations that had been hidden while the user was immersed in reading
2770     * the book.
2771     *
2772     * @see #setSystemUiVisibility(int)
2773     */
2774    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2775
2776    /**
2777     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2778     * flags, we would like a stable view of the content insets given to
2779     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2780     * will always represent the worst case that the application can expect
2781     * as a continuous state.  In the stock Android UI this is the space for
2782     * the system bar, nav bar, and status bar, but not more transient elements
2783     * such as an input method.
2784     *
2785     * The stable layout your UI sees is based on the system UI modes you can
2786     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2787     * then you will get a stable layout for changes of the
2788     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2789     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2790     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2791     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2792     * with a stable layout.  (Note that you should avoid using
2793     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2794     *
2795     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2796     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2797     * then a hidden status bar will be considered a "stable" state for purposes
2798     * here.  This allows your UI to continually hide the status bar, while still
2799     * using the system UI flags to hide the action bar while still retaining
2800     * a stable layout.  Note that changing the window fullscreen flag will never
2801     * provide a stable layout for a clean transition.
2802     *
2803     * <p>If you are using ActionBar in
2804     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2805     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2806     * insets it adds to those given to the application.
2807     */
2808    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2809
2810    /**
2811     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2812     * to be laid out as if it has requested
2813     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2814     * allows it to avoid artifacts when switching in and out of that mode, at
2815     * the expense that some of its user interface may be covered by screen
2816     * decorations when they are shown.  You can perform layout of your inner
2817     * UI elements to account for the navigation system UI through the
2818     * {@link #fitSystemWindows(Rect)} method.
2819     */
2820    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2821
2822    /**
2823     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2824     * to be laid out as if it has requested
2825     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2826     * allows it to avoid artifacts when switching in and out of that mode, at
2827     * the expense that some of its user interface may be covered by screen
2828     * decorations when they are shown.  You can perform layout of your inner
2829     * UI elements to account for non-fullscreen system UI through the
2830     * {@link #fitSystemWindows(Rect)} method.
2831     */
2832    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2833
2834    /**
2835     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2836     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2837     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2838     * user interaction.
2839     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2840     * has an effect when used in combination with that flag.</p>
2841     */
2842    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2843
2844    /**
2845     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2846     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2847     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2848     * experience while also hiding the system bars.  If this flag is not set,
2849     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2850     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2851     * if the user swipes from the top of the screen.
2852     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2853     * system gestures, such as swiping from the top of the screen.  These transient system bars
2854     * will overlay app’s content, may have some degree of transparency, and will automatically
2855     * hide after a short timeout.
2856     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2857     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2858     * with one or both of those flags.</p>
2859     */
2860    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2861
2862    /**
2863     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2864     * is compatible with light status bar backgrounds.
2865     *
2866     * <p>For this to take effect, the window must request
2867     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2868     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2869     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2870     *         FLAG_TRANSLUCENT_STATUS}.
2871     *
2872     * @see android.R.attr#windowLightStatusBar
2873     */
2874    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2875
2876    /**
2877     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2878     */
2879    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2880
2881    /**
2882     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2883     */
2884    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2885
2886    /**
2887     * @hide
2888     *
2889     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2890     * out of the public fields to keep the undefined bits out of the developer's way.
2891     *
2892     * Flag to make the status bar not expandable.  Unless you also
2893     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2894     */
2895    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2896
2897    /**
2898     * @hide
2899     *
2900     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2901     * out of the public fields to keep the undefined bits out of the developer's way.
2902     *
2903     * Flag to hide notification icons and scrolling ticker text.
2904     */
2905    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2906
2907    /**
2908     * @hide
2909     *
2910     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2911     * out of the public fields to keep the undefined bits out of the developer's way.
2912     *
2913     * Flag to disable incoming notification alerts.  This will not block
2914     * icons, but it will block sound, vibrating and other visual or aural notifications.
2915     */
2916    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2917
2918    /**
2919     * @hide
2920     *
2921     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2922     * out of the public fields to keep the undefined bits out of the developer's way.
2923     *
2924     * Flag to hide only the scrolling ticker.  Note that
2925     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2926     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2927     */
2928    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2929
2930    /**
2931     * @hide
2932     *
2933     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2934     * out of the public fields to keep the undefined bits out of the developer's way.
2935     *
2936     * Flag to hide the center system info area.
2937     */
2938    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2939
2940    /**
2941     * @hide
2942     *
2943     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2944     * out of the public fields to keep the undefined bits out of the developer's way.
2945     *
2946     * Flag to hide only the home button.  Don't use this
2947     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2948     */
2949    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2950
2951    /**
2952     * @hide
2953     *
2954     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2955     * out of the public fields to keep the undefined bits out of the developer's way.
2956     *
2957     * Flag to hide only the back button. Don't use this
2958     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2959     */
2960    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2961
2962    /**
2963     * @hide
2964     *
2965     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2966     * out of the public fields to keep the undefined bits out of the developer's way.
2967     *
2968     * Flag to hide only the clock.  You might use this if your activity has
2969     * its own clock making the status bar's clock redundant.
2970     */
2971    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2972
2973    /**
2974     * @hide
2975     *
2976     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2977     * out of the public fields to keep the undefined bits out of the developer's way.
2978     *
2979     * Flag to hide only the recent apps button. Don't use this
2980     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2981     */
2982    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2983
2984    /**
2985     * @hide
2986     *
2987     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2988     * out of the public fields to keep the undefined bits out of the developer's way.
2989     *
2990     * Flag to disable the global search gesture. Don't use this
2991     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2992     */
2993    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2994
2995    /**
2996     * @hide
2997     *
2998     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2999     * out of the public fields to keep the undefined bits out of the developer's way.
3000     *
3001     * Flag to specify that the status bar is displayed in transient mode.
3002     */
3003    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3004
3005    /**
3006     * @hide
3007     *
3008     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3009     * out of the public fields to keep the undefined bits out of the developer's way.
3010     *
3011     * Flag to specify that the navigation bar is displayed in transient mode.
3012     */
3013    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3014
3015    /**
3016     * @hide
3017     *
3018     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3019     * out of the public fields to keep the undefined bits out of the developer's way.
3020     *
3021     * Flag to specify that the hidden status bar would like to be shown.
3022     */
3023    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3024
3025    /**
3026     * @hide
3027     *
3028     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3029     * out of the public fields to keep the undefined bits out of the developer's way.
3030     *
3031     * Flag to specify that the hidden navigation bar would like to be shown.
3032     */
3033    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3034
3035    /**
3036     * @hide
3037     *
3038     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3039     * out of the public fields to keep the undefined bits out of the developer's way.
3040     *
3041     * Flag to specify that the status bar is displayed in translucent mode.
3042     */
3043    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3044
3045    /**
3046     * @hide
3047     *
3048     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3049     * out of the public fields to keep the undefined bits out of the developer's way.
3050     *
3051     * Flag to specify that the navigation bar is displayed in translucent mode.
3052     */
3053    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3054
3055    /**
3056     * @hide
3057     *
3058     * Whether Recents is visible or not.
3059     */
3060    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3061
3062    /**
3063     * @hide
3064     *
3065     * Makes navigation bar transparent (but not the status bar).
3066     */
3067    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3068
3069    /**
3070     * @hide
3071     *
3072     * Makes status bar transparent (but not the navigation bar).
3073     */
3074    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3075
3076    /**
3077     * @hide
3078     *
3079     * Makes both status bar and navigation bar transparent.
3080     */
3081    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3082            | STATUS_BAR_TRANSPARENT;
3083
3084    /**
3085     * @hide
3086     */
3087    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3088
3089    /**
3090     * These are the system UI flags that can be cleared by events outside
3091     * of an application.  Currently this is just the ability to tap on the
3092     * screen while hiding the navigation bar to have it return.
3093     * @hide
3094     */
3095    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3096            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3097            | SYSTEM_UI_FLAG_FULLSCREEN;
3098
3099    /**
3100     * Flags that can impact the layout in relation to system UI.
3101     */
3102    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3103            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3104            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3105
3106    /** @hide */
3107    @IntDef(flag = true,
3108            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3109    @Retention(RetentionPolicy.SOURCE)
3110    public @interface FindViewFlags {}
3111
3112    /**
3113     * Find views that render the specified text.
3114     *
3115     * @see #findViewsWithText(ArrayList, CharSequence, int)
3116     */
3117    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3118
3119    /**
3120     * Find find views that contain the specified content description.
3121     *
3122     * @see #findViewsWithText(ArrayList, CharSequence, int)
3123     */
3124    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3125
3126    /**
3127     * Find views that contain {@link AccessibilityNodeProvider}. Such
3128     * a View is a root of virtual view hierarchy and may contain the searched
3129     * text. If this flag is set Views with providers are automatically
3130     * added and it is a responsibility of the client to call the APIs of
3131     * the provider to determine whether the virtual tree rooted at this View
3132     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3133     * representing the virtual views with this text.
3134     *
3135     * @see #findViewsWithText(ArrayList, CharSequence, int)
3136     *
3137     * @hide
3138     */
3139    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3140
3141    /**
3142     * The undefined cursor position.
3143     *
3144     * @hide
3145     */
3146    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3147
3148    /**
3149     * Indicates that the screen has changed state and is now off.
3150     *
3151     * @see #onScreenStateChanged(int)
3152     */
3153    public static final int SCREEN_STATE_OFF = 0x0;
3154
3155    /**
3156     * Indicates that the screen has changed state and is now on.
3157     *
3158     * @see #onScreenStateChanged(int)
3159     */
3160    public static final int SCREEN_STATE_ON = 0x1;
3161
3162    /**
3163     * Indicates no axis of view scrolling.
3164     */
3165    public static final int SCROLL_AXIS_NONE = 0;
3166
3167    /**
3168     * Indicates scrolling along the horizontal axis.
3169     */
3170    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3171
3172    /**
3173     * Indicates scrolling along the vertical axis.
3174     */
3175    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3176
3177    /**
3178     * Controls the over-scroll mode for this view.
3179     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3180     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3181     * and {@link #OVER_SCROLL_NEVER}.
3182     */
3183    private int mOverScrollMode;
3184
3185    /**
3186     * The parent this view is attached to.
3187     * {@hide}
3188     *
3189     * @see #getParent()
3190     */
3191    protected ViewParent mParent;
3192
3193    /**
3194     * {@hide}
3195     */
3196    AttachInfo mAttachInfo;
3197
3198    /**
3199     * {@hide}
3200     */
3201    @ViewDebug.ExportedProperty(flagMapping = {
3202        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3203                name = "FORCE_LAYOUT"),
3204        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3205                name = "LAYOUT_REQUIRED"),
3206        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3207            name = "DRAWING_CACHE_INVALID", outputIf = false),
3208        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3209        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3210        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3211        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3212    }, formatToHexString = true)
3213    int mPrivateFlags;
3214    int mPrivateFlags2;
3215    int mPrivateFlags3;
3216
3217    /**
3218     * This view's request for the visibility of the status bar.
3219     * @hide
3220     */
3221    @ViewDebug.ExportedProperty(flagMapping = {
3222        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3223                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3224                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3225        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3226                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3227                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3228        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3229                                equals = SYSTEM_UI_FLAG_VISIBLE,
3230                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3231    }, formatToHexString = true)
3232    int mSystemUiVisibility;
3233
3234    /**
3235     * Reference count for transient state.
3236     * @see #setHasTransientState(boolean)
3237     */
3238    int mTransientStateCount = 0;
3239
3240    /**
3241     * Count of how many windows this view has been attached to.
3242     */
3243    int mWindowAttachCount;
3244
3245    /**
3246     * The layout parameters associated with this view and used by the parent
3247     * {@link android.view.ViewGroup} to determine how this view should be
3248     * laid out.
3249     * {@hide}
3250     */
3251    protected ViewGroup.LayoutParams mLayoutParams;
3252
3253    /**
3254     * The view flags hold various views states.
3255     * {@hide}
3256     */
3257    @ViewDebug.ExportedProperty(formatToHexString = true)
3258    int mViewFlags;
3259
3260    static class TransformationInfo {
3261        /**
3262         * The transform matrix for the View. This transform is calculated internally
3263         * based on the translation, rotation, and scale properties.
3264         *
3265         * Do *not* use this variable directly; instead call getMatrix(), which will
3266         * load the value from the View's RenderNode.
3267         */
3268        private final Matrix mMatrix = new Matrix();
3269
3270        /**
3271         * The inverse transform matrix for the View. This transform is calculated
3272         * internally based on the translation, rotation, and scale properties.
3273         *
3274         * Do *not* use this variable directly; instead call getInverseMatrix(),
3275         * which will load the value from the View's RenderNode.
3276         */
3277        private Matrix mInverseMatrix;
3278
3279        /**
3280         * The opacity of the View. This is a value from 0 to 1, where 0 means
3281         * completely transparent and 1 means completely opaque.
3282         */
3283        @ViewDebug.ExportedProperty
3284        float mAlpha = 1f;
3285
3286        /**
3287         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3288         * property only used by transitions, which is composited with the other alpha
3289         * values to calculate the final visual alpha value.
3290         */
3291        float mTransitionAlpha = 1f;
3292    }
3293
3294    TransformationInfo mTransformationInfo;
3295
3296    /**
3297     * Current clip bounds. to which all drawing of this view are constrained.
3298     */
3299    Rect mClipBounds = null;
3300
3301    private boolean mLastIsOpaque;
3302
3303    /**
3304     * The distance in pixels from the left edge of this view's parent
3305     * to the left edge of this view.
3306     * {@hide}
3307     */
3308    @ViewDebug.ExportedProperty(category = "layout")
3309    protected int mLeft;
3310    /**
3311     * The distance in pixels from the left edge of this view's parent
3312     * to the right edge of this view.
3313     * {@hide}
3314     */
3315    @ViewDebug.ExportedProperty(category = "layout")
3316    protected int mRight;
3317    /**
3318     * The distance in pixels from the top edge of this view's parent
3319     * to the top edge of this view.
3320     * {@hide}
3321     */
3322    @ViewDebug.ExportedProperty(category = "layout")
3323    protected int mTop;
3324    /**
3325     * The distance in pixels from the top edge of this view's parent
3326     * to the bottom edge of this view.
3327     * {@hide}
3328     */
3329    @ViewDebug.ExportedProperty(category = "layout")
3330    protected int mBottom;
3331
3332    /**
3333     * The offset, in pixels, by which the content of this view is scrolled
3334     * horizontally.
3335     * {@hide}
3336     */
3337    @ViewDebug.ExportedProperty(category = "scrolling")
3338    protected int mScrollX;
3339    /**
3340     * The offset, in pixels, by which the content of this view is scrolled
3341     * vertically.
3342     * {@hide}
3343     */
3344    @ViewDebug.ExportedProperty(category = "scrolling")
3345    protected int mScrollY;
3346
3347    /**
3348     * The left padding in pixels, that is the distance in pixels between the
3349     * left edge of this view and the left edge of its content.
3350     * {@hide}
3351     */
3352    @ViewDebug.ExportedProperty(category = "padding")
3353    protected int mPaddingLeft = 0;
3354    /**
3355     * The right padding in pixels, that is the distance in pixels between the
3356     * right edge of this view and the right edge of its content.
3357     * {@hide}
3358     */
3359    @ViewDebug.ExportedProperty(category = "padding")
3360    protected int mPaddingRight = 0;
3361    /**
3362     * The top padding in pixels, that is the distance in pixels between the
3363     * top edge of this view and the top edge of its content.
3364     * {@hide}
3365     */
3366    @ViewDebug.ExportedProperty(category = "padding")
3367    protected int mPaddingTop;
3368    /**
3369     * The bottom padding in pixels, that is the distance in pixels between the
3370     * bottom edge of this view and the bottom edge of its content.
3371     * {@hide}
3372     */
3373    @ViewDebug.ExportedProperty(category = "padding")
3374    protected int mPaddingBottom;
3375
3376    /**
3377     * The layout insets in pixels, that is the distance in pixels between the
3378     * visible edges of this view its bounds.
3379     */
3380    private Insets mLayoutInsets;
3381
3382    /**
3383     * Briefly describes the view and is primarily used for accessibility support.
3384     */
3385    private CharSequence mContentDescription;
3386
3387    /**
3388     * Specifies the id of a view for which this view serves as a label for
3389     * accessibility purposes.
3390     */
3391    private int mLabelForId = View.NO_ID;
3392
3393    /**
3394     * Predicate for matching labeled view id with its label for
3395     * accessibility purposes.
3396     */
3397    private MatchLabelForPredicate mMatchLabelForPredicate;
3398
3399    /**
3400     * Specifies a view before which this one is visited in accessibility traversal.
3401     */
3402    private int mAccessibilityTraversalBeforeId = NO_ID;
3403
3404    /**
3405     * Specifies a view after which this one is visited in accessibility traversal.
3406     */
3407    private int mAccessibilityTraversalAfterId = NO_ID;
3408
3409    /**
3410     * Predicate for matching a view by its id.
3411     */
3412    private MatchIdPredicate mMatchIdPredicate;
3413
3414    /**
3415     * Cache the paddingRight set by the user to append to the scrollbar's size.
3416     *
3417     * @hide
3418     */
3419    @ViewDebug.ExportedProperty(category = "padding")
3420    protected int mUserPaddingRight;
3421
3422    /**
3423     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3424     *
3425     * @hide
3426     */
3427    @ViewDebug.ExportedProperty(category = "padding")
3428    protected int mUserPaddingBottom;
3429
3430    /**
3431     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3432     *
3433     * @hide
3434     */
3435    @ViewDebug.ExportedProperty(category = "padding")
3436    protected int mUserPaddingLeft;
3437
3438    /**
3439     * Cache the paddingStart set by the user to append to the scrollbar's size.
3440     *
3441     */
3442    @ViewDebug.ExportedProperty(category = "padding")
3443    int mUserPaddingStart;
3444
3445    /**
3446     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3447     *
3448     */
3449    @ViewDebug.ExportedProperty(category = "padding")
3450    int mUserPaddingEnd;
3451
3452    /**
3453     * Cache initial left padding.
3454     *
3455     * @hide
3456     */
3457    int mUserPaddingLeftInitial;
3458
3459    /**
3460     * Cache initial right padding.
3461     *
3462     * @hide
3463     */
3464    int mUserPaddingRightInitial;
3465
3466    /**
3467     * Default undefined padding
3468     */
3469    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3470
3471    /**
3472     * Cache if a left padding has been defined
3473     */
3474    private boolean mLeftPaddingDefined = false;
3475
3476    /**
3477     * Cache if a right padding has been defined
3478     */
3479    private boolean mRightPaddingDefined = false;
3480
3481    /**
3482     * @hide
3483     */
3484    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3485    /**
3486     * @hide
3487     */
3488    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3489
3490    private LongSparseLongArray mMeasureCache;
3491
3492    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3493    private Drawable mBackground;
3494    private TintInfo mBackgroundTint;
3495
3496    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3497    private ForegroundInfo mForegroundInfo;
3498
3499    private Drawable mScrollIndicatorDrawable;
3500
3501    /**
3502     * RenderNode used for backgrounds.
3503     * <p>
3504     * When non-null and valid, this is expected to contain an up-to-date copy
3505     * of the background drawable. It is cleared on temporary detach, and reset
3506     * on cleanup.
3507     */
3508    private RenderNode mBackgroundRenderNode;
3509
3510    private int mBackgroundResource;
3511    private boolean mBackgroundSizeChanged;
3512
3513    private String mTransitionName;
3514
3515    static class TintInfo {
3516        ColorStateList mTintList;
3517        PorterDuff.Mode mTintMode;
3518        boolean mHasTintMode;
3519        boolean mHasTintList;
3520    }
3521
3522    private static class ForegroundInfo {
3523        private Drawable mDrawable;
3524        private TintInfo mTintInfo;
3525        private int mGravity = Gravity.FILL;
3526        private boolean mInsidePadding = true;
3527        private boolean mBoundsChanged = true;
3528        private final Rect mSelfBounds = new Rect();
3529        private final Rect mOverlayBounds = new Rect();
3530    }
3531
3532    static class ListenerInfo {
3533        /**
3534         * Listener used to dispatch focus change events.
3535         * This field should be made private, so it is hidden from the SDK.
3536         * {@hide}
3537         */
3538        protected OnFocusChangeListener mOnFocusChangeListener;
3539
3540        /**
3541         * Listeners for layout change events.
3542         */
3543        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3544
3545        protected OnScrollChangeListener mOnScrollChangeListener;
3546
3547        /**
3548         * Listeners for attach events.
3549         */
3550        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3551
3552        /**
3553         * Listener used to dispatch click events.
3554         * This field should be made private, so it is hidden from the SDK.
3555         * {@hide}
3556         */
3557        public OnClickListener mOnClickListener;
3558
3559        /**
3560         * Listener used to dispatch long click events.
3561         * This field should be made private, so it is hidden from the SDK.
3562         * {@hide}
3563         */
3564        protected OnLongClickListener mOnLongClickListener;
3565
3566        /**
3567         * Listener used to dispatch context click events. This field should be made private, so it
3568         * is hidden from the SDK.
3569         * {@hide}
3570         */
3571        protected OnContextClickListener mOnContextClickListener;
3572
3573        /**
3574         * Listener used to build the context menu.
3575         * This field should be made private, so it is hidden from the SDK.
3576         * {@hide}
3577         */
3578        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3579
3580        private OnKeyListener mOnKeyListener;
3581
3582        private OnTouchListener mOnTouchListener;
3583
3584        private OnHoverListener mOnHoverListener;
3585
3586        private OnGenericMotionListener mOnGenericMotionListener;
3587
3588        private OnDragListener mOnDragListener;
3589
3590        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3591
3592        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3593    }
3594
3595    ListenerInfo mListenerInfo;
3596
3597    // Temporary values used to hold (x,y) coordinates when delegating from the
3598    // two-arg performLongClick() method to the legacy no-arg version.
3599    private float mLongClickX = Float.NaN;
3600    private float mLongClickY = Float.NaN;
3601
3602    /**
3603     * The application environment this view lives in.
3604     * This field should be made private, so it is hidden from the SDK.
3605     * {@hide}
3606     */
3607    @ViewDebug.ExportedProperty(deepExport = true)
3608    protected Context mContext;
3609
3610    private final Resources mResources;
3611
3612    private ScrollabilityCache mScrollCache;
3613
3614    private int[] mDrawableState = null;
3615
3616    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3617
3618    /**
3619     * Animator that automatically runs based on state changes.
3620     */
3621    private StateListAnimator mStateListAnimator;
3622
3623    /**
3624     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3625     * the user may specify which view to go to next.
3626     */
3627    private int mNextFocusLeftId = View.NO_ID;
3628
3629    /**
3630     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3631     * the user may specify which view to go to next.
3632     */
3633    private int mNextFocusRightId = View.NO_ID;
3634
3635    /**
3636     * When this view has focus and the next focus is {@link #FOCUS_UP},
3637     * the user may specify which view to go to next.
3638     */
3639    private int mNextFocusUpId = View.NO_ID;
3640
3641    /**
3642     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3643     * the user may specify which view to go to next.
3644     */
3645    private int mNextFocusDownId = View.NO_ID;
3646
3647    /**
3648     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3649     * the user may specify which view to go to next.
3650     */
3651    int mNextFocusForwardId = View.NO_ID;
3652
3653    private CheckForLongPress mPendingCheckForLongPress;
3654    private CheckForTap mPendingCheckForTap = null;
3655    private PerformClick mPerformClick;
3656    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3657
3658    private UnsetPressedState mUnsetPressedState;
3659
3660    /**
3661     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3662     * up event while a long press is invoked as soon as the long press duration is reached, so
3663     * a long press could be performed before the tap is checked, in which case the tap's action
3664     * should not be invoked.
3665     */
3666    private boolean mHasPerformedLongPress;
3667
3668    /**
3669     * Whether a context click button is currently pressed down. This is true when the stylus is
3670     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3671     * pressed. This is false once the button is released or if the stylus has been lifted.
3672     */
3673    private boolean mInContextButtonPress;
3674
3675    /**
3676     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3677     * true after a stylus button press has occured, when the next up event should not be recognized
3678     * as a tap.
3679     */
3680    private boolean mIgnoreNextUpEvent;
3681
3682    /**
3683     * The minimum height of the view. We'll try our best to have the height
3684     * of this view to at least this amount.
3685     */
3686    @ViewDebug.ExportedProperty(category = "measurement")
3687    private int mMinHeight;
3688
3689    /**
3690     * The minimum width of the view. We'll try our best to have the width
3691     * of this view to at least this amount.
3692     */
3693    @ViewDebug.ExportedProperty(category = "measurement")
3694    private int mMinWidth;
3695
3696    /**
3697     * The delegate to handle touch events that are physically in this view
3698     * but should be handled by another view.
3699     */
3700    private TouchDelegate mTouchDelegate = null;
3701
3702    /**
3703     * Solid color to use as a background when creating the drawing cache. Enables
3704     * the cache to use 16 bit bitmaps instead of 32 bit.
3705     */
3706    private int mDrawingCacheBackgroundColor = 0;
3707
3708    /**
3709     * Special tree observer used when mAttachInfo is null.
3710     */
3711    private ViewTreeObserver mFloatingTreeObserver;
3712
3713    /**
3714     * Cache the touch slop from the context that created the view.
3715     */
3716    private int mTouchSlop;
3717
3718    /**
3719     * Object that handles automatic animation of view properties.
3720     */
3721    private ViewPropertyAnimator mAnimator = null;
3722
3723    /**
3724     * List of registered FrameMetricsObservers.
3725     */
3726    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3727
3728    /**
3729     * Flag indicating that a drag can cross window boundaries.  When
3730     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3731     * with this flag set, all visible applications will be able to participate
3732     * in the drag operation and receive the dragged content.
3733     *
3734     * If this is the only flag set, then the drag recipient will only have access to text data
3735     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3736     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags.
3737     */
3738    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3739
3740    /**
3741     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3742     * request read access to the content URI(s) contained in the {@link ClipData} object.
3743     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3744     */
3745    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3746
3747    /**
3748     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3749     * request write access to the content URI(s) contained in the {@link ClipData} object.
3750     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3751     */
3752    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3753
3754    /**
3755     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3756     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3757     * reboots until explicitly revoked with
3758     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3759     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3760     */
3761    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3762            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3763
3764    /**
3765     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3766     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3767     * match against the original granted URI.
3768     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3769     */
3770    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3771            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3772
3773    /**
3774     * Flag indicating that the drag shadow will be opaque.  When
3775     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3776     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3777     */
3778    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3779
3780    /**
3781     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3782     */
3783    private float mVerticalScrollFactor;
3784
3785    /**
3786     * Position of the vertical scroll bar.
3787     */
3788    private int mVerticalScrollbarPosition;
3789
3790    /**
3791     * Position the scroll bar at the default position as determined by the system.
3792     */
3793    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3794
3795    /**
3796     * Position the scroll bar along the left edge.
3797     */
3798    public static final int SCROLLBAR_POSITION_LEFT = 1;
3799
3800    /**
3801     * Position the scroll bar along the right edge.
3802     */
3803    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3804
3805    /**
3806     * Indicates that the view does not have a layer.
3807     *
3808     * @see #getLayerType()
3809     * @see #setLayerType(int, android.graphics.Paint)
3810     * @see #LAYER_TYPE_SOFTWARE
3811     * @see #LAYER_TYPE_HARDWARE
3812     */
3813    public static final int LAYER_TYPE_NONE = 0;
3814
3815    /**
3816     * <p>Indicates that the view has a software layer. A software layer is backed
3817     * by a bitmap and causes the view to be rendered using Android's software
3818     * rendering pipeline, even if hardware acceleration is enabled.</p>
3819     *
3820     * <p>Software layers have various usages:</p>
3821     * <p>When the application is not using hardware acceleration, a software layer
3822     * is useful to apply a specific color filter and/or blending mode and/or
3823     * translucency to a view and all its children.</p>
3824     * <p>When the application is using hardware acceleration, a software layer
3825     * is useful to render drawing primitives not supported by the hardware
3826     * accelerated pipeline. It can also be used to cache a complex view tree
3827     * into a texture and reduce the complexity of drawing operations. For instance,
3828     * when animating a complex view tree with a translation, a software layer can
3829     * be used to render the view tree only once.</p>
3830     * <p>Software layers should be avoided when the affected view tree updates
3831     * often. Every update will require to re-render the software layer, which can
3832     * potentially be slow (particularly when hardware acceleration is turned on
3833     * since the layer will have to be uploaded into a hardware texture after every
3834     * update.)</p>
3835     *
3836     * @see #getLayerType()
3837     * @see #setLayerType(int, android.graphics.Paint)
3838     * @see #LAYER_TYPE_NONE
3839     * @see #LAYER_TYPE_HARDWARE
3840     */
3841    public static final int LAYER_TYPE_SOFTWARE = 1;
3842
3843    /**
3844     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3845     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3846     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3847     * rendering pipeline, but only if hardware acceleration is turned on for the
3848     * view hierarchy. When hardware acceleration is turned off, hardware layers
3849     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3850     *
3851     * <p>A hardware layer is useful to apply a specific color filter and/or
3852     * blending mode and/or translucency to a view and all its children.</p>
3853     * <p>A hardware layer can be used to cache a complex view tree into a
3854     * texture and reduce the complexity of drawing operations. For instance,
3855     * when animating a complex view tree with a translation, a hardware layer can
3856     * be used to render the view tree only once.</p>
3857     * <p>A hardware layer can also be used to increase the rendering quality when
3858     * rotation transformations are applied on a view. It can also be used to
3859     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3860     *
3861     * @see #getLayerType()
3862     * @see #setLayerType(int, android.graphics.Paint)
3863     * @see #LAYER_TYPE_NONE
3864     * @see #LAYER_TYPE_SOFTWARE
3865     */
3866    public static final int LAYER_TYPE_HARDWARE = 2;
3867
3868    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3869            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3870            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3871            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3872    })
3873    int mLayerType = LAYER_TYPE_NONE;
3874    Paint mLayerPaint;
3875
3876    /**
3877     * Set to true when drawing cache is enabled and cannot be created.
3878     *
3879     * @hide
3880     */
3881    public boolean mCachingFailed;
3882    private Bitmap mDrawingCache;
3883    private Bitmap mUnscaledDrawingCache;
3884
3885    /**
3886     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3887     * <p>
3888     * When non-null and valid, this is expected to contain an up-to-date copy
3889     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3890     * cleanup.
3891     */
3892    final RenderNode mRenderNode;
3893
3894    /**
3895     * Set to true when the view is sending hover accessibility events because it
3896     * is the innermost hovered view.
3897     */
3898    private boolean mSendingHoverAccessibilityEvents;
3899
3900    /**
3901     * Delegate for injecting accessibility functionality.
3902     */
3903    AccessibilityDelegate mAccessibilityDelegate;
3904
3905    /**
3906     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3907     * and add/remove objects to/from the overlay directly through the Overlay methods.
3908     */
3909    ViewOverlay mOverlay;
3910
3911    /**
3912     * The currently active parent view for receiving delegated nested scrolling events.
3913     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3914     * by {@link #stopNestedScroll()} at the same point where we clear
3915     * requestDisallowInterceptTouchEvent.
3916     */
3917    private ViewParent mNestedScrollingParent;
3918
3919    /**
3920     * Consistency verifier for debugging purposes.
3921     * @hide
3922     */
3923    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3924            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3925                    new InputEventConsistencyVerifier(this, 0) : null;
3926
3927    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3928
3929    private int[] mTempNestedScrollConsumed;
3930
3931    /**
3932     * An overlay is going to draw this View instead of being drawn as part of this
3933     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3934     * when this view is invalidated.
3935     */
3936    GhostView mGhostView;
3937
3938    /**
3939     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3940     * @hide
3941     */
3942    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3943    public String[] mAttributes;
3944
3945    /**
3946     * Maps a Resource id to its name.
3947     */
3948    private static SparseArray<String> mAttributeMap;
3949
3950    /**
3951     * Queue of pending runnables. Used to postpone calls to post() until this
3952     * view is attached and has a handler.
3953     */
3954    private HandlerActionQueue mRunQueue;
3955
3956    /**
3957     * The pointer icon when the mouse hovers on this view. The default is null.
3958     */
3959    private PointerIcon mPointerIcon;
3960
3961    /**
3962     * @hide
3963     */
3964    String mStartActivityRequestWho;
3965
3966    /**
3967     * Simple constructor to use when creating a view from code.
3968     *
3969     * @param context The Context the view is running in, through which it can
3970     *        access the current theme, resources, etc.
3971     */
3972    public View(Context context) {
3973        mContext = context;
3974        mResources = context != null ? context.getResources() : null;
3975        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3976        // Set some flags defaults
3977        mPrivateFlags2 =
3978                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3979                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3980                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3981                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3982                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3983                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3984        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3985        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3986        mUserPaddingStart = UNDEFINED_PADDING;
3987        mUserPaddingEnd = UNDEFINED_PADDING;
3988        mRenderNode = RenderNode.create(getClass().getName(), this);
3989
3990        if (!sCompatibilityDone && context != null) {
3991            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3992
3993            // Older apps may need this compatibility hack for measurement.
3994            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3995
3996            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3997            // of whether a layout was requested on that View.
3998            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3999
4000            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4001
4002            // In M and newer, our widgets can pass a "hint" value in the size
4003            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4004            // know what the expected parent size is going to be, so e.g. list items can size
4005            // themselves at 1/3 the size of their container. It breaks older apps though,
4006            // specifically apps that use some popular open source libraries.
4007            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4008
4009            // Old versions of the platform would give different results from
4010            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4011            // modes, so we always need to run an additional EXACTLY pass.
4012            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4013
4014            // Prior to N, layout params could change without requiring a
4015            // subsequent call to setLayoutParams() and they would usually
4016            // work. Partial layout breaks this assumption.
4017            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4018
4019            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4020            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4021            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4022
4023            sCompatibilityDone = true;
4024        }
4025    }
4026
4027    /**
4028     * Constructor that is called when inflating a view from XML. This is called
4029     * when a view is being constructed from an XML file, supplying attributes
4030     * that were specified in the XML file. This version uses a default style of
4031     * 0, so the only attribute values applied are those in the Context's Theme
4032     * and the given AttributeSet.
4033     *
4034     * <p>
4035     * The method onFinishInflate() will be called after all children have been
4036     * added.
4037     *
4038     * @param context The Context the view is running in, through which it can
4039     *        access the current theme, resources, etc.
4040     * @param attrs The attributes of the XML tag that is inflating the view.
4041     * @see #View(Context, AttributeSet, int)
4042     */
4043    public View(Context context, @Nullable AttributeSet attrs) {
4044        this(context, attrs, 0);
4045    }
4046
4047    /**
4048     * Perform inflation from XML and apply a class-specific base style from a
4049     * theme attribute. This constructor of View allows subclasses to use their
4050     * own base style when they are inflating. For example, a Button class's
4051     * constructor would call this version of the super class constructor and
4052     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4053     * allows the theme's button style to modify all of the base view attributes
4054     * (in particular its background) as well as the Button class's attributes.
4055     *
4056     * @param context The Context the view is running in, through which it can
4057     *        access the current theme, resources, etc.
4058     * @param attrs The attributes of the XML tag that is inflating the view.
4059     * @param defStyleAttr An attribute in the current theme that contains a
4060     *        reference to a style resource that supplies default values for
4061     *        the view. Can be 0 to not look for defaults.
4062     * @see #View(Context, AttributeSet)
4063     */
4064    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4065        this(context, attrs, defStyleAttr, 0);
4066    }
4067
4068    /**
4069     * Perform inflation from XML and apply a class-specific base style from a
4070     * theme attribute or style resource. This constructor of View allows
4071     * subclasses to use their own base style when they are inflating.
4072     * <p>
4073     * When determining the final value of a particular attribute, there are
4074     * four inputs that come into play:
4075     * <ol>
4076     * <li>Any attribute values in the given AttributeSet.
4077     * <li>The style resource specified in the AttributeSet (named "style").
4078     * <li>The default style specified by <var>defStyleAttr</var>.
4079     * <li>The default style specified by <var>defStyleRes</var>.
4080     * <li>The base values in this theme.
4081     * </ol>
4082     * <p>
4083     * Each of these inputs is considered in-order, with the first listed taking
4084     * precedence over the following ones. In other words, if in the
4085     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4086     * , then the button's text will <em>always</em> be black, regardless of
4087     * what is specified in any of the styles.
4088     *
4089     * @param context The Context the view is running in, through which it can
4090     *        access the current theme, resources, etc.
4091     * @param attrs The attributes of the XML tag that is inflating the view.
4092     * @param defStyleAttr An attribute in the current theme that contains a
4093     *        reference to a style resource that supplies default values for
4094     *        the view. Can be 0 to not look for defaults.
4095     * @param defStyleRes A resource identifier of a style resource that
4096     *        supplies default values for the view, used only if
4097     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4098     *        to not look for defaults.
4099     * @see #View(Context, AttributeSet, int)
4100     */
4101    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4102        this(context);
4103
4104        final TypedArray a = context.obtainStyledAttributes(
4105                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4106
4107        if (mDebugViewAttributes) {
4108            saveAttributeData(attrs, a);
4109        }
4110
4111        Drawable background = null;
4112
4113        int leftPadding = -1;
4114        int topPadding = -1;
4115        int rightPadding = -1;
4116        int bottomPadding = -1;
4117        int startPadding = UNDEFINED_PADDING;
4118        int endPadding = UNDEFINED_PADDING;
4119
4120        int padding = -1;
4121
4122        int viewFlagValues = 0;
4123        int viewFlagMasks = 0;
4124
4125        boolean setScrollContainer = false;
4126
4127        int x = 0;
4128        int y = 0;
4129
4130        float tx = 0;
4131        float ty = 0;
4132        float tz = 0;
4133        float elevation = 0;
4134        float rotation = 0;
4135        float rotationX = 0;
4136        float rotationY = 0;
4137        float sx = 1f;
4138        float sy = 1f;
4139        boolean transformSet = false;
4140
4141        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4142        int overScrollMode = mOverScrollMode;
4143        boolean initializeScrollbars = false;
4144        boolean initializeScrollIndicators = false;
4145
4146        boolean startPaddingDefined = false;
4147        boolean endPaddingDefined = false;
4148        boolean leftPaddingDefined = false;
4149        boolean rightPaddingDefined = false;
4150
4151        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4152
4153        final int N = a.getIndexCount();
4154        for (int i = 0; i < N; i++) {
4155            int attr = a.getIndex(i);
4156            switch (attr) {
4157                case com.android.internal.R.styleable.View_background:
4158                    background = a.getDrawable(attr);
4159                    break;
4160                case com.android.internal.R.styleable.View_padding:
4161                    padding = a.getDimensionPixelSize(attr, -1);
4162                    mUserPaddingLeftInitial = padding;
4163                    mUserPaddingRightInitial = padding;
4164                    leftPaddingDefined = true;
4165                    rightPaddingDefined = true;
4166                    break;
4167                 case com.android.internal.R.styleable.View_paddingLeft:
4168                    leftPadding = a.getDimensionPixelSize(attr, -1);
4169                    mUserPaddingLeftInitial = leftPadding;
4170                    leftPaddingDefined = true;
4171                    break;
4172                case com.android.internal.R.styleable.View_paddingTop:
4173                    topPadding = a.getDimensionPixelSize(attr, -1);
4174                    break;
4175                case com.android.internal.R.styleable.View_paddingRight:
4176                    rightPadding = a.getDimensionPixelSize(attr, -1);
4177                    mUserPaddingRightInitial = rightPadding;
4178                    rightPaddingDefined = true;
4179                    break;
4180                case com.android.internal.R.styleable.View_paddingBottom:
4181                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4182                    break;
4183                case com.android.internal.R.styleable.View_paddingStart:
4184                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4185                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4186                    break;
4187                case com.android.internal.R.styleable.View_paddingEnd:
4188                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4189                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4190                    break;
4191                case com.android.internal.R.styleable.View_scrollX:
4192                    x = a.getDimensionPixelOffset(attr, 0);
4193                    break;
4194                case com.android.internal.R.styleable.View_scrollY:
4195                    y = a.getDimensionPixelOffset(attr, 0);
4196                    break;
4197                case com.android.internal.R.styleable.View_alpha:
4198                    setAlpha(a.getFloat(attr, 1f));
4199                    break;
4200                case com.android.internal.R.styleable.View_transformPivotX:
4201                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4202                    break;
4203                case com.android.internal.R.styleable.View_transformPivotY:
4204                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4205                    break;
4206                case com.android.internal.R.styleable.View_translationX:
4207                    tx = a.getDimensionPixelOffset(attr, 0);
4208                    transformSet = true;
4209                    break;
4210                case com.android.internal.R.styleable.View_translationY:
4211                    ty = a.getDimensionPixelOffset(attr, 0);
4212                    transformSet = true;
4213                    break;
4214                case com.android.internal.R.styleable.View_translationZ:
4215                    tz = a.getDimensionPixelOffset(attr, 0);
4216                    transformSet = true;
4217                    break;
4218                case com.android.internal.R.styleable.View_elevation:
4219                    elevation = a.getDimensionPixelOffset(attr, 0);
4220                    transformSet = true;
4221                    break;
4222                case com.android.internal.R.styleable.View_rotation:
4223                    rotation = a.getFloat(attr, 0);
4224                    transformSet = true;
4225                    break;
4226                case com.android.internal.R.styleable.View_rotationX:
4227                    rotationX = a.getFloat(attr, 0);
4228                    transformSet = true;
4229                    break;
4230                case com.android.internal.R.styleable.View_rotationY:
4231                    rotationY = a.getFloat(attr, 0);
4232                    transformSet = true;
4233                    break;
4234                case com.android.internal.R.styleable.View_scaleX:
4235                    sx = a.getFloat(attr, 1f);
4236                    transformSet = true;
4237                    break;
4238                case com.android.internal.R.styleable.View_scaleY:
4239                    sy = a.getFloat(attr, 1f);
4240                    transformSet = true;
4241                    break;
4242                case com.android.internal.R.styleable.View_id:
4243                    mID = a.getResourceId(attr, NO_ID);
4244                    break;
4245                case com.android.internal.R.styleable.View_tag:
4246                    mTag = a.getText(attr);
4247                    break;
4248                case com.android.internal.R.styleable.View_fitsSystemWindows:
4249                    if (a.getBoolean(attr, false)) {
4250                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4251                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4252                    }
4253                    break;
4254                case com.android.internal.R.styleable.View_focusable:
4255                    if (a.getBoolean(attr, false)) {
4256                        viewFlagValues |= FOCUSABLE;
4257                        viewFlagMasks |= FOCUSABLE_MASK;
4258                    }
4259                    break;
4260                case com.android.internal.R.styleable.View_focusableInTouchMode:
4261                    if (a.getBoolean(attr, false)) {
4262                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4263                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4264                    }
4265                    break;
4266                case com.android.internal.R.styleable.View_clickable:
4267                    if (a.getBoolean(attr, false)) {
4268                        viewFlagValues |= CLICKABLE;
4269                        viewFlagMasks |= CLICKABLE;
4270                    }
4271                    break;
4272                case com.android.internal.R.styleable.View_longClickable:
4273                    if (a.getBoolean(attr, false)) {
4274                        viewFlagValues |= LONG_CLICKABLE;
4275                        viewFlagMasks |= LONG_CLICKABLE;
4276                    }
4277                    break;
4278                case com.android.internal.R.styleable.View_contextClickable:
4279                    if (a.getBoolean(attr, false)) {
4280                        viewFlagValues |= CONTEXT_CLICKABLE;
4281                        viewFlagMasks |= CONTEXT_CLICKABLE;
4282                    }
4283                    break;
4284                case com.android.internal.R.styleable.View_saveEnabled:
4285                    if (!a.getBoolean(attr, true)) {
4286                        viewFlagValues |= SAVE_DISABLED;
4287                        viewFlagMasks |= SAVE_DISABLED_MASK;
4288                    }
4289                    break;
4290                case com.android.internal.R.styleable.View_duplicateParentState:
4291                    if (a.getBoolean(attr, false)) {
4292                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4293                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4294                    }
4295                    break;
4296                case com.android.internal.R.styleable.View_visibility:
4297                    final int visibility = a.getInt(attr, 0);
4298                    if (visibility != 0) {
4299                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4300                        viewFlagMasks |= VISIBILITY_MASK;
4301                    }
4302                    break;
4303                case com.android.internal.R.styleable.View_layoutDirection:
4304                    // Clear any layout direction flags (included resolved bits) already set
4305                    mPrivateFlags2 &=
4306                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4307                    // Set the layout direction flags depending on the value of the attribute
4308                    final int layoutDirection = a.getInt(attr, -1);
4309                    final int value = (layoutDirection != -1) ?
4310                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4311                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4312                    break;
4313                case com.android.internal.R.styleable.View_drawingCacheQuality:
4314                    final int cacheQuality = a.getInt(attr, 0);
4315                    if (cacheQuality != 0) {
4316                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4317                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4318                    }
4319                    break;
4320                case com.android.internal.R.styleable.View_contentDescription:
4321                    setContentDescription(a.getString(attr));
4322                    break;
4323                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4324                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4325                    break;
4326                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4327                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4328                    break;
4329                case com.android.internal.R.styleable.View_labelFor:
4330                    setLabelFor(a.getResourceId(attr, NO_ID));
4331                    break;
4332                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4333                    if (!a.getBoolean(attr, true)) {
4334                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4335                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4336                    }
4337                    break;
4338                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4339                    if (!a.getBoolean(attr, true)) {
4340                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4341                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4342                    }
4343                    break;
4344                case R.styleable.View_scrollbars:
4345                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4346                    if (scrollbars != SCROLLBARS_NONE) {
4347                        viewFlagValues |= scrollbars;
4348                        viewFlagMasks |= SCROLLBARS_MASK;
4349                        initializeScrollbars = true;
4350                    }
4351                    break;
4352                //noinspection deprecation
4353                case R.styleable.View_fadingEdge:
4354                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4355                        // Ignore the attribute starting with ICS
4356                        break;
4357                    }
4358                    // With builds < ICS, fall through and apply fading edges
4359                case R.styleable.View_requiresFadingEdge:
4360                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4361                    if (fadingEdge != FADING_EDGE_NONE) {
4362                        viewFlagValues |= fadingEdge;
4363                        viewFlagMasks |= FADING_EDGE_MASK;
4364                        initializeFadingEdgeInternal(a);
4365                    }
4366                    break;
4367                case R.styleable.View_scrollbarStyle:
4368                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4369                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4370                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4371                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4372                    }
4373                    break;
4374                case R.styleable.View_isScrollContainer:
4375                    setScrollContainer = true;
4376                    if (a.getBoolean(attr, false)) {
4377                        setScrollContainer(true);
4378                    }
4379                    break;
4380                case com.android.internal.R.styleable.View_keepScreenOn:
4381                    if (a.getBoolean(attr, false)) {
4382                        viewFlagValues |= KEEP_SCREEN_ON;
4383                        viewFlagMasks |= KEEP_SCREEN_ON;
4384                    }
4385                    break;
4386                case R.styleable.View_filterTouchesWhenObscured:
4387                    if (a.getBoolean(attr, false)) {
4388                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4389                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4390                    }
4391                    break;
4392                case R.styleable.View_nextFocusLeft:
4393                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4394                    break;
4395                case R.styleable.View_nextFocusRight:
4396                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4397                    break;
4398                case R.styleable.View_nextFocusUp:
4399                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4400                    break;
4401                case R.styleable.View_nextFocusDown:
4402                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4403                    break;
4404                case R.styleable.View_nextFocusForward:
4405                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4406                    break;
4407                case R.styleable.View_minWidth:
4408                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4409                    break;
4410                case R.styleable.View_minHeight:
4411                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4412                    break;
4413                case R.styleable.View_onClick:
4414                    if (context.isRestricted()) {
4415                        throw new IllegalStateException("The android:onClick attribute cannot "
4416                                + "be used within a restricted context");
4417                    }
4418
4419                    final String handlerName = a.getString(attr);
4420                    if (handlerName != null) {
4421                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4422                    }
4423                    break;
4424                case R.styleable.View_overScrollMode:
4425                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4426                    break;
4427                case R.styleable.View_verticalScrollbarPosition:
4428                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4429                    break;
4430                case R.styleable.View_layerType:
4431                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4432                    break;
4433                case R.styleable.View_textDirection:
4434                    // Clear any text direction flag already set
4435                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4436                    // Set the text direction flags depending on the value of the attribute
4437                    final int textDirection = a.getInt(attr, -1);
4438                    if (textDirection != -1) {
4439                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4440                    }
4441                    break;
4442                case R.styleable.View_textAlignment:
4443                    // Clear any text alignment flag already set
4444                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4445                    // Set the text alignment flag depending on the value of the attribute
4446                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4447                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4448                    break;
4449                case R.styleable.View_importantForAccessibility:
4450                    setImportantForAccessibility(a.getInt(attr,
4451                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4452                    break;
4453                case R.styleable.View_accessibilityLiveRegion:
4454                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4455                    break;
4456                case R.styleable.View_transitionName:
4457                    setTransitionName(a.getString(attr));
4458                    break;
4459                case R.styleable.View_nestedScrollingEnabled:
4460                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4461                    break;
4462                case R.styleable.View_stateListAnimator:
4463                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4464                            a.getResourceId(attr, 0)));
4465                    break;
4466                case R.styleable.View_backgroundTint:
4467                    // This will get applied later during setBackground().
4468                    if (mBackgroundTint == null) {
4469                        mBackgroundTint = new TintInfo();
4470                    }
4471                    mBackgroundTint.mTintList = a.getColorStateList(
4472                            R.styleable.View_backgroundTint);
4473                    mBackgroundTint.mHasTintList = true;
4474                    break;
4475                case R.styleable.View_backgroundTintMode:
4476                    // This will get applied later during setBackground().
4477                    if (mBackgroundTint == null) {
4478                        mBackgroundTint = new TintInfo();
4479                    }
4480                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4481                            R.styleable.View_backgroundTintMode, -1), null);
4482                    mBackgroundTint.mHasTintMode = true;
4483                    break;
4484                case R.styleable.View_outlineProvider:
4485                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4486                            PROVIDER_BACKGROUND));
4487                    break;
4488                case R.styleable.View_foreground:
4489                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4490                        setForeground(a.getDrawable(attr));
4491                    }
4492                    break;
4493                case R.styleable.View_foregroundGravity:
4494                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4495                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4496                    }
4497                    break;
4498                case R.styleable.View_foregroundTintMode:
4499                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4500                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4501                    }
4502                    break;
4503                case R.styleable.View_foregroundTint:
4504                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4505                        setForegroundTintList(a.getColorStateList(attr));
4506                    }
4507                    break;
4508                case R.styleable.View_foregroundInsidePadding:
4509                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4510                        if (mForegroundInfo == null) {
4511                            mForegroundInfo = new ForegroundInfo();
4512                        }
4513                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4514                                mForegroundInfo.mInsidePadding);
4515                    }
4516                    break;
4517                case R.styleable.View_scrollIndicators:
4518                    final int scrollIndicators =
4519                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4520                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4521                    if (scrollIndicators != 0) {
4522                        mPrivateFlags3 |= scrollIndicators;
4523                        initializeScrollIndicators = true;
4524                    }
4525                    break;
4526                case R.styleable.View_pointerShape:
4527                    final int resourceId = a.getResourceId(attr, 0);
4528                    if (resourceId != 0) {
4529                        setPointerIcon(PointerIcon.loadCustomIcon(
4530                                context.getResources(), resourceId));
4531                    } else {
4532                        final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED);
4533                        if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) {
4534                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape));
4535                        }
4536                    }
4537                    break;
4538                case R.styleable.View_forceHasOverlappingRendering:
4539                    if (a.peekValue(attr) != null) {
4540                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4541                    }
4542                    break;
4543
4544            }
4545        }
4546
4547        setOverScrollMode(overScrollMode);
4548
4549        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4550        // the resolved layout direction). Those cached values will be used later during padding
4551        // resolution.
4552        mUserPaddingStart = startPadding;
4553        mUserPaddingEnd = endPadding;
4554
4555        if (background != null) {
4556            setBackground(background);
4557        }
4558
4559        // setBackground above will record that padding is currently provided by the background.
4560        // If we have padding specified via xml, record that here instead and use it.
4561        mLeftPaddingDefined = leftPaddingDefined;
4562        mRightPaddingDefined = rightPaddingDefined;
4563
4564        if (padding >= 0) {
4565            leftPadding = padding;
4566            topPadding = padding;
4567            rightPadding = padding;
4568            bottomPadding = padding;
4569            mUserPaddingLeftInitial = padding;
4570            mUserPaddingRightInitial = padding;
4571        }
4572
4573        if (isRtlCompatibilityMode()) {
4574            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4575            // left / right padding are used if defined (meaning here nothing to do). If they are not
4576            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4577            // start / end and resolve them as left / right (layout direction is not taken into account).
4578            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4579            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4580            // defined.
4581            if (!mLeftPaddingDefined && startPaddingDefined) {
4582                leftPadding = startPadding;
4583            }
4584            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4585            if (!mRightPaddingDefined && endPaddingDefined) {
4586                rightPadding = endPadding;
4587            }
4588            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4589        } else {
4590            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4591            // values defined. Otherwise, left /right values are used.
4592            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4593            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4594            // defined.
4595            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4596
4597            if (mLeftPaddingDefined && !hasRelativePadding) {
4598                mUserPaddingLeftInitial = leftPadding;
4599            }
4600            if (mRightPaddingDefined && !hasRelativePadding) {
4601                mUserPaddingRightInitial = rightPadding;
4602            }
4603        }
4604
4605        internalSetPadding(
4606                mUserPaddingLeftInitial,
4607                topPadding >= 0 ? topPadding : mPaddingTop,
4608                mUserPaddingRightInitial,
4609                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4610
4611        if (viewFlagMasks != 0) {
4612            setFlags(viewFlagValues, viewFlagMasks);
4613        }
4614
4615        if (initializeScrollbars) {
4616            initializeScrollbarsInternal(a);
4617        }
4618
4619        if (initializeScrollIndicators) {
4620            initializeScrollIndicatorsInternal();
4621        }
4622
4623        a.recycle();
4624
4625        // Needs to be called after mViewFlags is set
4626        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4627            recomputePadding();
4628        }
4629
4630        if (x != 0 || y != 0) {
4631            scrollTo(x, y);
4632        }
4633
4634        if (transformSet) {
4635            setTranslationX(tx);
4636            setTranslationY(ty);
4637            setTranslationZ(tz);
4638            setElevation(elevation);
4639            setRotation(rotation);
4640            setRotationX(rotationX);
4641            setRotationY(rotationY);
4642            setScaleX(sx);
4643            setScaleY(sy);
4644        }
4645
4646        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4647            setScrollContainer(true);
4648        }
4649
4650        computeOpaqueFlags();
4651    }
4652
4653    /**
4654     * An implementation of OnClickListener that attempts to lazily load a
4655     * named click handling method from a parent or ancestor context.
4656     */
4657    private static class DeclaredOnClickListener implements OnClickListener {
4658        private final View mHostView;
4659        private final String mMethodName;
4660
4661        private Method mResolvedMethod;
4662        private Context mResolvedContext;
4663
4664        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4665            mHostView = hostView;
4666            mMethodName = methodName;
4667        }
4668
4669        @Override
4670        public void onClick(@NonNull View v) {
4671            if (mResolvedMethod == null) {
4672                resolveMethod(mHostView.getContext(), mMethodName);
4673            }
4674
4675            try {
4676                mResolvedMethod.invoke(mResolvedContext, v);
4677            } catch (IllegalAccessException e) {
4678                throw new IllegalStateException(
4679                        "Could not execute non-public method for android:onClick", e);
4680            } catch (InvocationTargetException e) {
4681                throw new IllegalStateException(
4682                        "Could not execute method for android:onClick", e);
4683            }
4684        }
4685
4686        @NonNull
4687        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4688            while (context != null) {
4689                try {
4690                    if (!context.isRestricted()) {
4691                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4692                        if (method != null) {
4693                            mResolvedMethod = method;
4694                            mResolvedContext = context;
4695                            return;
4696                        }
4697                    }
4698                } catch (NoSuchMethodException e) {
4699                    // Failed to find method, keep searching up the hierarchy.
4700                }
4701
4702                if (context instanceof ContextWrapper) {
4703                    context = ((ContextWrapper) context).getBaseContext();
4704                } else {
4705                    // Can't search up the hierarchy, null out and fail.
4706                    context = null;
4707                }
4708            }
4709
4710            final int id = mHostView.getId();
4711            final String idText = id == NO_ID ? "" : " with id '"
4712                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4713            throw new IllegalStateException("Could not find method " + mMethodName
4714                    + "(View) in a parent or ancestor Context for android:onClick "
4715                    + "attribute defined on view " + mHostView.getClass() + idText);
4716        }
4717    }
4718
4719    /**
4720     * Non-public constructor for use in testing
4721     */
4722    View() {
4723        mResources = null;
4724        mRenderNode = RenderNode.create(getClass().getName(), this);
4725    }
4726
4727    private static SparseArray<String> getAttributeMap() {
4728        if (mAttributeMap == null) {
4729            mAttributeMap = new SparseArray<>();
4730        }
4731        return mAttributeMap;
4732    }
4733
4734    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4735        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4736        final int indexCount = t.getIndexCount();
4737        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4738
4739        int i = 0;
4740
4741        // Store raw XML attributes.
4742        for (int j = 0; j < attrsCount; ++j) {
4743            attributes[i] = attrs.getAttributeName(j);
4744            attributes[i + 1] = attrs.getAttributeValue(j);
4745            i += 2;
4746        }
4747
4748        // Store resolved styleable attributes.
4749        final Resources res = t.getResources();
4750        final SparseArray<String> attributeMap = getAttributeMap();
4751        for (int j = 0; j < indexCount; ++j) {
4752            final int index = t.getIndex(j);
4753            if (!t.hasValueOrEmpty(index)) {
4754                // Value is undefined. Skip it.
4755                continue;
4756            }
4757
4758            final int resourceId = t.getResourceId(index, 0);
4759            if (resourceId == 0) {
4760                // Value is not a reference. Skip it.
4761                continue;
4762            }
4763
4764            String resourceName = attributeMap.get(resourceId);
4765            if (resourceName == null) {
4766                try {
4767                    resourceName = res.getResourceName(resourceId);
4768                } catch (Resources.NotFoundException e) {
4769                    resourceName = "0x" + Integer.toHexString(resourceId);
4770                }
4771                attributeMap.put(resourceId, resourceName);
4772            }
4773
4774            attributes[i] = resourceName;
4775            attributes[i + 1] = t.getString(index);
4776            i += 2;
4777        }
4778
4779        // Trim to fit contents.
4780        final String[] trimmed = new String[i];
4781        System.arraycopy(attributes, 0, trimmed, 0, i);
4782        mAttributes = trimmed;
4783    }
4784
4785    public String toString() {
4786        StringBuilder out = new StringBuilder(128);
4787        out.append(getClass().getName());
4788        out.append('{');
4789        out.append(Integer.toHexString(System.identityHashCode(this)));
4790        out.append(' ');
4791        switch (mViewFlags&VISIBILITY_MASK) {
4792            case VISIBLE: out.append('V'); break;
4793            case INVISIBLE: out.append('I'); break;
4794            case GONE: out.append('G'); break;
4795            default: out.append('.'); break;
4796        }
4797        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4798        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4799        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4800        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4801        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4802        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4803        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4804        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4805        out.append(' ');
4806        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4807        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4808        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4809        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4810            out.append('p');
4811        } else {
4812            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4813        }
4814        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4815        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4816        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4817        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4818        out.append(' ');
4819        out.append(mLeft);
4820        out.append(',');
4821        out.append(mTop);
4822        out.append('-');
4823        out.append(mRight);
4824        out.append(',');
4825        out.append(mBottom);
4826        final int id = getId();
4827        if (id != NO_ID) {
4828            out.append(" #");
4829            out.append(Integer.toHexString(id));
4830            final Resources r = mResources;
4831            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4832                try {
4833                    String pkgname;
4834                    switch (id&0xff000000) {
4835                        case 0x7f000000:
4836                            pkgname="app";
4837                            break;
4838                        case 0x01000000:
4839                            pkgname="android";
4840                            break;
4841                        default:
4842                            pkgname = r.getResourcePackageName(id);
4843                            break;
4844                    }
4845                    String typename = r.getResourceTypeName(id);
4846                    String entryname = r.getResourceEntryName(id);
4847                    out.append(" ");
4848                    out.append(pkgname);
4849                    out.append(":");
4850                    out.append(typename);
4851                    out.append("/");
4852                    out.append(entryname);
4853                } catch (Resources.NotFoundException e) {
4854                }
4855            }
4856        }
4857        out.append("}");
4858        return out.toString();
4859    }
4860
4861    /**
4862     * <p>
4863     * Initializes the fading edges from a given set of styled attributes. This
4864     * method should be called by subclasses that need fading edges and when an
4865     * instance of these subclasses is created programmatically rather than
4866     * being inflated from XML. This method is automatically called when the XML
4867     * is inflated.
4868     * </p>
4869     *
4870     * @param a the styled attributes set to initialize the fading edges from
4871     *
4872     * @removed
4873     */
4874    protected void initializeFadingEdge(TypedArray a) {
4875        // This method probably shouldn't have been included in the SDK to begin with.
4876        // It relies on 'a' having been initialized using an attribute filter array that is
4877        // not publicly available to the SDK. The old method has been renamed
4878        // to initializeFadingEdgeInternal and hidden for framework use only;
4879        // this one initializes using defaults to make it safe to call for apps.
4880
4881        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4882
4883        initializeFadingEdgeInternal(arr);
4884
4885        arr.recycle();
4886    }
4887
4888    /**
4889     * <p>
4890     * Initializes the fading edges from a given set of styled attributes. This
4891     * method should be called by subclasses that need fading edges and when an
4892     * instance of these subclasses is created programmatically rather than
4893     * being inflated from XML. This method is automatically called when the XML
4894     * is inflated.
4895     * </p>
4896     *
4897     * @param a the styled attributes set to initialize the fading edges from
4898     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4899     */
4900    protected void initializeFadingEdgeInternal(TypedArray a) {
4901        initScrollCache();
4902
4903        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4904                R.styleable.View_fadingEdgeLength,
4905                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4906    }
4907
4908    /**
4909     * Returns the size of the vertical faded edges used to indicate that more
4910     * content in this view is visible.
4911     *
4912     * @return The size in pixels of the vertical faded edge or 0 if vertical
4913     *         faded edges are not enabled for this view.
4914     * @attr ref android.R.styleable#View_fadingEdgeLength
4915     */
4916    public int getVerticalFadingEdgeLength() {
4917        if (isVerticalFadingEdgeEnabled()) {
4918            ScrollabilityCache cache = mScrollCache;
4919            if (cache != null) {
4920                return cache.fadingEdgeLength;
4921            }
4922        }
4923        return 0;
4924    }
4925
4926    /**
4927     * Set the size of the faded edge used to indicate that more content in this
4928     * view is available.  Will not change whether the fading edge is enabled; use
4929     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4930     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4931     * for the vertical or horizontal fading edges.
4932     *
4933     * @param length The size in pixels of the faded edge used to indicate that more
4934     *        content in this view is visible.
4935     */
4936    public void setFadingEdgeLength(int length) {
4937        initScrollCache();
4938        mScrollCache.fadingEdgeLength = length;
4939    }
4940
4941    /**
4942     * Returns the size of the horizontal faded edges used to indicate that more
4943     * content in this view is visible.
4944     *
4945     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4946     *         faded edges are not enabled for this view.
4947     * @attr ref android.R.styleable#View_fadingEdgeLength
4948     */
4949    public int getHorizontalFadingEdgeLength() {
4950        if (isHorizontalFadingEdgeEnabled()) {
4951            ScrollabilityCache cache = mScrollCache;
4952            if (cache != null) {
4953                return cache.fadingEdgeLength;
4954            }
4955        }
4956        return 0;
4957    }
4958
4959    /**
4960     * Returns the width of the vertical scrollbar.
4961     *
4962     * @return The width in pixels of the vertical scrollbar or 0 if there
4963     *         is no vertical scrollbar.
4964     */
4965    public int getVerticalScrollbarWidth() {
4966        ScrollabilityCache cache = mScrollCache;
4967        if (cache != null) {
4968            ScrollBarDrawable scrollBar = cache.scrollBar;
4969            if (scrollBar != null) {
4970                int size = scrollBar.getSize(true);
4971                if (size <= 0) {
4972                    size = cache.scrollBarSize;
4973                }
4974                return size;
4975            }
4976            return 0;
4977        }
4978        return 0;
4979    }
4980
4981    /**
4982     * Returns the height of the horizontal scrollbar.
4983     *
4984     * @return The height in pixels of the horizontal scrollbar or 0 if
4985     *         there is no horizontal scrollbar.
4986     */
4987    protected int getHorizontalScrollbarHeight() {
4988        ScrollabilityCache cache = mScrollCache;
4989        if (cache != null) {
4990            ScrollBarDrawable scrollBar = cache.scrollBar;
4991            if (scrollBar != null) {
4992                int size = scrollBar.getSize(false);
4993                if (size <= 0) {
4994                    size = cache.scrollBarSize;
4995                }
4996                return size;
4997            }
4998            return 0;
4999        }
5000        return 0;
5001    }
5002
5003    /**
5004     * <p>
5005     * Initializes the scrollbars from a given set of styled attributes. This
5006     * method should be called by subclasses that need scrollbars and when an
5007     * instance of these subclasses is created programmatically rather than
5008     * being inflated from XML. This method is automatically called when the XML
5009     * is inflated.
5010     * </p>
5011     *
5012     * @param a the styled attributes set to initialize the scrollbars from
5013     *
5014     * @removed
5015     */
5016    protected void initializeScrollbars(TypedArray a) {
5017        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5018        // using the View filter array which is not available to the SDK. As such, internal
5019        // framework usage now uses initializeScrollbarsInternal and we grab a default
5020        // TypedArray with the right filter instead here.
5021        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5022
5023        initializeScrollbarsInternal(arr);
5024
5025        // We ignored the method parameter. Recycle the one we actually did use.
5026        arr.recycle();
5027    }
5028
5029    /**
5030     * <p>
5031     * Initializes the scrollbars from a given set of styled attributes. This
5032     * method should be called by subclasses that need scrollbars and when an
5033     * instance of these subclasses is created programmatically rather than
5034     * being inflated from XML. This method is automatically called when the XML
5035     * is inflated.
5036     * </p>
5037     *
5038     * @param a the styled attributes set to initialize the scrollbars from
5039     * @hide
5040     */
5041    protected void initializeScrollbarsInternal(TypedArray a) {
5042        initScrollCache();
5043
5044        final ScrollabilityCache scrollabilityCache = mScrollCache;
5045
5046        if (scrollabilityCache.scrollBar == null) {
5047            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5048            scrollabilityCache.scrollBar.setState(getDrawableState());
5049            scrollabilityCache.scrollBar.setCallback(this);
5050        }
5051
5052        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5053
5054        if (!fadeScrollbars) {
5055            scrollabilityCache.state = ScrollabilityCache.ON;
5056        }
5057        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5058
5059
5060        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5061                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5062                        .getScrollBarFadeDuration());
5063        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5064                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5065                ViewConfiguration.getScrollDefaultDelay());
5066
5067
5068        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5069                com.android.internal.R.styleable.View_scrollbarSize,
5070                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5071
5072        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5073        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5074
5075        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5076        if (thumb != null) {
5077            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5078        }
5079
5080        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5081                false);
5082        if (alwaysDraw) {
5083            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5084        }
5085
5086        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5087        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5088
5089        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5090        if (thumb != null) {
5091            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5092        }
5093
5094        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5095                false);
5096        if (alwaysDraw) {
5097            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5098        }
5099
5100        // Apply layout direction to the new Drawables if needed
5101        final int layoutDirection = getLayoutDirection();
5102        if (track != null) {
5103            track.setLayoutDirection(layoutDirection);
5104        }
5105        if (thumb != null) {
5106            thumb.setLayoutDirection(layoutDirection);
5107        }
5108
5109        // Re-apply user/background padding so that scrollbar(s) get added
5110        resolvePadding();
5111    }
5112
5113    private void initializeScrollIndicatorsInternal() {
5114        // Some day maybe we'll break this into top/left/start/etc. and let the
5115        // client control it. Until then, you can have any scroll indicator you
5116        // want as long as it's a 1dp foreground-colored rectangle.
5117        if (mScrollIndicatorDrawable == null) {
5118            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5119        }
5120    }
5121
5122    /**
5123     * <p>
5124     * Initalizes the scrollability cache if necessary.
5125     * </p>
5126     */
5127    private void initScrollCache() {
5128        if (mScrollCache == null) {
5129            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5130        }
5131    }
5132
5133    private ScrollabilityCache getScrollCache() {
5134        initScrollCache();
5135        return mScrollCache;
5136    }
5137
5138    /**
5139     * Set the position of the vertical scroll bar. Should be one of
5140     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5141     * {@link #SCROLLBAR_POSITION_RIGHT}.
5142     *
5143     * @param position Where the vertical scroll bar should be positioned.
5144     */
5145    public void setVerticalScrollbarPosition(int position) {
5146        if (mVerticalScrollbarPosition != position) {
5147            mVerticalScrollbarPosition = position;
5148            computeOpaqueFlags();
5149            resolvePadding();
5150        }
5151    }
5152
5153    /**
5154     * @return The position where the vertical scroll bar will show, if applicable.
5155     * @see #setVerticalScrollbarPosition(int)
5156     */
5157    public int getVerticalScrollbarPosition() {
5158        return mVerticalScrollbarPosition;
5159    }
5160
5161    boolean isOnScrollbar(float x, float y) {
5162        if (mScrollCache == null) {
5163            return false;
5164        }
5165        x += getScrollX();
5166        y += getScrollY();
5167        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5168            final Rect bounds = mScrollCache.mScrollBarBounds;
5169            getVerticalScrollBarBounds(bounds);
5170            if (bounds.contains((int)x, (int)y)) {
5171                return true;
5172            }
5173        }
5174        if (isHorizontalScrollBarEnabled()) {
5175            final Rect bounds = mScrollCache.mScrollBarBounds;
5176            getHorizontalScrollBarBounds(bounds);
5177            if (bounds.contains((int)x, (int)y)) {
5178                return true;
5179            }
5180        }
5181        return false;
5182    }
5183
5184    boolean isOnScrollbarThumb(float x, float y) {
5185        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5186    }
5187
5188    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5189        if (mScrollCache == null) {
5190            return false;
5191        }
5192        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5193            x += getScrollX();
5194            y += getScrollY();
5195            final Rect bounds = mScrollCache.mScrollBarBounds;
5196            getVerticalScrollBarBounds(bounds);
5197            final int range = computeVerticalScrollRange();
5198            final int offset = computeVerticalScrollOffset();
5199            final int extent = computeVerticalScrollExtent();
5200            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5201                    extent, range);
5202            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5203                    extent, range, offset);
5204            final int thumbTop = bounds.top + thumbOffset;
5205            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5206                    && y <= thumbTop + thumbLength) {
5207                return true;
5208            }
5209        }
5210        return false;
5211    }
5212
5213    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5214        if (mScrollCache == null) {
5215            return false;
5216        }
5217        if (isHorizontalScrollBarEnabled()) {
5218            x += getScrollX();
5219            y += getScrollY();
5220            final Rect bounds = mScrollCache.mScrollBarBounds;
5221            getHorizontalScrollBarBounds(bounds);
5222            final int range = computeHorizontalScrollRange();
5223            final int offset = computeHorizontalScrollOffset();
5224            final int extent = computeHorizontalScrollExtent();
5225            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5226                    extent, range);
5227            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5228                    extent, range, offset);
5229            final int thumbLeft = bounds.left + thumbOffset;
5230            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5231                    && y <= bounds.bottom) {
5232                return true;
5233            }
5234        }
5235        return false;
5236    }
5237
5238    boolean isDraggingScrollBar() {
5239        return mScrollCache != null
5240                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5241    }
5242
5243    /**
5244     * Sets the state of all scroll indicators.
5245     * <p>
5246     * See {@link #setScrollIndicators(int, int)} for usage information.
5247     *
5248     * @param indicators a bitmask of indicators that should be enabled, or
5249     *                   {@code 0} to disable all indicators
5250     * @see #setScrollIndicators(int, int)
5251     * @see #getScrollIndicators()
5252     * @attr ref android.R.styleable#View_scrollIndicators
5253     */
5254    public void setScrollIndicators(@ScrollIndicators int indicators) {
5255        setScrollIndicators(indicators,
5256                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5257    }
5258
5259    /**
5260     * Sets the state of the scroll indicators specified by the mask. To change
5261     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5262     * <p>
5263     * When a scroll indicator is enabled, it will be displayed if the view
5264     * can scroll in the direction of the indicator.
5265     * <p>
5266     * Multiple indicator types may be enabled or disabled by passing the
5267     * logical OR of the desired types. If multiple types are specified, they
5268     * will all be set to the same enabled state.
5269     * <p>
5270     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5271     *
5272     * @param indicators the indicator direction, or the logical OR of multiple
5273     *             indicator directions. One or more of:
5274     *             <ul>
5275     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5276     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5277     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5278     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5279     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5280     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5281     *             </ul>
5282     * @see #setScrollIndicators(int)
5283     * @see #getScrollIndicators()
5284     * @attr ref android.R.styleable#View_scrollIndicators
5285     */
5286    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5287        // Shift and sanitize mask.
5288        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5289        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5290
5291        // Shift and mask indicators.
5292        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5293        indicators &= mask;
5294
5295        // Merge with non-masked flags.
5296        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5297
5298        if (mPrivateFlags3 != updatedFlags) {
5299            mPrivateFlags3 = updatedFlags;
5300
5301            if (indicators != 0) {
5302                initializeScrollIndicatorsInternal();
5303            }
5304            invalidate();
5305        }
5306    }
5307
5308    /**
5309     * Returns a bitmask representing the enabled scroll indicators.
5310     * <p>
5311     * For example, if the top and left scroll indicators are enabled and all
5312     * other indicators are disabled, the return value will be
5313     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5314     * <p>
5315     * To check whether the bottom scroll indicator is enabled, use the value
5316     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5317     *
5318     * @return a bitmask representing the enabled scroll indicators
5319     */
5320    @ScrollIndicators
5321    public int getScrollIndicators() {
5322        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5323                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5324    }
5325
5326    ListenerInfo getListenerInfo() {
5327        if (mListenerInfo != null) {
5328            return mListenerInfo;
5329        }
5330        mListenerInfo = new ListenerInfo();
5331        return mListenerInfo;
5332    }
5333
5334    /**
5335     * Register a callback to be invoked when the scroll X or Y positions of
5336     * this view change.
5337     * <p>
5338     * <b>Note:</b> Some views handle scrolling independently from View and may
5339     * have their own separate listeners for scroll-type events. For example,
5340     * {@link android.widget.ListView ListView} allows clients to register an
5341     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5342     * to listen for changes in list scroll position.
5343     *
5344     * @param l The listener to notify when the scroll X or Y position changes.
5345     * @see android.view.View#getScrollX()
5346     * @see android.view.View#getScrollY()
5347     */
5348    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5349        getListenerInfo().mOnScrollChangeListener = l;
5350    }
5351
5352    /**
5353     * Register a callback to be invoked when focus of this view changed.
5354     *
5355     * @param l The callback that will run.
5356     */
5357    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5358        getListenerInfo().mOnFocusChangeListener = l;
5359    }
5360
5361    /**
5362     * Add a listener that will be called when the bounds of the view change due to
5363     * layout processing.
5364     *
5365     * @param listener The listener that will be called when layout bounds change.
5366     */
5367    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5368        ListenerInfo li = getListenerInfo();
5369        if (li.mOnLayoutChangeListeners == null) {
5370            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5371        }
5372        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5373            li.mOnLayoutChangeListeners.add(listener);
5374        }
5375    }
5376
5377    /**
5378     * Remove a listener for layout changes.
5379     *
5380     * @param listener The listener for layout bounds change.
5381     */
5382    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5383        ListenerInfo li = mListenerInfo;
5384        if (li == null || li.mOnLayoutChangeListeners == null) {
5385            return;
5386        }
5387        li.mOnLayoutChangeListeners.remove(listener);
5388    }
5389
5390    /**
5391     * Add a listener for attach state changes.
5392     *
5393     * This listener will be called whenever this view is attached or detached
5394     * from a window. Remove the listener using
5395     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5396     *
5397     * @param listener Listener to attach
5398     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5399     */
5400    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5401        ListenerInfo li = getListenerInfo();
5402        if (li.mOnAttachStateChangeListeners == null) {
5403            li.mOnAttachStateChangeListeners
5404                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5405        }
5406        li.mOnAttachStateChangeListeners.add(listener);
5407    }
5408
5409    /**
5410     * Remove a listener for attach state changes. The listener will receive no further
5411     * notification of window attach/detach events.
5412     *
5413     * @param listener Listener to remove
5414     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5415     */
5416    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5417        ListenerInfo li = mListenerInfo;
5418        if (li == null || li.mOnAttachStateChangeListeners == null) {
5419            return;
5420        }
5421        li.mOnAttachStateChangeListeners.remove(listener);
5422    }
5423
5424    /**
5425     * Returns the focus-change callback registered for this view.
5426     *
5427     * @return The callback, or null if one is not registered.
5428     */
5429    public OnFocusChangeListener getOnFocusChangeListener() {
5430        ListenerInfo li = mListenerInfo;
5431        return li != null ? li.mOnFocusChangeListener : null;
5432    }
5433
5434    /**
5435     * Register a callback to be invoked when this view is clicked. If this view is not
5436     * clickable, it becomes clickable.
5437     *
5438     * @param l The callback that will run
5439     *
5440     * @see #setClickable(boolean)
5441     */
5442    public void setOnClickListener(@Nullable OnClickListener l) {
5443        if (!isClickable()) {
5444            setClickable(true);
5445        }
5446        getListenerInfo().mOnClickListener = l;
5447    }
5448
5449    /**
5450     * Return whether this view has an attached OnClickListener.  Returns
5451     * true if there is a listener, false if there is none.
5452     */
5453    public boolean hasOnClickListeners() {
5454        ListenerInfo li = mListenerInfo;
5455        return (li != null && li.mOnClickListener != null);
5456    }
5457
5458    /**
5459     * Register a callback to be invoked when this view is clicked and held. If this view is not
5460     * long clickable, it becomes long clickable.
5461     *
5462     * @param l The callback that will run
5463     *
5464     * @see #setLongClickable(boolean)
5465     */
5466    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5467        if (!isLongClickable()) {
5468            setLongClickable(true);
5469        }
5470        getListenerInfo().mOnLongClickListener = l;
5471    }
5472
5473    /**
5474     * Register a callback to be invoked when this view is context clicked. If the view is not
5475     * context clickable, it becomes context clickable.
5476     *
5477     * @param l The callback that will run
5478     * @see #setContextClickable(boolean)
5479     */
5480    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5481        if (!isContextClickable()) {
5482            setContextClickable(true);
5483        }
5484        getListenerInfo().mOnContextClickListener = l;
5485    }
5486
5487    /**
5488     * Register a callback to be invoked when the context menu for this view is
5489     * being built. If this view is not long clickable, it becomes long clickable.
5490     *
5491     * @param l The callback that will run
5492     *
5493     */
5494    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5495        if (!isLongClickable()) {
5496            setLongClickable(true);
5497        }
5498        getListenerInfo().mOnCreateContextMenuListener = l;
5499    }
5500
5501    /**
5502     * Set an observer to collect stats for each frame rendered for this view.
5503     *
5504     * @hide
5505     */
5506    public void addFrameMetricsListener(Window window, Window.FrameMetricsListener listener,
5507            Handler handler) {
5508        if (mAttachInfo != null) {
5509            if (mAttachInfo.mHardwareRenderer != null) {
5510                if (mFrameMetricsObservers == null) {
5511                    mFrameMetricsObservers = new ArrayList<>();
5512                }
5513
5514                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5515                        handler.getLooper(), listener);
5516                mFrameMetricsObservers.add(fmo);
5517                mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo);
5518            } else {
5519                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5520            }
5521        } else {
5522            if (mFrameMetricsObservers == null) {
5523                mFrameMetricsObservers = new ArrayList<>();
5524            }
5525
5526            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5527                    handler.getLooper(), listener);
5528            mFrameMetricsObservers.add(fmo);
5529        }
5530    }
5531
5532    /**
5533     * Remove observer configured to collect frame stats for this view.
5534     *
5535     * @hide
5536     */
5537    public void removeFrameMetricsListener(Window.FrameMetricsListener listener) {
5538        ThreadedRenderer renderer = getHardwareRenderer();
5539        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5540        if (fmo == null) {
5541            throw new IllegalArgumentException("attempt to remove FrameMetricsListener that was never added");
5542        }
5543
5544        if (mFrameMetricsObservers != null) {
5545            mFrameMetricsObservers.remove(fmo);
5546            if (renderer != null) {
5547                renderer.removeFrameMetricsObserver(fmo);
5548            }
5549        }
5550    }
5551
5552    private void registerPendingFrameMetricsObservers() {
5553        if (mFrameMetricsObservers != null) {
5554            ThreadedRenderer renderer = getHardwareRenderer();
5555            if (renderer != null) {
5556                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5557                    renderer.addFrameMetricsObserver(fmo);
5558                }
5559            } else {
5560                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5561            }
5562        }
5563    }
5564
5565    private FrameMetricsObserver findFrameMetricsObserver(Window.FrameMetricsListener listener) {
5566        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5567            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5568            if (observer.mListener == listener) {
5569                return observer;
5570            }
5571        }
5572
5573        return null;
5574    }
5575
5576    /**
5577     * Call this view's OnClickListener, if it is defined.  Performs all normal
5578     * actions associated with clicking: reporting accessibility event, playing
5579     * a sound, etc.
5580     *
5581     * @return True there was an assigned OnClickListener that was called, false
5582     *         otherwise is returned.
5583     */
5584    public boolean performClick() {
5585        final boolean result;
5586        final ListenerInfo li = mListenerInfo;
5587        if (li != null && li.mOnClickListener != null) {
5588            playSoundEffect(SoundEffectConstants.CLICK);
5589            li.mOnClickListener.onClick(this);
5590            result = true;
5591        } else {
5592            result = false;
5593        }
5594
5595        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5596        return result;
5597    }
5598
5599    /**
5600     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5601     * this only calls the listener, and does not do any associated clicking
5602     * actions like reporting an accessibility event.
5603     *
5604     * @return True there was an assigned OnClickListener that was called, false
5605     *         otherwise is returned.
5606     */
5607    public boolean callOnClick() {
5608        ListenerInfo li = mListenerInfo;
5609        if (li != null && li.mOnClickListener != null) {
5610            li.mOnClickListener.onClick(this);
5611            return true;
5612        }
5613        return false;
5614    }
5615
5616    /**
5617     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5618     * context menu if the OnLongClickListener did not consume the event.
5619     *
5620     * @return {@code true} if one of the above receivers consumed the event,
5621     *         {@code false} otherwise
5622     */
5623    public boolean performLongClick() {
5624        return performLongClickInternal(mLongClickX, mLongClickY);
5625    }
5626
5627    /**
5628     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5629     * context menu if the OnLongClickListener did not consume the event,
5630     * anchoring it to an (x,y) coordinate.
5631     *
5632     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5633     *          to disable anchoring
5634     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5635     *          to disable anchoring
5636     * @return {@code true} if one of the above receivers consumed the event,
5637     *         {@code false} otherwise
5638     */
5639    public boolean performLongClick(float x, float y) {
5640        mLongClickX = x;
5641        mLongClickY = y;
5642        final boolean handled = performLongClick();
5643        mLongClickX = Float.NaN;
5644        mLongClickY = Float.NaN;
5645        return handled;
5646    }
5647
5648    /**
5649     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5650     * context menu if the OnLongClickListener did not consume the event,
5651     * optionally anchoring it to an (x,y) coordinate.
5652     *
5653     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5654     *          to disable anchoring
5655     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5656     *          to disable anchoring
5657     * @return {@code true} if one of the above receivers consumed the event,
5658     *         {@code false} otherwise
5659     */
5660    private boolean performLongClickInternal(float x, float y) {
5661        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5662
5663        boolean handled = false;
5664        final ListenerInfo li = mListenerInfo;
5665        if (li != null && li.mOnLongClickListener != null) {
5666            handled = li.mOnLongClickListener.onLongClick(View.this);
5667        }
5668        if (!handled) {
5669            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5670            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5671        }
5672        if (handled) {
5673            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5674        }
5675        return handled;
5676    }
5677
5678    /**
5679     * Call this view's OnContextClickListener, if it is defined.
5680     *
5681     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5682     *         otherwise.
5683     */
5684    public boolean performContextClick() {
5685        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5686
5687        boolean handled = false;
5688        ListenerInfo li = mListenerInfo;
5689        if (li != null && li.mOnContextClickListener != null) {
5690            handled = li.mOnContextClickListener.onContextClick(View.this);
5691        }
5692        if (handled) {
5693            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5694        }
5695        return handled;
5696    }
5697
5698    /**
5699     * Performs button-related actions during a touch down event.
5700     *
5701     * @param event The event.
5702     * @return True if the down was consumed.
5703     *
5704     * @hide
5705     */
5706    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5707        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5708            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5709            showContextMenu(event.getX(), event.getY());
5710            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5711            return true;
5712        }
5713        return false;
5714    }
5715
5716    /**
5717     * Shows the context menu for this view.
5718     *
5719     * @return {@code true} if the context menu was shown, {@code false}
5720     *         otherwise
5721     * @see #showContextMenu(float, float)
5722     */
5723    public boolean showContextMenu() {
5724        return getParent().showContextMenuForChild(this);
5725    }
5726
5727    /**
5728     * Shows the context menu for this view anchored to the specified
5729     * view-relative coordinate.
5730     *
5731     * @param x the X coordinate in pixels relative to the view to which the
5732     *          menu should be anchored
5733     * @param y the Y coordinate in pixels relative to the view to which the
5734     *          menu should be anchored
5735     * @return {@code true} if the context menu was shown, {@code false}
5736     *         otherwise
5737     */
5738    public boolean showContextMenu(float x, float y) {
5739        return getParent().showContextMenuForChild(this, x, y);
5740    }
5741
5742    /**
5743     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5744     *
5745     * @param callback Callback that will control the lifecycle of the action mode
5746     * @return The new action mode if it is started, null otherwise
5747     *
5748     * @see ActionMode
5749     * @see #startActionMode(android.view.ActionMode.Callback, int)
5750     */
5751    public ActionMode startActionMode(ActionMode.Callback callback) {
5752        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5753    }
5754
5755    /**
5756     * Start an action mode with the given type.
5757     *
5758     * @param callback Callback that will control the lifecycle of the action mode
5759     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5760     * @return The new action mode if it is started, null otherwise
5761     *
5762     * @see ActionMode
5763     */
5764    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5765        ViewParent parent = getParent();
5766        if (parent == null) return null;
5767        try {
5768            return parent.startActionModeForChild(this, callback, type);
5769        } catch (AbstractMethodError ame) {
5770            // Older implementations of custom views might not implement this.
5771            return parent.startActionModeForChild(this, callback);
5772        }
5773    }
5774
5775    /**
5776     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5777     * Context, creating a unique View identifier to retrieve the result.
5778     *
5779     * @param intent The Intent to be started.
5780     * @param requestCode The request code to use.
5781     * @hide
5782     */
5783    public void startActivityForResult(Intent intent, int requestCode) {
5784        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5785        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5786    }
5787
5788    /**
5789     * If this View corresponds to the calling who, dispatches the activity result.
5790     * @param who The identifier for the targeted View to receive the result.
5791     * @param requestCode The integer request code originally supplied to
5792     *                    startActivityForResult(), allowing you to identify who this
5793     *                    result came from.
5794     * @param resultCode The integer result code returned by the child activity
5795     *                   through its setResult().
5796     * @param data An Intent, which can return result data to the caller
5797     *               (various data can be attached to Intent "extras").
5798     * @return {@code true} if the activity result was dispatched.
5799     * @hide
5800     */
5801    public boolean dispatchActivityResult(
5802            String who, int requestCode, int resultCode, Intent data) {
5803        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5804            onActivityResult(requestCode, resultCode, data);
5805            mStartActivityRequestWho = null;
5806            return true;
5807        }
5808        return false;
5809    }
5810
5811    /**
5812     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5813     *
5814     * @param requestCode The integer request code originally supplied to
5815     *                    startActivityForResult(), allowing you to identify who this
5816     *                    result came from.
5817     * @param resultCode The integer result code returned by the child activity
5818     *                   through its setResult().
5819     * @param data An Intent, which can return result data to the caller
5820     *               (various data can be attached to Intent "extras").
5821     * @hide
5822     */
5823    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5824        // Do nothing.
5825    }
5826
5827    /**
5828     * Register a callback to be invoked when a hardware key is pressed in this view.
5829     * Key presses in software input methods will generally not trigger the methods of
5830     * this listener.
5831     * @param l the key listener to attach to this view
5832     */
5833    public void setOnKeyListener(OnKeyListener l) {
5834        getListenerInfo().mOnKeyListener = l;
5835    }
5836
5837    /**
5838     * Register a callback to be invoked when a touch event is sent to this view.
5839     * @param l the touch listener to attach to this view
5840     */
5841    public void setOnTouchListener(OnTouchListener l) {
5842        getListenerInfo().mOnTouchListener = l;
5843    }
5844
5845    /**
5846     * Register a callback to be invoked when a generic motion event is sent to this view.
5847     * @param l the generic motion listener to attach to this view
5848     */
5849    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5850        getListenerInfo().mOnGenericMotionListener = l;
5851    }
5852
5853    /**
5854     * Register a callback to be invoked when a hover event is sent to this view.
5855     * @param l the hover listener to attach to this view
5856     */
5857    public void setOnHoverListener(OnHoverListener l) {
5858        getListenerInfo().mOnHoverListener = l;
5859    }
5860
5861    /**
5862     * Register a drag event listener callback object for this View. The parameter is
5863     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5864     * View, the system calls the
5865     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5866     * @param l An implementation of {@link android.view.View.OnDragListener}.
5867     */
5868    public void setOnDragListener(OnDragListener l) {
5869        getListenerInfo().mOnDragListener = l;
5870    }
5871
5872    /**
5873     * Give this view focus. This will cause
5874     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5875     *
5876     * Note: this does not check whether this {@link View} should get focus, it just
5877     * gives it focus no matter what.  It should only be called internally by framework
5878     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5879     *
5880     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5881     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5882     *        focus moved when requestFocus() is called. It may not always
5883     *        apply, in which case use the default View.FOCUS_DOWN.
5884     * @param previouslyFocusedRect The rectangle of the view that had focus
5885     *        prior in this View's coordinate system.
5886     */
5887    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5888        if (DBG) {
5889            System.out.println(this + " requestFocus()");
5890        }
5891
5892        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5893            mPrivateFlags |= PFLAG_FOCUSED;
5894
5895            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5896
5897            if (mParent != null) {
5898                mParent.requestChildFocus(this, this);
5899            }
5900
5901            if (mAttachInfo != null) {
5902                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5903            }
5904
5905            onFocusChanged(true, direction, previouslyFocusedRect);
5906            refreshDrawableState();
5907        }
5908    }
5909
5910    /**
5911     * Populates <code>outRect</code> with the hotspot bounds. By default,
5912     * the hotspot bounds are identical to the screen bounds.
5913     *
5914     * @param outRect rect to populate with hotspot bounds
5915     * @hide Only for internal use by views and widgets.
5916     */
5917    public void getHotspotBounds(Rect outRect) {
5918        final Drawable background = getBackground();
5919        if (background != null) {
5920            background.getHotspotBounds(outRect);
5921        } else {
5922            getBoundsOnScreen(outRect);
5923        }
5924    }
5925
5926    /**
5927     * Request that a rectangle of this view be visible on the screen,
5928     * scrolling if necessary just enough.
5929     *
5930     * <p>A View should call this if it maintains some notion of which part
5931     * of its content is interesting.  For example, a text editing view
5932     * should call this when its cursor moves.
5933     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5934     * It should not be affected by which part of the View is currently visible or its scroll
5935     * position.
5936     *
5937     * @param rectangle The rectangle in the View's content coordinate space
5938     * @return Whether any parent scrolled.
5939     */
5940    public boolean requestRectangleOnScreen(Rect rectangle) {
5941        return requestRectangleOnScreen(rectangle, false);
5942    }
5943
5944    /**
5945     * Request that a rectangle of this view be visible on the screen,
5946     * scrolling if necessary just enough.
5947     *
5948     * <p>A View should call this if it maintains some notion of which part
5949     * of its content is interesting.  For example, a text editing view
5950     * should call this when its cursor moves.
5951     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5952     * It should not be affected by which part of the View is currently visible or its scroll
5953     * position.
5954     * <p>When <code>immediate</code> is set to true, scrolling will not be
5955     * animated.
5956     *
5957     * @param rectangle The rectangle in the View's content coordinate space
5958     * @param immediate True to forbid animated scrolling, false otherwise
5959     * @return Whether any parent scrolled.
5960     */
5961    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5962        if (mParent == null) {
5963            return false;
5964        }
5965
5966        View child = this;
5967
5968        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5969        position.set(rectangle);
5970
5971        ViewParent parent = mParent;
5972        boolean scrolled = false;
5973        while (parent != null) {
5974            rectangle.set((int) position.left, (int) position.top,
5975                    (int) position.right, (int) position.bottom);
5976
5977            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
5978
5979            if (!(parent instanceof View)) {
5980                break;
5981            }
5982
5983            // move it from child's content coordinate space to parent's content coordinate space
5984            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
5985
5986            child = (View) parent;
5987            parent = child.getParent();
5988        }
5989
5990        return scrolled;
5991    }
5992
5993    /**
5994     * Called when this view wants to give up focus. If focus is cleared
5995     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5996     * <p>
5997     * <strong>Note:</strong> When a View clears focus the framework is trying
5998     * to give focus to the first focusable View from the top. Hence, if this
5999     * View is the first from the top that can take focus, then all callbacks
6000     * related to clearing focus will be invoked after which the framework will
6001     * give focus to this view.
6002     * </p>
6003     */
6004    public void clearFocus() {
6005        if (DBG) {
6006            System.out.println(this + " clearFocus()");
6007        }
6008
6009        clearFocusInternal(null, true, true);
6010    }
6011
6012    /**
6013     * Clears focus from the view, optionally propagating the change up through
6014     * the parent hierarchy and requesting that the root view place new focus.
6015     *
6016     * @param propagate whether to propagate the change up through the parent
6017     *            hierarchy
6018     * @param refocus when propagate is true, specifies whether to request the
6019     *            root view place new focus
6020     */
6021    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6022        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6023            mPrivateFlags &= ~PFLAG_FOCUSED;
6024
6025            if (propagate && mParent != null) {
6026                mParent.clearChildFocus(this);
6027            }
6028
6029            onFocusChanged(false, 0, null);
6030            refreshDrawableState();
6031
6032            if (propagate && (!refocus || !rootViewRequestFocus())) {
6033                notifyGlobalFocusCleared(this);
6034            }
6035        }
6036    }
6037
6038    void notifyGlobalFocusCleared(View oldFocus) {
6039        if (oldFocus != null && mAttachInfo != null) {
6040            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6041        }
6042    }
6043
6044    boolean rootViewRequestFocus() {
6045        final View root = getRootView();
6046        return root != null && root.requestFocus();
6047    }
6048
6049    /**
6050     * Called internally by the view system when a new view is getting focus.
6051     * This is what clears the old focus.
6052     * <p>
6053     * <b>NOTE:</b> The parent view's focused child must be updated manually
6054     * after calling this method. Otherwise, the view hierarchy may be left in
6055     * an inconstent state.
6056     */
6057    void unFocus(View focused) {
6058        if (DBG) {
6059            System.out.println(this + " unFocus()");
6060        }
6061
6062        clearFocusInternal(focused, false, false);
6063    }
6064
6065    /**
6066     * Returns true if this view has focus itself, or is the ancestor of the
6067     * view that has focus.
6068     *
6069     * @return True if this view has or contains focus, false otherwise.
6070     */
6071    @ViewDebug.ExportedProperty(category = "focus")
6072    public boolean hasFocus() {
6073        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6074    }
6075
6076    /**
6077     * Returns true if this view is focusable or if it contains a reachable View
6078     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6079     * is a View whose parents do not block descendants focus.
6080     *
6081     * Only {@link #VISIBLE} views are considered focusable.
6082     *
6083     * @return True if the view is focusable or if the view contains a focusable
6084     *         View, false otherwise.
6085     *
6086     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6087     * @see ViewGroup#getTouchscreenBlocksFocus()
6088     */
6089    public boolean hasFocusable() {
6090        if (!isFocusableInTouchMode()) {
6091            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6092                final ViewGroup g = (ViewGroup) p;
6093                if (g.shouldBlockFocusForTouchscreen()) {
6094                    return false;
6095                }
6096            }
6097        }
6098        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6099    }
6100
6101    /**
6102     * Called by the view system when the focus state of this view changes.
6103     * When the focus change event is caused by directional navigation, direction
6104     * and previouslyFocusedRect provide insight into where the focus is coming from.
6105     * When overriding, be sure to call up through to the super class so that
6106     * the standard focus handling will occur.
6107     *
6108     * @param gainFocus True if the View has focus; false otherwise.
6109     * @param direction The direction focus has moved when requestFocus()
6110     *                  is called to give this view focus. Values are
6111     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6112     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6113     *                  It may not always apply, in which case use the default.
6114     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6115     *        system, of the previously focused view.  If applicable, this will be
6116     *        passed in as finer grained information about where the focus is coming
6117     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6118     */
6119    @CallSuper
6120    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6121            @Nullable Rect previouslyFocusedRect) {
6122        if (gainFocus) {
6123            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6124        } else {
6125            notifyViewAccessibilityStateChangedIfNeeded(
6126                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6127        }
6128
6129        InputMethodManager imm = InputMethodManager.peekInstance();
6130        if (!gainFocus) {
6131            if (isPressed()) {
6132                setPressed(false);
6133            }
6134            if (imm != null && mAttachInfo != null
6135                    && mAttachInfo.mHasWindowFocus) {
6136                imm.focusOut(this);
6137            }
6138            onFocusLost();
6139        } else if (imm != null && mAttachInfo != null
6140                && mAttachInfo.mHasWindowFocus) {
6141            imm.focusIn(this);
6142        }
6143
6144        invalidate(true);
6145        ListenerInfo li = mListenerInfo;
6146        if (li != null && li.mOnFocusChangeListener != null) {
6147            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6148        }
6149
6150        if (mAttachInfo != null) {
6151            mAttachInfo.mKeyDispatchState.reset(this);
6152        }
6153    }
6154
6155    /**
6156     * Sends an accessibility event of the given type. If accessibility is
6157     * not enabled this method has no effect. The default implementation calls
6158     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6159     * to populate information about the event source (this View), then calls
6160     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6161     * populate the text content of the event source including its descendants,
6162     * and last calls
6163     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6164     * on its parent to request sending of the event to interested parties.
6165     * <p>
6166     * If an {@link AccessibilityDelegate} has been specified via calling
6167     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6168     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6169     * responsible for handling this call.
6170     * </p>
6171     *
6172     * @param eventType The type of the event to send, as defined by several types from
6173     * {@link android.view.accessibility.AccessibilityEvent}, such as
6174     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6175     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6176     *
6177     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6178     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6179     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6180     * @see AccessibilityDelegate
6181     */
6182    public void sendAccessibilityEvent(int eventType) {
6183        if (mAccessibilityDelegate != null) {
6184            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6185        } else {
6186            sendAccessibilityEventInternal(eventType);
6187        }
6188    }
6189
6190    /**
6191     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6192     * {@link AccessibilityEvent} to make an announcement which is related to some
6193     * sort of a context change for which none of the events representing UI transitions
6194     * is a good fit. For example, announcing a new page in a book. If accessibility
6195     * is not enabled this method does nothing.
6196     *
6197     * @param text The announcement text.
6198     */
6199    public void announceForAccessibility(CharSequence text) {
6200        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6201            AccessibilityEvent event = AccessibilityEvent.obtain(
6202                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6203            onInitializeAccessibilityEvent(event);
6204            event.getText().add(text);
6205            event.setContentDescription(null);
6206            mParent.requestSendAccessibilityEvent(this, event);
6207        }
6208    }
6209
6210    /**
6211     * @see #sendAccessibilityEvent(int)
6212     *
6213     * Note: Called from the default {@link AccessibilityDelegate}.
6214     *
6215     * @hide
6216     */
6217    public void sendAccessibilityEventInternal(int eventType) {
6218        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6219            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6220        }
6221    }
6222
6223    /**
6224     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6225     * takes as an argument an empty {@link AccessibilityEvent} and does not
6226     * perform a check whether accessibility is enabled.
6227     * <p>
6228     * If an {@link AccessibilityDelegate} has been specified via calling
6229     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6230     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6231     * is responsible for handling this call.
6232     * </p>
6233     *
6234     * @param event The event to send.
6235     *
6236     * @see #sendAccessibilityEvent(int)
6237     */
6238    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6239        if (mAccessibilityDelegate != null) {
6240            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6241        } else {
6242            sendAccessibilityEventUncheckedInternal(event);
6243        }
6244    }
6245
6246    /**
6247     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6248     *
6249     * Note: Called from the default {@link AccessibilityDelegate}.
6250     *
6251     * @hide
6252     */
6253    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6254        if (!isShown()) {
6255            return;
6256        }
6257        onInitializeAccessibilityEvent(event);
6258        // Only a subset of accessibility events populates text content.
6259        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6260            dispatchPopulateAccessibilityEvent(event);
6261        }
6262        // In the beginning we called #isShown(), so we know that getParent() is not null.
6263        getParent().requestSendAccessibilityEvent(this, event);
6264    }
6265
6266    /**
6267     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6268     * to its children for adding their text content to the event. Note that the
6269     * event text is populated in a separate dispatch path since we add to the
6270     * event not only the text of the source but also the text of all its descendants.
6271     * A typical implementation will call
6272     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6273     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6274     * on each child. Override this method if custom population of the event text
6275     * content is required.
6276     * <p>
6277     * If an {@link AccessibilityDelegate} has been specified via calling
6278     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6279     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6280     * is responsible for handling this call.
6281     * </p>
6282     * <p>
6283     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6284     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6285     * </p>
6286     *
6287     * @param event The event.
6288     *
6289     * @return True if the event population was completed.
6290     */
6291    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6292        if (mAccessibilityDelegate != null) {
6293            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6294        } else {
6295            return dispatchPopulateAccessibilityEventInternal(event);
6296        }
6297    }
6298
6299    /**
6300     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6301     *
6302     * Note: Called from the default {@link AccessibilityDelegate}.
6303     *
6304     * @hide
6305     */
6306    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6307        onPopulateAccessibilityEvent(event);
6308        return false;
6309    }
6310
6311    /**
6312     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6313     * giving a chance to this View to populate the accessibility event with its
6314     * text content. While this method is free to modify event
6315     * attributes other than text content, doing so should normally be performed in
6316     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6317     * <p>
6318     * Example: Adding formatted date string to an accessibility event in addition
6319     *          to the text added by the super implementation:
6320     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6321     *     super.onPopulateAccessibilityEvent(event);
6322     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6323     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6324     *         mCurrentDate.getTimeInMillis(), flags);
6325     *     event.getText().add(selectedDateUtterance);
6326     * }</pre>
6327     * <p>
6328     * If an {@link AccessibilityDelegate} has been specified via calling
6329     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6330     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6331     * is responsible for handling this call.
6332     * </p>
6333     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6334     * information to the event, in case the default implementation has basic information to add.
6335     * </p>
6336     *
6337     * @param event The accessibility event which to populate.
6338     *
6339     * @see #sendAccessibilityEvent(int)
6340     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6341     */
6342    @CallSuper
6343    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6344        if (mAccessibilityDelegate != null) {
6345            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6346        } else {
6347            onPopulateAccessibilityEventInternal(event);
6348        }
6349    }
6350
6351    /**
6352     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6353     *
6354     * Note: Called from the default {@link AccessibilityDelegate}.
6355     *
6356     * @hide
6357     */
6358    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6359    }
6360
6361    /**
6362     * Initializes an {@link AccessibilityEvent} with information about
6363     * this View which is the event source. In other words, the source of
6364     * an accessibility event is the view whose state change triggered firing
6365     * the event.
6366     * <p>
6367     * Example: Setting the password property of an event in addition
6368     *          to properties set by the super implementation:
6369     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6370     *     super.onInitializeAccessibilityEvent(event);
6371     *     event.setPassword(true);
6372     * }</pre>
6373     * <p>
6374     * If an {@link AccessibilityDelegate} has been specified via calling
6375     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6376     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6377     * is responsible for handling this call.
6378     * </p>
6379     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6380     * information to the event, in case the default implementation has basic information to add.
6381     * </p>
6382     * @param event The event to initialize.
6383     *
6384     * @see #sendAccessibilityEvent(int)
6385     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6386     */
6387    @CallSuper
6388    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6389        if (mAccessibilityDelegate != null) {
6390            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6391        } else {
6392            onInitializeAccessibilityEventInternal(event);
6393        }
6394    }
6395
6396    /**
6397     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6398     *
6399     * Note: Called from the default {@link AccessibilityDelegate}.
6400     *
6401     * @hide
6402     */
6403    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6404        event.setSource(this);
6405        event.setClassName(getAccessibilityClassName());
6406        event.setPackageName(getContext().getPackageName());
6407        event.setEnabled(isEnabled());
6408        event.setContentDescription(mContentDescription);
6409
6410        switch (event.getEventType()) {
6411            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6412                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6413                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6414                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6415                event.setItemCount(focusablesTempList.size());
6416                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6417                if (mAttachInfo != null) {
6418                    focusablesTempList.clear();
6419                }
6420            } break;
6421            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6422                CharSequence text = getIterableTextForAccessibility();
6423                if (text != null && text.length() > 0) {
6424                    event.setFromIndex(getAccessibilitySelectionStart());
6425                    event.setToIndex(getAccessibilitySelectionEnd());
6426                    event.setItemCount(text.length());
6427                }
6428            } break;
6429        }
6430    }
6431
6432    /**
6433     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6434     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6435     * This method is responsible for obtaining an accessibility node info from a
6436     * pool of reusable instances and calling
6437     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6438     * initialize the former.
6439     * <p>
6440     * Note: The client is responsible for recycling the obtained instance by calling
6441     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6442     * </p>
6443     *
6444     * @return A populated {@link AccessibilityNodeInfo}.
6445     *
6446     * @see AccessibilityNodeInfo
6447     */
6448    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6449        if (mAccessibilityDelegate != null) {
6450            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6451        } else {
6452            return createAccessibilityNodeInfoInternal();
6453        }
6454    }
6455
6456    /**
6457     * @see #createAccessibilityNodeInfo()
6458     *
6459     * @hide
6460     */
6461    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6462        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6463        if (provider != null) {
6464            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6465        } else {
6466            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6467            onInitializeAccessibilityNodeInfo(info);
6468            return info;
6469        }
6470    }
6471
6472    /**
6473     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6474     * The base implementation sets:
6475     * <ul>
6476     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6477     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6478     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6479     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6480     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6481     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6482     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6483     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6484     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6485     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6486     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6487     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6488     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6489     * </ul>
6490     * <p>
6491     * Subclasses should override this method, call the super implementation,
6492     * and set additional attributes.
6493     * </p>
6494     * <p>
6495     * If an {@link AccessibilityDelegate} has been specified via calling
6496     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6497     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6498     * is responsible for handling this call.
6499     * </p>
6500     *
6501     * @param info The instance to initialize.
6502     */
6503    @CallSuper
6504    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6505        if (mAccessibilityDelegate != null) {
6506            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6507        } else {
6508            onInitializeAccessibilityNodeInfoInternal(info);
6509        }
6510    }
6511
6512    /**
6513     * Gets the location of this view in screen coordinates.
6514     *
6515     * @param outRect The output location
6516     * @hide
6517     */
6518    public void getBoundsOnScreen(Rect outRect) {
6519        getBoundsOnScreen(outRect, false);
6520    }
6521
6522    /**
6523     * Gets the location of this view in screen coordinates.
6524     *
6525     * @param outRect The output location
6526     * @param clipToParent Whether to clip child bounds to the parent ones.
6527     * @hide
6528     */
6529    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6530        if (mAttachInfo == null) {
6531            return;
6532        }
6533
6534        RectF position = mAttachInfo.mTmpTransformRect;
6535        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6536
6537        if (!hasIdentityMatrix()) {
6538            getMatrix().mapRect(position);
6539        }
6540
6541        position.offset(mLeft, mTop);
6542
6543        ViewParent parent = mParent;
6544        while (parent instanceof View) {
6545            View parentView = (View) parent;
6546
6547            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6548
6549            if (clipToParent) {
6550                position.left = Math.max(position.left, 0);
6551                position.top = Math.max(position.top, 0);
6552                position.right = Math.min(position.right, parentView.getWidth());
6553                position.bottom = Math.min(position.bottom, parentView.getHeight());
6554            }
6555
6556            if (!parentView.hasIdentityMatrix()) {
6557                parentView.getMatrix().mapRect(position);
6558            }
6559
6560            position.offset(parentView.mLeft, parentView.mTop);
6561
6562            parent = parentView.mParent;
6563        }
6564
6565        if (parent instanceof ViewRootImpl) {
6566            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6567            position.offset(0, -viewRootImpl.mCurScrollY);
6568        }
6569
6570        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6571
6572        outRect.set(Math.round(position.left), Math.round(position.top),
6573                Math.round(position.right), Math.round(position.bottom));
6574    }
6575
6576    /**
6577     * Return the class name of this object to be used for accessibility purposes.
6578     * Subclasses should only override this if they are implementing something that
6579     * should be seen as a completely new class of view when used by accessibility,
6580     * unrelated to the class it is deriving from.  This is used to fill in
6581     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6582     */
6583    public CharSequence getAccessibilityClassName() {
6584        return View.class.getName();
6585    }
6586
6587    /**
6588     * Called when assist structure is being retrieved from a view as part of
6589     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6590     * @param structure Fill in with structured view data.  The default implementation
6591     * fills in all data that can be inferred from the view itself.
6592     */
6593    public void onProvideStructure(ViewStructure structure) {
6594        final int id = mID;
6595        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6596                && (id&0x0000ffff) != 0) {
6597            String pkg, type, entry;
6598            try {
6599                final Resources res = getResources();
6600                entry = res.getResourceEntryName(id);
6601                type = res.getResourceTypeName(id);
6602                pkg = res.getResourcePackageName(id);
6603            } catch (Resources.NotFoundException e) {
6604                entry = type = pkg = null;
6605            }
6606            structure.setId(id, pkg, type, entry);
6607        } else {
6608            structure.setId(id, null, null, null);
6609        }
6610        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6611        if (!hasIdentityMatrix()) {
6612            structure.setTransformation(getMatrix());
6613        }
6614        structure.setElevation(getZ());
6615        structure.setVisibility(getVisibility());
6616        structure.setEnabled(isEnabled());
6617        if (isClickable()) {
6618            structure.setClickable(true);
6619        }
6620        if (isFocusable()) {
6621            structure.setFocusable(true);
6622        }
6623        if (isFocused()) {
6624            structure.setFocused(true);
6625        }
6626        if (isAccessibilityFocused()) {
6627            structure.setAccessibilityFocused(true);
6628        }
6629        if (isSelected()) {
6630            structure.setSelected(true);
6631        }
6632        if (isActivated()) {
6633            structure.setActivated(true);
6634        }
6635        if (isLongClickable()) {
6636            structure.setLongClickable(true);
6637        }
6638        if (this instanceof Checkable) {
6639            structure.setCheckable(true);
6640            if (((Checkable)this).isChecked()) {
6641                structure.setChecked(true);
6642            }
6643        }
6644        if (isContextClickable()) {
6645            structure.setContextClickable(true);
6646        }
6647        structure.setClassName(getAccessibilityClassName().toString());
6648        structure.setContentDescription(getContentDescription());
6649    }
6650
6651    /**
6652     * Called when assist structure is being retrieved from a view as part of
6653     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6654     * generate additional virtual structure under this view.  The defaullt implementation
6655     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6656     * view's virtual accessibility nodes, if any.  You can override this for a more
6657     * optimal implementation providing this data.
6658     */
6659    public void onProvideVirtualStructure(ViewStructure structure) {
6660        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6661        if (provider != null) {
6662            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6663            structure.setChildCount(1);
6664            ViewStructure root = structure.newChild(0);
6665            populateVirtualStructure(root, provider, info);
6666            info.recycle();
6667        }
6668    }
6669
6670    private void populateVirtualStructure(ViewStructure structure,
6671            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6672        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6673                null, null, null);
6674        Rect rect = structure.getTempRect();
6675        info.getBoundsInParent(rect);
6676        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6677        structure.setVisibility(VISIBLE);
6678        structure.setEnabled(info.isEnabled());
6679        if (info.isClickable()) {
6680            structure.setClickable(true);
6681        }
6682        if (info.isFocusable()) {
6683            structure.setFocusable(true);
6684        }
6685        if (info.isFocused()) {
6686            structure.setFocused(true);
6687        }
6688        if (info.isAccessibilityFocused()) {
6689            structure.setAccessibilityFocused(true);
6690        }
6691        if (info.isSelected()) {
6692            structure.setSelected(true);
6693        }
6694        if (info.isLongClickable()) {
6695            structure.setLongClickable(true);
6696        }
6697        if (info.isCheckable()) {
6698            structure.setCheckable(true);
6699            if (info.isChecked()) {
6700                structure.setChecked(true);
6701            }
6702        }
6703        if (info.isContextClickable()) {
6704            structure.setContextClickable(true);
6705        }
6706        CharSequence cname = info.getClassName();
6707        structure.setClassName(cname != null ? cname.toString() : null);
6708        structure.setContentDescription(info.getContentDescription());
6709        if (info.getText() != null || info.getError() != null) {
6710            structure.setText(info.getText(), info.getTextSelectionStart(),
6711                    info.getTextSelectionEnd());
6712        }
6713        final int NCHILDREN = info.getChildCount();
6714        if (NCHILDREN > 0) {
6715            structure.setChildCount(NCHILDREN);
6716            for (int i=0; i<NCHILDREN; i++) {
6717                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6718                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6719                ViewStructure child = structure.newChild(i);
6720                populateVirtualStructure(child, provider, cinfo);
6721                cinfo.recycle();
6722            }
6723        }
6724    }
6725
6726    /**
6727     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6728     * implementation calls {@link #onProvideStructure} and
6729     * {@link #onProvideVirtualStructure}.
6730     */
6731    public void dispatchProvideStructure(ViewStructure structure) {
6732        if (!isAssistBlocked()) {
6733            onProvideStructure(structure);
6734            onProvideVirtualStructure(structure);
6735        } else {
6736            structure.setClassName(getAccessibilityClassName().toString());
6737            structure.setAssistBlocked(true);
6738        }
6739    }
6740
6741    /**
6742     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6743     *
6744     * Note: Called from the default {@link AccessibilityDelegate}.
6745     *
6746     * @hide
6747     */
6748    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6749        if (mAttachInfo == null) {
6750            return;
6751        }
6752
6753        Rect bounds = mAttachInfo.mTmpInvalRect;
6754
6755        getDrawingRect(bounds);
6756        info.setBoundsInParent(bounds);
6757
6758        getBoundsOnScreen(bounds, true);
6759        info.setBoundsInScreen(bounds);
6760
6761        ViewParent parent = getParentForAccessibility();
6762        if (parent instanceof View) {
6763            info.setParent((View) parent);
6764        }
6765
6766        if (mID != View.NO_ID) {
6767            View rootView = getRootView();
6768            if (rootView == null) {
6769                rootView = this;
6770            }
6771
6772            View label = rootView.findLabelForView(this, mID);
6773            if (label != null) {
6774                info.setLabeledBy(label);
6775            }
6776
6777            if ((mAttachInfo.mAccessibilityFetchFlags
6778                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6779                    && Resources.resourceHasPackage(mID)) {
6780                try {
6781                    String viewId = getResources().getResourceName(mID);
6782                    info.setViewIdResourceName(viewId);
6783                } catch (Resources.NotFoundException nfe) {
6784                    /* ignore */
6785                }
6786            }
6787        }
6788
6789        if (mLabelForId != View.NO_ID) {
6790            View rootView = getRootView();
6791            if (rootView == null) {
6792                rootView = this;
6793            }
6794            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6795            if (labeled != null) {
6796                info.setLabelFor(labeled);
6797            }
6798        }
6799
6800        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6801            View rootView = getRootView();
6802            if (rootView == null) {
6803                rootView = this;
6804            }
6805            View next = rootView.findViewInsideOutShouldExist(this,
6806                    mAccessibilityTraversalBeforeId);
6807            if (next != null && next.includeForAccessibility()) {
6808                info.setTraversalBefore(next);
6809            }
6810        }
6811
6812        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6813            View rootView = getRootView();
6814            if (rootView == null) {
6815                rootView = this;
6816            }
6817            View next = rootView.findViewInsideOutShouldExist(this,
6818                    mAccessibilityTraversalAfterId);
6819            if (next != null && next.includeForAccessibility()) {
6820                info.setTraversalAfter(next);
6821            }
6822        }
6823
6824        info.setVisibleToUser(isVisibleToUser());
6825
6826        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6827                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6828            info.setImportantForAccessibility(isImportantForAccessibility());
6829        } else {
6830            info.setImportantForAccessibility(true);
6831        }
6832
6833        info.setPackageName(mContext.getPackageName());
6834        info.setClassName(getAccessibilityClassName());
6835        info.setContentDescription(getContentDescription());
6836
6837        info.setEnabled(isEnabled());
6838        info.setClickable(isClickable());
6839        info.setFocusable(isFocusable());
6840        info.setFocused(isFocused());
6841        info.setAccessibilityFocused(isAccessibilityFocused());
6842        info.setSelected(isSelected());
6843        info.setLongClickable(isLongClickable());
6844        info.setContextClickable(isContextClickable());
6845        info.setLiveRegion(getAccessibilityLiveRegion());
6846
6847        // TODO: These make sense only if we are in an AdapterView but all
6848        // views can be selected. Maybe from accessibility perspective
6849        // we should report as selectable view in an AdapterView.
6850        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6851        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6852
6853        if (isFocusable()) {
6854            if (isFocused()) {
6855                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6856            } else {
6857                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6858            }
6859        }
6860
6861        if (!isAccessibilityFocused()) {
6862            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6863        } else {
6864            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6865        }
6866
6867        if (isClickable() && isEnabled()) {
6868            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6869        }
6870
6871        if (isLongClickable() && isEnabled()) {
6872            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6873        }
6874
6875        if (isContextClickable() && isEnabled()) {
6876            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6877        }
6878
6879        CharSequence text = getIterableTextForAccessibility();
6880        if (text != null && text.length() > 0) {
6881            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6882
6883            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6884            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6885            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6886            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6887                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6888                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6889        }
6890
6891        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6892        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6893    }
6894
6895    /**
6896     * Determine the order in which this view will be drawn relative to its siblings for a11y
6897     *
6898     * @param info The info whose drawing order should be populated
6899     */
6900    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6901        /*
6902         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
6903         * drawing order may not be well-defined, and some Views with custom drawing order may
6904         * not be initialized sufficiently to respond properly getChildDrawingOrder.
6905         */
6906        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
6907            info.setDrawingOrder(0);
6908            return;
6909        }
6910        int drawingOrderInParent = 1;
6911        // Iterate up the hierarchy if parents are not important for a11y
6912        View viewAtDrawingLevel = this;
6913        final ViewParent parent = getParentForAccessibility();
6914        while (viewAtDrawingLevel != parent) {
6915            final ViewParent currentParent = viewAtDrawingLevel.getParent();
6916            if (!(currentParent instanceof ViewGroup)) {
6917                // Should only happen for the Decor
6918                drawingOrderInParent = 0;
6919                break;
6920            } else {
6921                final ViewGroup parentGroup = (ViewGroup) currentParent;
6922                final int childCount = parentGroup.getChildCount();
6923                if (childCount > 1) {
6924                    List<View> preorderedList = parentGroup.buildOrderedChildList();
6925                    if (preorderedList != null) {
6926                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
6927                        for (int i = 0; i < childDrawIndex; i++) {
6928                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
6929                        }
6930                    } else {
6931                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
6932                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
6933                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
6934                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
6935                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
6936                        if (childDrawIndex != 0) {
6937                            for (int i = 0; i < numChildrenToIterate; i++) {
6938                                final int otherDrawIndex = (customOrder ?
6939                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
6940                                if (otherDrawIndex < childDrawIndex) {
6941                                    drawingOrderInParent +=
6942                                            numViewsForAccessibility(parentGroup.getChildAt(i));
6943                                }
6944                            }
6945                        }
6946                    }
6947                }
6948            }
6949            viewAtDrawingLevel = (View) currentParent;
6950        }
6951        info.setDrawingOrder(drawingOrderInParent);
6952    }
6953
6954    private static int numViewsForAccessibility(View view) {
6955        if (view != null) {
6956            if (view.includeForAccessibility()) {
6957                return 1;
6958            } else if (view instanceof ViewGroup) {
6959                return ((ViewGroup) view).getNumChildrenForAccessibility();
6960            }
6961        }
6962        return 0;
6963    }
6964
6965    private View findLabelForView(View view, int labeledId) {
6966        if (mMatchLabelForPredicate == null) {
6967            mMatchLabelForPredicate = new MatchLabelForPredicate();
6968        }
6969        mMatchLabelForPredicate.mLabeledId = labeledId;
6970        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6971    }
6972
6973    /**
6974     * Computes whether this view is visible to the user. Such a view is
6975     * attached, visible, all its predecessors are visible, it is not clipped
6976     * entirely by its predecessors, and has an alpha greater than zero.
6977     *
6978     * @return Whether the view is visible on the screen.
6979     *
6980     * @hide
6981     */
6982    protected boolean isVisibleToUser() {
6983        return isVisibleToUser(null);
6984    }
6985
6986    /**
6987     * Computes whether the given portion of this view is visible to the user.
6988     * Such a view is attached, visible, all its predecessors are visible,
6989     * has an alpha greater than zero, and the specified portion is not
6990     * clipped entirely by its predecessors.
6991     *
6992     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6993     *                    <code>null</code>, and the entire view will be tested in this case.
6994     *                    When <code>true</code> is returned by the function, the actual visible
6995     *                    region will be stored in this parameter; that is, if boundInView is fully
6996     *                    contained within the view, no modification will be made, otherwise regions
6997     *                    outside of the visible area of the view will be clipped.
6998     *
6999     * @return Whether the specified portion of the view is visible on the screen.
7000     *
7001     * @hide
7002     */
7003    protected boolean isVisibleToUser(Rect boundInView) {
7004        if (mAttachInfo != null) {
7005            // Attached to invisible window means this view is not visible.
7006            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7007                return false;
7008            }
7009            // An invisible predecessor or one with alpha zero means
7010            // that this view is not visible to the user.
7011            Object current = this;
7012            while (current instanceof View) {
7013                View view = (View) current;
7014                // We have attach info so this view is attached and there is no
7015                // need to check whether we reach to ViewRootImpl on the way up.
7016                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7017                        view.getVisibility() != VISIBLE) {
7018                    return false;
7019                }
7020                current = view.mParent;
7021            }
7022            // Check if the view is entirely covered by its predecessors.
7023            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7024            Point offset = mAttachInfo.mPoint;
7025            if (!getGlobalVisibleRect(visibleRect, offset)) {
7026                return false;
7027            }
7028            // Check if the visible portion intersects the rectangle of interest.
7029            if (boundInView != null) {
7030                visibleRect.offset(-offset.x, -offset.y);
7031                return boundInView.intersect(visibleRect);
7032            }
7033            return true;
7034        }
7035        return false;
7036    }
7037
7038    /**
7039     * Returns the delegate for implementing accessibility support via
7040     * composition. For more details see {@link AccessibilityDelegate}.
7041     *
7042     * @return The delegate, or null if none set.
7043     *
7044     * @hide
7045     */
7046    public AccessibilityDelegate getAccessibilityDelegate() {
7047        return mAccessibilityDelegate;
7048    }
7049
7050    /**
7051     * Sets a delegate for implementing accessibility support via composition
7052     * (as opposed to inheritance). For more details, see
7053     * {@link AccessibilityDelegate}.
7054     * <p>
7055     * <strong>Note:</strong> On platform versions prior to
7056     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7057     * views in the {@code android.widget.*} package are called <i>before</i>
7058     * host methods. This prevents certain properties such as class name from
7059     * being modified by overriding
7060     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7061     * as any changes will be overwritten by the host class.
7062     * <p>
7063     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7064     * methods are called <i>after</i> host methods, which all properties to be
7065     * modified without being overwritten by the host class.
7066     *
7067     * @param delegate the object to which accessibility method calls should be
7068     *                 delegated
7069     * @see AccessibilityDelegate
7070     */
7071    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7072        mAccessibilityDelegate = delegate;
7073    }
7074
7075    /**
7076     * Gets the provider for managing a virtual view hierarchy rooted at this View
7077     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7078     * that explore the window content.
7079     * <p>
7080     * If this method returns an instance, this instance is responsible for managing
7081     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7082     * View including the one representing the View itself. Similarly the returned
7083     * instance is responsible for performing accessibility actions on any virtual
7084     * view or the root view itself.
7085     * </p>
7086     * <p>
7087     * If an {@link AccessibilityDelegate} has been specified via calling
7088     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7089     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7090     * is responsible for handling this call.
7091     * </p>
7092     *
7093     * @return The provider.
7094     *
7095     * @see AccessibilityNodeProvider
7096     */
7097    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7098        if (mAccessibilityDelegate != null) {
7099            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7100        } else {
7101            return null;
7102        }
7103    }
7104
7105    /**
7106     * Gets the unique identifier of this view on the screen for accessibility purposes.
7107     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7108     *
7109     * @return The view accessibility id.
7110     *
7111     * @hide
7112     */
7113    public int getAccessibilityViewId() {
7114        if (mAccessibilityViewId == NO_ID) {
7115            mAccessibilityViewId = sNextAccessibilityViewId++;
7116        }
7117        return mAccessibilityViewId;
7118    }
7119
7120    /**
7121     * Gets the unique identifier of the window in which this View reseides.
7122     *
7123     * @return The window accessibility id.
7124     *
7125     * @hide
7126     */
7127    public int getAccessibilityWindowId() {
7128        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7129                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7130    }
7131
7132    /**
7133     * Returns the {@link View}'s content description.
7134     * <p>
7135     * <strong>Note:</strong> Do not override this method, as it will have no
7136     * effect on the content description presented to accessibility services.
7137     * You must call {@link #setContentDescription(CharSequence)} to modify the
7138     * content description.
7139     *
7140     * @return the content description
7141     * @see #setContentDescription(CharSequence)
7142     * @attr ref android.R.styleable#View_contentDescription
7143     */
7144    @ViewDebug.ExportedProperty(category = "accessibility")
7145    public CharSequence getContentDescription() {
7146        return mContentDescription;
7147    }
7148
7149    /**
7150     * Sets the {@link View}'s content description.
7151     * <p>
7152     * A content description briefly describes the view and is primarily used
7153     * for accessibility support to determine how a view should be presented to
7154     * the user. In the case of a view with no textual representation, such as
7155     * {@link android.widget.ImageButton}, a useful content description
7156     * explains what the view does. For example, an image button with a phone
7157     * icon that is used to place a call may use "Call" as its content
7158     * description. An image of a floppy disk that is used to save a file may
7159     * use "Save".
7160     *
7161     * @param contentDescription The content description.
7162     * @see #getContentDescription()
7163     * @attr ref android.R.styleable#View_contentDescription
7164     */
7165    @RemotableViewMethod
7166    public void setContentDescription(CharSequence contentDescription) {
7167        if (mContentDescription == null) {
7168            if (contentDescription == null) {
7169                return;
7170            }
7171        } else if (mContentDescription.equals(contentDescription)) {
7172            return;
7173        }
7174        mContentDescription = contentDescription;
7175        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7176        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7177            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7178            notifySubtreeAccessibilityStateChangedIfNeeded();
7179        } else {
7180            notifyViewAccessibilityStateChangedIfNeeded(
7181                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7182        }
7183    }
7184
7185    /**
7186     * Sets the id of a view before which this one is visited in accessibility traversal.
7187     * A screen-reader must visit the content of this view before the content of the one
7188     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7189     * will traverse the entire content of B before traversing the entire content of A,
7190     * regardles of what traversal strategy it is using.
7191     * <p>
7192     * Views that do not have specified before/after relationships are traversed in order
7193     * determined by the screen-reader.
7194     * </p>
7195     * <p>
7196     * Setting that this view is before a view that is not important for accessibility
7197     * or if this view is not important for accessibility will have no effect as the
7198     * screen-reader is not aware of unimportant views.
7199     * </p>
7200     *
7201     * @param beforeId The id of a view this one precedes in accessibility traversal.
7202     *
7203     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7204     *
7205     * @see #setImportantForAccessibility(int)
7206     */
7207    @RemotableViewMethod
7208    public void setAccessibilityTraversalBefore(int beforeId) {
7209        if (mAccessibilityTraversalBeforeId == beforeId) {
7210            return;
7211        }
7212        mAccessibilityTraversalBeforeId = beforeId;
7213        notifyViewAccessibilityStateChangedIfNeeded(
7214                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7215    }
7216
7217    /**
7218     * Gets the id of a view before which this one is visited in accessibility traversal.
7219     *
7220     * @return The id of a view this one precedes in accessibility traversal if
7221     *         specified, otherwise {@link #NO_ID}.
7222     *
7223     * @see #setAccessibilityTraversalBefore(int)
7224     */
7225    public int getAccessibilityTraversalBefore() {
7226        return mAccessibilityTraversalBeforeId;
7227    }
7228
7229    /**
7230     * Sets the id of a view after which this one is visited in accessibility traversal.
7231     * A screen-reader must visit the content of the other view before the content of this
7232     * one. For example, if view B is set to be after view A, then a screen-reader
7233     * will traverse the entire content of A before traversing the entire content of B,
7234     * regardles of what traversal strategy it is using.
7235     * <p>
7236     * Views that do not have specified before/after relationships are traversed in order
7237     * determined by the screen-reader.
7238     * </p>
7239     * <p>
7240     * Setting that this view is after a view that is not important for accessibility
7241     * or if this view is not important for accessibility will have no effect as the
7242     * screen-reader is not aware of unimportant views.
7243     * </p>
7244     *
7245     * @param afterId The id of a view this one succedees in accessibility traversal.
7246     *
7247     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7248     *
7249     * @see #setImportantForAccessibility(int)
7250     */
7251    @RemotableViewMethod
7252    public void setAccessibilityTraversalAfter(int afterId) {
7253        if (mAccessibilityTraversalAfterId == afterId) {
7254            return;
7255        }
7256        mAccessibilityTraversalAfterId = afterId;
7257        notifyViewAccessibilityStateChangedIfNeeded(
7258                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7259    }
7260
7261    /**
7262     * Gets the id of a view after which this one is visited in accessibility traversal.
7263     *
7264     * @return The id of a view this one succeedes in accessibility traversal if
7265     *         specified, otherwise {@link #NO_ID}.
7266     *
7267     * @see #setAccessibilityTraversalAfter(int)
7268     */
7269    public int getAccessibilityTraversalAfter() {
7270        return mAccessibilityTraversalAfterId;
7271    }
7272
7273    /**
7274     * Gets the id of a view for which this view serves as a label for
7275     * accessibility purposes.
7276     *
7277     * @return The labeled view id.
7278     */
7279    @ViewDebug.ExportedProperty(category = "accessibility")
7280    public int getLabelFor() {
7281        return mLabelForId;
7282    }
7283
7284    /**
7285     * Sets the id of a view for which this view serves as a label for
7286     * accessibility purposes.
7287     *
7288     * @param id The labeled view id.
7289     */
7290    @RemotableViewMethod
7291    public void setLabelFor(@IdRes int id) {
7292        if (mLabelForId == id) {
7293            return;
7294        }
7295        mLabelForId = id;
7296        if (mLabelForId != View.NO_ID
7297                && mID == View.NO_ID) {
7298            mID = generateViewId();
7299        }
7300        notifyViewAccessibilityStateChangedIfNeeded(
7301                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7302    }
7303
7304    /**
7305     * Invoked whenever this view loses focus, either by losing window focus or by losing
7306     * focus within its window. This method can be used to clear any state tied to the
7307     * focus. For instance, if a button is held pressed with the trackball and the window
7308     * loses focus, this method can be used to cancel the press.
7309     *
7310     * Subclasses of View overriding this method should always call super.onFocusLost().
7311     *
7312     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7313     * @see #onWindowFocusChanged(boolean)
7314     *
7315     * @hide pending API council approval
7316     */
7317    @CallSuper
7318    protected void onFocusLost() {
7319        resetPressedState();
7320    }
7321
7322    private void resetPressedState() {
7323        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7324            return;
7325        }
7326
7327        if (isPressed()) {
7328            setPressed(false);
7329
7330            if (!mHasPerformedLongPress) {
7331                removeLongPressCallback();
7332            }
7333        }
7334    }
7335
7336    /**
7337     * Returns true if this view has focus
7338     *
7339     * @return True if this view has focus, false otherwise.
7340     */
7341    @ViewDebug.ExportedProperty(category = "focus")
7342    public boolean isFocused() {
7343        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7344    }
7345
7346    /**
7347     * Find the view in the hierarchy rooted at this view that currently has
7348     * focus.
7349     *
7350     * @return The view that currently has focus, or null if no focused view can
7351     *         be found.
7352     */
7353    public View findFocus() {
7354        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7355    }
7356
7357    /**
7358     * Indicates whether this view is one of the set of scrollable containers in
7359     * its window.
7360     *
7361     * @return whether this view is one of the set of scrollable containers in
7362     * its window
7363     *
7364     * @attr ref android.R.styleable#View_isScrollContainer
7365     */
7366    public boolean isScrollContainer() {
7367        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7368    }
7369
7370    /**
7371     * Change whether this view is one of the set of scrollable containers in
7372     * its window.  This will be used to determine whether the window can
7373     * resize or must pan when a soft input area is open -- scrollable
7374     * containers allow the window to use resize mode since the container
7375     * will appropriately shrink.
7376     *
7377     * @attr ref android.R.styleable#View_isScrollContainer
7378     */
7379    public void setScrollContainer(boolean isScrollContainer) {
7380        if (isScrollContainer) {
7381            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7382                mAttachInfo.mScrollContainers.add(this);
7383                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7384            }
7385            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7386        } else {
7387            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7388                mAttachInfo.mScrollContainers.remove(this);
7389            }
7390            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7391        }
7392    }
7393
7394    /**
7395     * Returns the quality of the drawing cache.
7396     *
7397     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7398     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7399     *
7400     * @see #setDrawingCacheQuality(int)
7401     * @see #setDrawingCacheEnabled(boolean)
7402     * @see #isDrawingCacheEnabled()
7403     *
7404     * @attr ref android.R.styleable#View_drawingCacheQuality
7405     */
7406    @DrawingCacheQuality
7407    public int getDrawingCacheQuality() {
7408        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7409    }
7410
7411    /**
7412     * Set the drawing cache quality of this view. This value is used only when the
7413     * drawing cache is enabled
7414     *
7415     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7416     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7417     *
7418     * @see #getDrawingCacheQuality()
7419     * @see #setDrawingCacheEnabled(boolean)
7420     * @see #isDrawingCacheEnabled()
7421     *
7422     * @attr ref android.R.styleable#View_drawingCacheQuality
7423     */
7424    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7425        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7426    }
7427
7428    /**
7429     * Returns whether the screen should remain on, corresponding to the current
7430     * value of {@link #KEEP_SCREEN_ON}.
7431     *
7432     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7433     *
7434     * @see #setKeepScreenOn(boolean)
7435     *
7436     * @attr ref android.R.styleable#View_keepScreenOn
7437     */
7438    public boolean getKeepScreenOn() {
7439        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7440    }
7441
7442    /**
7443     * Controls whether the screen should remain on, modifying the
7444     * value of {@link #KEEP_SCREEN_ON}.
7445     *
7446     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7447     *
7448     * @see #getKeepScreenOn()
7449     *
7450     * @attr ref android.R.styleable#View_keepScreenOn
7451     */
7452    public void setKeepScreenOn(boolean keepScreenOn) {
7453        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7454    }
7455
7456    /**
7457     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7458     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7459     *
7460     * @attr ref android.R.styleable#View_nextFocusLeft
7461     */
7462    public int getNextFocusLeftId() {
7463        return mNextFocusLeftId;
7464    }
7465
7466    /**
7467     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7468     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7469     * decide automatically.
7470     *
7471     * @attr ref android.R.styleable#View_nextFocusLeft
7472     */
7473    public void setNextFocusLeftId(int nextFocusLeftId) {
7474        mNextFocusLeftId = nextFocusLeftId;
7475    }
7476
7477    /**
7478     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7479     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7480     *
7481     * @attr ref android.R.styleable#View_nextFocusRight
7482     */
7483    public int getNextFocusRightId() {
7484        return mNextFocusRightId;
7485    }
7486
7487    /**
7488     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7489     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7490     * decide automatically.
7491     *
7492     * @attr ref android.R.styleable#View_nextFocusRight
7493     */
7494    public void setNextFocusRightId(int nextFocusRightId) {
7495        mNextFocusRightId = nextFocusRightId;
7496    }
7497
7498    /**
7499     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7500     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7501     *
7502     * @attr ref android.R.styleable#View_nextFocusUp
7503     */
7504    public int getNextFocusUpId() {
7505        return mNextFocusUpId;
7506    }
7507
7508    /**
7509     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7510     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7511     * decide automatically.
7512     *
7513     * @attr ref android.R.styleable#View_nextFocusUp
7514     */
7515    public void setNextFocusUpId(int nextFocusUpId) {
7516        mNextFocusUpId = nextFocusUpId;
7517    }
7518
7519    /**
7520     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7521     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7522     *
7523     * @attr ref android.R.styleable#View_nextFocusDown
7524     */
7525    public int getNextFocusDownId() {
7526        return mNextFocusDownId;
7527    }
7528
7529    /**
7530     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7531     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7532     * decide automatically.
7533     *
7534     * @attr ref android.R.styleable#View_nextFocusDown
7535     */
7536    public void setNextFocusDownId(int nextFocusDownId) {
7537        mNextFocusDownId = nextFocusDownId;
7538    }
7539
7540    /**
7541     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7542     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7543     *
7544     * @attr ref android.R.styleable#View_nextFocusForward
7545     */
7546    public int getNextFocusForwardId() {
7547        return mNextFocusForwardId;
7548    }
7549
7550    /**
7551     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7552     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7553     * decide automatically.
7554     *
7555     * @attr ref android.R.styleable#View_nextFocusForward
7556     */
7557    public void setNextFocusForwardId(int nextFocusForwardId) {
7558        mNextFocusForwardId = nextFocusForwardId;
7559    }
7560
7561    /**
7562     * Returns the visibility of this view and all of its ancestors
7563     *
7564     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7565     */
7566    public boolean isShown() {
7567        View current = this;
7568        //noinspection ConstantConditions
7569        do {
7570            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7571                return false;
7572            }
7573            ViewParent parent = current.mParent;
7574            if (parent == null) {
7575                return false; // We are not attached to the view root
7576            }
7577            if (!(parent instanceof View)) {
7578                return true;
7579            }
7580            current = (View) parent;
7581        } while (current != null);
7582
7583        return false;
7584    }
7585
7586    /**
7587     * Called by the view hierarchy when the content insets for a window have
7588     * changed, to allow it to adjust its content to fit within those windows.
7589     * The content insets tell you the space that the status bar, input method,
7590     * and other system windows infringe on the application's window.
7591     *
7592     * <p>You do not normally need to deal with this function, since the default
7593     * window decoration given to applications takes care of applying it to the
7594     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7595     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7596     * and your content can be placed under those system elements.  You can then
7597     * use this method within your view hierarchy if you have parts of your UI
7598     * which you would like to ensure are not being covered.
7599     *
7600     * <p>The default implementation of this method simply applies the content
7601     * insets to the view's padding, consuming that content (modifying the
7602     * insets to be 0), and returning true.  This behavior is off by default, but can
7603     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7604     *
7605     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7606     * insets object is propagated down the hierarchy, so any changes made to it will
7607     * be seen by all following views (including potentially ones above in
7608     * the hierarchy since this is a depth-first traversal).  The first view
7609     * that returns true will abort the entire traversal.
7610     *
7611     * <p>The default implementation works well for a situation where it is
7612     * used with a container that covers the entire window, allowing it to
7613     * apply the appropriate insets to its content on all edges.  If you need
7614     * a more complicated layout (such as two different views fitting system
7615     * windows, one on the top of the window, and one on the bottom),
7616     * you can override the method and handle the insets however you would like.
7617     * Note that the insets provided by the framework are always relative to the
7618     * far edges of the window, not accounting for the location of the called view
7619     * within that window.  (In fact when this method is called you do not yet know
7620     * where the layout will place the view, as it is done before layout happens.)
7621     *
7622     * <p>Note: unlike many View methods, there is no dispatch phase to this
7623     * call.  If you are overriding it in a ViewGroup and want to allow the
7624     * call to continue to your children, you must be sure to call the super
7625     * implementation.
7626     *
7627     * <p>Here is a sample layout that makes use of fitting system windows
7628     * to have controls for a video view placed inside of the window decorations
7629     * that it hides and shows.  This can be used with code like the second
7630     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7631     *
7632     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7633     *
7634     * @param insets Current content insets of the window.  Prior to
7635     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7636     * the insets or else you and Android will be unhappy.
7637     *
7638     * @return {@code true} if this view applied the insets and it should not
7639     * continue propagating further down the hierarchy, {@code false} otherwise.
7640     * @see #getFitsSystemWindows()
7641     * @see #setFitsSystemWindows(boolean)
7642     * @see #setSystemUiVisibility(int)
7643     *
7644     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7645     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7646     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7647     * to implement handling their own insets.
7648     */
7649    protected boolean fitSystemWindows(Rect insets) {
7650        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7651            if (insets == null) {
7652                // Null insets by definition have already been consumed.
7653                // This call cannot apply insets since there are none to apply,
7654                // so return false.
7655                return false;
7656            }
7657            // If we're not in the process of dispatching the newer apply insets call,
7658            // that means we're not in the compatibility path. Dispatch into the newer
7659            // apply insets path and take things from there.
7660            try {
7661                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7662                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7663            } finally {
7664                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7665            }
7666        } else {
7667            // We're being called from the newer apply insets path.
7668            // Perform the standard fallback behavior.
7669            return fitSystemWindowsInt(insets);
7670        }
7671    }
7672
7673    private boolean fitSystemWindowsInt(Rect insets) {
7674        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7675            mUserPaddingStart = UNDEFINED_PADDING;
7676            mUserPaddingEnd = UNDEFINED_PADDING;
7677            Rect localInsets = sThreadLocal.get();
7678            if (localInsets == null) {
7679                localInsets = new Rect();
7680                sThreadLocal.set(localInsets);
7681            }
7682            boolean res = computeFitSystemWindows(insets, localInsets);
7683            mUserPaddingLeftInitial = localInsets.left;
7684            mUserPaddingRightInitial = localInsets.right;
7685            internalSetPadding(localInsets.left, localInsets.top,
7686                    localInsets.right, localInsets.bottom);
7687            return res;
7688        }
7689        return false;
7690    }
7691
7692    /**
7693     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7694     *
7695     * <p>This method should be overridden by views that wish to apply a policy different from or
7696     * in addition to the default behavior. Clients that wish to force a view subtree
7697     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7698     *
7699     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7700     * it will be called during dispatch instead of this method. The listener may optionally
7701     * call this method from its own implementation if it wishes to apply the view's default
7702     * insets policy in addition to its own.</p>
7703     *
7704     * <p>Implementations of this method should either return the insets parameter unchanged
7705     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7706     * that this view applied itself. This allows new inset types added in future platform
7707     * versions to pass through existing implementations unchanged without being erroneously
7708     * consumed.</p>
7709     *
7710     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7711     * property is set then the view will consume the system window insets and apply them
7712     * as padding for the view.</p>
7713     *
7714     * @param insets Insets to apply
7715     * @return The supplied insets with any applied insets consumed
7716     */
7717    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7718        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7719            // We weren't called from within a direct call to fitSystemWindows,
7720            // call into it as a fallback in case we're in a class that overrides it
7721            // and has logic to perform.
7722            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7723                return insets.consumeSystemWindowInsets();
7724            }
7725        } else {
7726            // We were called from within a direct call to fitSystemWindows.
7727            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7728                return insets.consumeSystemWindowInsets();
7729            }
7730        }
7731        return insets;
7732    }
7733
7734    /**
7735     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7736     * window insets to this view. The listener's
7737     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7738     * method will be called instead of the view's
7739     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7740     *
7741     * @param listener Listener to set
7742     *
7743     * @see #onApplyWindowInsets(WindowInsets)
7744     */
7745    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7746        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7747    }
7748
7749    /**
7750     * Request to apply the given window insets to this view or another view in its subtree.
7751     *
7752     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7753     * obscured by window decorations or overlays. This can include the status and navigation bars,
7754     * action bars, input methods and more. New inset categories may be added in the future.
7755     * The method returns the insets provided minus any that were applied by this view or its
7756     * children.</p>
7757     *
7758     * <p>Clients wishing to provide custom behavior should override the
7759     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7760     * {@link OnApplyWindowInsetsListener} via the
7761     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7762     * method.</p>
7763     *
7764     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7765     * </p>
7766     *
7767     * @param insets Insets to apply
7768     * @return The provided insets minus the insets that were consumed
7769     */
7770    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7771        try {
7772            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7773            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7774                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7775            } else {
7776                return onApplyWindowInsets(insets);
7777            }
7778        } finally {
7779            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7780        }
7781    }
7782
7783    /**
7784     * Compute the view's coordinate within the surface.
7785     *
7786     * <p>Computes the coordinates of this view in its surface. The argument
7787     * must be an array of two integers. After the method returns, the array
7788     * contains the x and y location in that order.</p>
7789     * @hide
7790     * @param location an array of two integers in which to hold the coordinates
7791     */
7792    public void getLocationInSurface(@Size(2) int[] location) {
7793        getLocationInWindow(location);
7794        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7795            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7796            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7797        }
7798    }
7799
7800    /**
7801     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7802     * only available if the view is attached.
7803     *
7804     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7805     */
7806    public WindowInsets getRootWindowInsets() {
7807        if (mAttachInfo != null) {
7808            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7809        }
7810        return null;
7811    }
7812
7813    /**
7814     * @hide Compute the insets that should be consumed by this view and the ones
7815     * that should propagate to those under it.
7816     */
7817    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7818        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7819                || mAttachInfo == null
7820                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7821                        && !mAttachInfo.mOverscanRequested)) {
7822            outLocalInsets.set(inoutInsets);
7823            inoutInsets.set(0, 0, 0, 0);
7824            return true;
7825        } else {
7826            // The application wants to take care of fitting system window for
7827            // the content...  however we still need to take care of any overscan here.
7828            final Rect overscan = mAttachInfo.mOverscanInsets;
7829            outLocalInsets.set(overscan);
7830            inoutInsets.left -= overscan.left;
7831            inoutInsets.top -= overscan.top;
7832            inoutInsets.right -= overscan.right;
7833            inoutInsets.bottom -= overscan.bottom;
7834            return false;
7835        }
7836    }
7837
7838    /**
7839     * Compute insets that should be consumed by this view and the ones that should propagate
7840     * to those under it.
7841     *
7842     * @param in Insets currently being processed by this View, likely received as a parameter
7843     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7844     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7845     *                       by this view
7846     * @return Insets that should be passed along to views under this one
7847     */
7848    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7849        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7850                || mAttachInfo == null
7851                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7852            outLocalInsets.set(in.getSystemWindowInsets());
7853            return in.consumeSystemWindowInsets();
7854        } else {
7855            outLocalInsets.set(0, 0, 0, 0);
7856            return in;
7857        }
7858    }
7859
7860    /**
7861     * Sets whether or not this view should account for system screen decorations
7862     * such as the status bar and inset its content; that is, controlling whether
7863     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7864     * executed.  See that method for more details.
7865     *
7866     * <p>Note that if you are providing your own implementation of
7867     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7868     * flag to true -- your implementation will be overriding the default
7869     * implementation that checks this flag.
7870     *
7871     * @param fitSystemWindows If true, then the default implementation of
7872     * {@link #fitSystemWindows(Rect)} will be executed.
7873     *
7874     * @attr ref android.R.styleable#View_fitsSystemWindows
7875     * @see #getFitsSystemWindows()
7876     * @see #fitSystemWindows(Rect)
7877     * @see #setSystemUiVisibility(int)
7878     */
7879    public void setFitsSystemWindows(boolean fitSystemWindows) {
7880        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7881    }
7882
7883    /**
7884     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7885     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7886     * will be executed.
7887     *
7888     * @return {@code true} if the default implementation of
7889     * {@link #fitSystemWindows(Rect)} will be executed.
7890     *
7891     * @attr ref android.R.styleable#View_fitsSystemWindows
7892     * @see #setFitsSystemWindows(boolean)
7893     * @see #fitSystemWindows(Rect)
7894     * @see #setSystemUiVisibility(int)
7895     */
7896    @ViewDebug.ExportedProperty
7897    public boolean getFitsSystemWindows() {
7898        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7899    }
7900
7901    /** @hide */
7902    public boolean fitsSystemWindows() {
7903        return getFitsSystemWindows();
7904    }
7905
7906    /**
7907     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7908     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7909     */
7910    public void requestFitSystemWindows() {
7911        if (mParent != null) {
7912            mParent.requestFitSystemWindows();
7913        }
7914    }
7915
7916    /**
7917     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7918     */
7919    public void requestApplyInsets() {
7920        requestFitSystemWindows();
7921    }
7922
7923    /**
7924     * For use by PhoneWindow to make its own system window fitting optional.
7925     * @hide
7926     */
7927    public void makeOptionalFitsSystemWindows() {
7928        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7929    }
7930
7931    /**
7932     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7933     * treat them as such.
7934     * @hide
7935     */
7936    public void getOutsets(Rect outOutsetRect) {
7937        if (mAttachInfo != null) {
7938            outOutsetRect.set(mAttachInfo.mOutsets);
7939        } else {
7940            outOutsetRect.setEmpty();
7941        }
7942    }
7943
7944    /**
7945     * Returns the visibility status for this view.
7946     *
7947     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7948     * @attr ref android.R.styleable#View_visibility
7949     */
7950    @ViewDebug.ExportedProperty(mapping = {
7951        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7952        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7953        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7954    })
7955    @Visibility
7956    public int getVisibility() {
7957        return mViewFlags & VISIBILITY_MASK;
7958    }
7959
7960    /**
7961     * Set the enabled state of this view.
7962     *
7963     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7964     * @attr ref android.R.styleable#View_visibility
7965     */
7966    @RemotableViewMethod
7967    public void setVisibility(@Visibility int visibility) {
7968        setFlags(visibility, VISIBILITY_MASK);
7969    }
7970
7971    /**
7972     * Returns the enabled status for this view. The interpretation of the
7973     * enabled state varies by subclass.
7974     *
7975     * @return True if this view is enabled, false otherwise.
7976     */
7977    @ViewDebug.ExportedProperty
7978    public boolean isEnabled() {
7979        return (mViewFlags & ENABLED_MASK) == ENABLED;
7980    }
7981
7982    /**
7983     * Set the enabled state of this view. The interpretation of the enabled
7984     * state varies by subclass.
7985     *
7986     * @param enabled True if this view is enabled, false otherwise.
7987     */
7988    @RemotableViewMethod
7989    public void setEnabled(boolean enabled) {
7990        if (enabled == isEnabled()) return;
7991
7992        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7993
7994        /*
7995         * The View most likely has to change its appearance, so refresh
7996         * the drawable state.
7997         */
7998        refreshDrawableState();
7999
8000        // Invalidate too, since the default behavior for views is to be
8001        // be drawn at 50% alpha rather than to change the drawable.
8002        invalidate(true);
8003
8004        if (!enabled) {
8005            cancelPendingInputEvents();
8006        }
8007    }
8008
8009    /**
8010     * Set whether this view can receive the focus.
8011     *
8012     * Setting this to false will also ensure that this view is not focusable
8013     * in touch mode.
8014     *
8015     * @param focusable If true, this view can receive the focus.
8016     *
8017     * @see #setFocusableInTouchMode(boolean)
8018     * @attr ref android.R.styleable#View_focusable
8019     */
8020    public void setFocusable(boolean focusable) {
8021        if (!focusable) {
8022            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8023        }
8024        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8025    }
8026
8027    /**
8028     * Set whether this view can receive focus while in touch mode.
8029     *
8030     * Setting this to true will also ensure that this view is focusable.
8031     *
8032     * @param focusableInTouchMode If true, this view can receive the focus while
8033     *   in touch mode.
8034     *
8035     * @see #setFocusable(boolean)
8036     * @attr ref android.R.styleable#View_focusableInTouchMode
8037     */
8038    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8039        // Focusable in touch mode should always be set before the focusable flag
8040        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8041        // which, in touch mode, will not successfully request focus on this view
8042        // because the focusable in touch mode flag is not set
8043        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8044        if (focusableInTouchMode) {
8045            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8046        }
8047    }
8048
8049    /**
8050     * Set whether this view should have sound effects enabled for events such as
8051     * clicking and touching.
8052     *
8053     * <p>You may wish to disable sound effects for a view if you already play sounds,
8054     * for instance, a dial key that plays dtmf tones.
8055     *
8056     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8057     * @see #isSoundEffectsEnabled()
8058     * @see #playSoundEffect(int)
8059     * @attr ref android.R.styleable#View_soundEffectsEnabled
8060     */
8061    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8062        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8063    }
8064
8065    /**
8066     * @return whether this view should have sound effects enabled for events such as
8067     *     clicking and touching.
8068     *
8069     * @see #setSoundEffectsEnabled(boolean)
8070     * @see #playSoundEffect(int)
8071     * @attr ref android.R.styleable#View_soundEffectsEnabled
8072     */
8073    @ViewDebug.ExportedProperty
8074    public boolean isSoundEffectsEnabled() {
8075        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8076    }
8077
8078    /**
8079     * Set whether this view should have haptic feedback for events such as
8080     * long presses.
8081     *
8082     * <p>You may wish to disable haptic feedback if your view already controls
8083     * its own haptic feedback.
8084     *
8085     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8086     * @see #isHapticFeedbackEnabled()
8087     * @see #performHapticFeedback(int)
8088     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8089     */
8090    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8091        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8092    }
8093
8094    /**
8095     * @return whether this view should have haptic feedback enabled for events
8096     * long presses.
8097     *
8098     * @see #setHapticFeedbackEnabled(boolean)
8099     * @see #performHapticFeedback(int)
8100     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8101     */
8102    @ViewDebug.ExportedProperty
8103    public boolean isHapticFeedbackEnabled() {
8104        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8105    }
8106
8107    /**
8108     * Returns the layout direction for this view.
8109     *
8110     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8111     *   {@link #LAYOUT_DIRECTION_RTL},
8112     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8113     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8114     *
8115     * @attr ref android.R.styleable#View_layoutDirection
8116     *
8117     * @hide
8118     */
8119    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8120        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8121        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8122        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8123        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8124    })
8125    @LayoutDir
8126    public int getRawLayoutDirection() {
8127        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8128    }
8129
8130    /**
8131     * Set the layout direction for this view. This will propagate a reset of layout direction
8132     * resolution to the view's children and resolve layout direction for this view.
8133     *
8134     * @param layoutDirection the layout direction to set. Should be one of:
8135     *
8136     * {@link #LAYOUT_DIRECTION_LTR},
8137     * {@link #LAYOUT_DIRECTION_RTL},
8138     * {@link #LAYOUT_DIRECTION_INHERIT},
8139     * {@link #LAYOUT_DIRECTION_LOCALE}.
8140     *
8141     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8142     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8143     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8144     *
8145     * @attr ref android.R.styleable#View_layoutDirection
8146     */
8147    @RemotableViewMethod
8148    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8149        if (getRawLayoutDirection() != layoutDirection) {
8150            // Reset the current layout direction and the resolved one
8151            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8152            resetRtlProperties();
8153            // Set the new layout direction (filtered)
8154            mPrivateFlags2 |=
8155                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8156            // We need to resolve all RTL properties as they all depend on layout direction
8157            resolveRtlPropertiesIfNeeded();
8158            requestLayout();
8159            invalidate(true);
8160        }
8161    }
8162
8163    /**
8164     * Returns the resolved layout direction for this view.
8165     *
8166     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8167     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8168     *
8169     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8170     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8171     *
8172     * @attr ref android.R.styleable#View_layoutDirection
8173     */
8174    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8175        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8176        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8177    })
8178    @ResolvedLayoutDir
8179    public int getLayoutDirection() {
8180        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8181        if (targetSdkVersion < JELLY_BEAN_MR1) {
8182            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8183            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8184        }
8185        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8186                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8187    }
8188
8189    /**
8190     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8191     * layout attribute and/or the inherited value from the parent
8192     *
8193     * @return true if the layout is right-to-left.
8194     *
8195     * @hide
8196     */
8197    @ViewDebug.ExportedProperty(category = "layout")
8198    public boolean isLayoutRtl() {
8199        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8200    }
8201
8202    /**
8203     * Indicates whether the view is currently tracking transient state that the
8204     * app should not need to concern itself with saving and restoring, but that
8205     * the framework should take special note to preserve when possible.
8206     *
8207     * <p>A view with transient state cannot be trivially rebound from an external
8208     * data source, such as an adapter binding item views in a list. This may be
8209     * because the view is performing an animation, tracking user selection
8210     * of content, or similar.</p>
8211     *
8212     * @return true if the view has transient state
8213     */
8214    @ViewDebug.ExportedProperty(category = "layout")
8215    public boolean hasTransientState() {
8216        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8217    }
8218
8219    /**
8220     * Set whether this view is currently tracking transient state that the
8221     * framework should attempt to preserve when possible. This flag is reference counted,
8222     * so every call to setHasTransientState(true) should be paired with a later call
8223     * to setHasTransientState(false).
8224     *
8225     * <p>A view with transient state cannot be trivially rebound from an external
8226     * data source, such as an adapter binding item views in a list. This may be
8227     * because the view is performing an animation, tracking user selection
8228     * of content, or similar.</p>
8229     *
8230     * @param hasTransientState true if this view has transient state
8231     */
8232    public void setHasTransientState(boolean hasTransientState) {
8233        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8234                mTransientStateCount - 1;
8235        if (mTransientStateCount < 0) {
8236            mTransientStateCount = 0;
8237            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8238                    "unmatched pair of setHasTransientState calls");
8239        } else if ((hasTransientState && mTransientStateCount == 1) ||
8240                (!hasTransientState && mTransientStateCount == 0)) {
8241            // update flag if we've just incremented up from 0 or decremented down to 0
8242            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8243                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8244            if (mParent != null) {
8245                try {
8246                    mParent.childHasTransientStateChanged(this, hasTransientState);
8247                } catch (AbstractMethodError e) {
8248                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8249                            " does not fully implement ViewParent", e);
8250                }
8251            }
8252        }
8253    }
8254
8255    /**
8256     * Returns true if this view is currently attached to a window.
8257     */
8258    public boolean isAttachedToWindow() {
8259        return mAttachInfo != null;
8260    }
8261
8262    /**
8263     * Returns true if this view has been through at least one layout since it
8264     * was last attached to or detached from a window.
8265     */
8266    public boolean isLaidOut() {
8267        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8268    }
8269
8270    /**
8271     * If this view doesn't do any drawing on its own, set this flag to
8272     * allow further optimizations. By default, this flag is not set on
8273     * View, but could be set on some View subclasses such as ViewGroup.
8274     *
8275     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8276     * you should clear this flag.
8277     *
8278     * @param willNotDraw whether or not this View draw on its own
8279     */
8280    public void setWillNotDraw(boolean willNotDraw) {
8281        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8282    }
8283
8284    /**
8285     * Returns whether or not this View draws on its own.
8286     *
8287     * @return true if this view has nothing to draw, false otherwise
8288     */
8289    @ViewDebug.ExportedProperty(category = "drawing")
8290    public boolean willNotDraw() {
8291        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8292    }
8293
8294    /**
8295     * When a View's drawing cache is enabled, drawing is redirected to an
8296     * offscreen bitmap. Some views, like an ImageView, must be able to
8297     * bypass this mechanism if they already draw a single bitmap, to avoid
8298     * unnecessary usage of the memory.
8299     *
8300     * @param willNotCacheDrawing true if this view does not cache its
8301     *        drawing, false otherwise
8302     */
8303    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8304        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8305    }
8306
8307    /**
8308     * Returns whether or not this View can cache its drawing or not.
8309     *
8310     * @return true if this view does not cache its drawing, false otherwise
8311     */
8312    @ViewDebug.ExportedProperty(category = "drawing")
8313    public boolean willNotCacheDrawing() {
8314        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8315    }
8316
8317    /**
8318     * Indicates whether this view reacts to click events or not.
8319     *
8320     * @return true if the view is clickable, false otherwise
8321     *
8322     * @see #setClickable(boolean)
8323     * @attr ref android.R.styleable#View_clickable
8324     */
8325    @ViewDebug.ExportedProperty
8326    public boolean isClickable() {
8327        return (mViewFlags & CLICKABLE) == CLICKABLE;
8328    }
8329
8330    /**
8331     * Enables or disables click events for this view. When a view
8332     * is clickable it will change its state to "pressed" on every click.
8333     * Subclasses should set the view clickable to visually react to
8334     * user's clicks.
8335     *
8336     * @param clickable true to make the view clickable, false otherwise
8337     *
8338     * @see #isClickable()
8339     * @attr ref android.R.styleable#View_clickable
8340     */
8341    public void setClickable(boolean clickable) {
8342        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8343    }
8344
8345    /**
8346     * Indicates whether this view reacts to long click events or not.
8347     *
8348     * @return true if the view is long clickable, false otherwise
8349     *
8350     * @see #setLongClickable(boolean)
8351     * @attr ref android.R.styleable#View_longClickable
8352     */
8353    public boolean isLongClickable() {
8354        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8355    }
8356
8357    /**
8358     * Enables or disables long click events for this view. When a view is long
8359     * clickable it reacts to the user holding down the button for a longer
8360     * duration than a tap. This event can either launch the listener or a
8361     * context menu.
8362     *
8363     * @param longClickable true to make the view long clickable, false otherwise
8364     * @see #isLongClickable()
8365     * @attr ref android.R.styleable#View_longClickable
8366     */
8367    public void setLongClickable(boolean longClickable) {
8368        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8369    }
8370
8371    /**
8372     * Indicates whether this view reacts to context clicks or not.
8373     *
8374     * @return true if the view is context clickable, false otherwise
8375     * @see #setContextClickable(boolean)
8376     * @attr ref android.R.styleable#View_contextClickable
8377     */
8378    public boolean isContextClickable() {
8379        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8380    }
8381
8382    /**
8383     * Enables or disables context clicking for this view. This event can launch the listener.
8384     *
8385     * @param contextClickable true to make the view react to a context click, false otherwise
8386     * @see #isContextClickable()
8387     * @attr ref android.R.styleable#View_contextClickable
8388     */
8389    public void setContextClickable(boolean contextClickable) {
8390        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8391    }
8392
8393    /**
8394     * Sets the pressed state for this view and provides a touch coordinate for
8395     * animation hinting.
8396     *
8397     * @param pressed Pass true to set the View's internal state to "pressed",
8398     *            or false to reverts the View's internal state from a
8399     *            previously set "pressed" state.
8400     * @param x The x coordinate of the touch that caused the press
8401     * @param y The y coordinate of the touch that caused the press
8402     */
8403    private void setPressed(boolean pressed, float x, float y) {
8404        if (pressed) {
8405            drawableHotspotChanged(x, y);
8406        }
8407
8408        setPressed(pressed);
8409    }
8410
8411    /**
8412     * Sets the pressed state for this view.
8413     *
8414     * @see #isClickable()
8415     * @see #setClickable(boolean)
8416     *
8417     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8418     *        the View's internal state from a previously set "pressed" state.
8419     */
8420    public void setPressed(boolean pressed) {
8421        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8422
8423        if (pressed) {
8424            mPrivateFlags |= PFLAG_PRESSED;
8425        } else {
8426            mPrivateFlags &= ~PFLAG_PRESSED;
8427        }
8428
8429        if (needsRefresh) {
8430            refreshDrawableState();
8431        }
8432        dispatchSetPressed(pressed);
8433    }
8434
8435    /**
8436     * Dispatch setPressed to all of this View's children.
8437     *
8438     * @see #setPressed(boolean)
8439     *
8440     * @param pressed The new pressed state
8441     */
8442    protected void dispatchSetPressed(boolean pressed) {
8443    }
8444
8445    /**
8446     * Indicates whether the view is currently in pressed state. Unless
8447     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8448     * the pressed state.
8449     *
8450     * @see #setPressed(boolean)
8451     * @see #isClickable()
8452     * @see #setClickable(boolean)
8453     *
8454     * @return true if the view is currently pressed, false otherwise
8455     */
8456    @ViewDebug.ExportedProperty
8457    public boolean isPressed() {
8458        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8459    }
8460
8461    /**
8462     * @hide
8463     * Indicates whether this view will participate in data collection through
8464     * {@link ViewStructure}.  If true, it will not provide any data
8465     * for itself or its children.  If false, the normal data collection will be allowed.
8466     *
8467     * @return Returns false if assist data collection is not blocked, else true.
8468     *
8469     * @see #setAssistBlocked(boolean)
8470     * @attr ref android.R.styleable#View_assistBlocked
8471     */
8472    public boolean isAssistBlocked() {
8473        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8474    }
8475
8476    /**
8477     * @hide
8478     * Controls whether assist data collection from this view and its children is enabled
8479     * (that is, whether {@link #onProvideStructure} and
8480     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8481     * allowing normal assist collection.  Setting this to false will disable assist collection.
8482     *
8483     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8484     * (the default) to allow it.
8485     *
8486     * @see #isAssistBlocked()
8487     * @see #onProvideStructure
8488     * @see #onProvideVirtualStructure
8489     * @attr ref android.R.styleable#View_assistBlocked
8490     */
8491    public void setAssistBlocked(boolean enabled) {
8492        if (enabled) {
8493            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8494        } else {
8495            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8496        }
8497    }
8498
8499    /**
8500     * Indicates whether this view will save its state (that is,
8501     * whether its {@link #onSaveInstanceState} method will be called).
8502     *
8503     * @return Returns true if the view state saving is enabled, else false.
8504     *
8505     * @see #setSaveEnabled(boolean)
8506     * @attr ref android.R.styleable#View_saveEnabled
8507     */
8508    public boolean isSaveEnabled() {
8509        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8510    }
8511
8512    /**
8513     * Controls whether the saving of this view's state is
8514     * enabled (that is, whether its {@link #onSaveInstanceState} method
8515     * will be called).  Note that even if freezing is enabled, the
8516     * view still must have an id assigned to it (via {@link #setId(int)})
8517     * for its state to be saved.  This flag can only disable the
8518     * saving of this view; any child views may still have their state saved.
8519     *
8520     * @param enabled Set to false to <em>disable</em> state saving, or true
8521     * (the default) to allow it.
8522     *
8523     * @see #isSaveEnabled()
8524     * @see #setId(int)
8525     * @see #onSaveInstanceState()
8526     * @attr ref android.R.styleable#View_saveEnabled
8527     */
8528    public void setSaveEnabled(boolean enabled) {
8529        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8530    }
8531
8532    /**
8533     * Gets whether the framework should discard touches when the view's
8534     * window is obscured by another visible window.
8535     * Refer to the {@link View} security documentation for more details.
8536     *
8537     * @return True if touch filtering is enabled.
8538     *
8539     * @see #setFilterTouchesWhenObscured(boolean)
8540     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8541     */
8542    @ViewDebug.ExportedProperty
8543    public boolean getFilterTouchesWhenObscured() {
8544        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8545    }
8546
8547    /**
8548     * Sets whether the framework should discard touches when the view's
8549     * window is obscured by another visible window.
8550     * Refer to the {@link View} security documentation for more details.
8551     *
8552     * @param enabled True if touch filtering should be enabled.
8553     *
8554     * @see #getFilterTouchesWhenObscured
8555     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8556     */
8557    public void setFilterTouchesWhenObscured(boolean enabled) {
8558        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8559                FILTER_TOUCHES_WHEN_OBSCURED);
8560    }
8561
8562    /**
8563     * Indicates whether the entire hierarchy under this view will save its
8564     * state when a state saving traversal occurs from its parent.  The default
8565     * is true; if false, these views will not be saved unless
8566     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8567     *
8568     * @return Returns true if the view state saving from parent is enabled, else false.
8569     *
8570     * @see #setSaveFromParentEnabled(boolean)
8571     */
8572    public boolean isSaveFromParentEnabled() {
8573        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8574    }
8575
8576    /**
8577     * Controls whether the entire hierarchy under this view will save its
8578     * state when a state saving traversal occurs from its parent.  The default
8579     * is true; if false, these views will not be saved unless
8580     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8581     *
8582     * @param enabled Set to false to <em>disable</em> state saving, or true
8583     * (the default) to allow it.
8584     *
8585     * @see #isSaveFromParentEnabled()
8586     * @see #setId(int)
8587     * @see #onSaveInstanceState()
8588     */
8589    public void setSaveFromParentEnabled(boolean enabled) {
8590        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8591    }
8592
8593
8594    /**
8595     * Returns whether this View is able to take focus.
8596     *
8597     * @return True if this view can take focus, or false otherwise.
8598     * @attr ref android.R.styleable#View_focusable
8599     */
8600    @ViewDebug.ExportedProperty(category = "focus")
8601    public final boolean isFocusable() {
8602        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8603    }
8604
8605    /**
8606     * When a view is focusable, it may not want to take focus when in touch mode.
8607     * For example, a button would like focus when the user is navigating via a D-pad
8608     * so that the user can click on it, but once the user starts touching the screen,
8609     * the button shouldn't take focus
8610     * @return Whether the view is focusable in touch mode.
8611     * @attr ref android.R.styleable#View_focusableInTouchMode
8612     */
8613    @ViewDebug.ExportedProperty
8614    public final boolean isFocusableInTouchMode() {
8615        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8616    }
8617
8618    /**
8619     * Find the nearest view in the specified direction that can take focus.
8620     * This does not actually give focus to that view.
8621     *
8622     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8623     *
8624     * @return The nearest focusable in the specified direction, or null if none
8625     *         can be found.
8626     */
8627    public View focusSearch(@FocusRealDirection int direction) {
8628        if (mParent != null) {
8629            return mParent.focusSearch(this, direction);
8630        } else {
8631            return null;
8632        }
8633    }
8634
8635    /**
8636     * This method is the last chance for the focused view and its ancestors to
8637     * respond to an arrow key. This is called when the focused view did not
8638     * consume the key internally, nor could the view system find a new view in
8639     * the requested direction to give focus to.
8640     *
8641     * @param focused The currently focused view.
8642     * @param direction The direction focus wants to move. One of FOCUS_UP,
8643     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8644     * @return True if the this view consumed this unhandled move.
8645     */
8646    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8647        return false;
8648    }
8649
8650    /**
8651     * If a user manually specified the next view id for a particular direction,
8652     * use the root to look up the view.
8653     * @param root The root view of the hierarchy containing this view.
8654     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8655     * or FOCUS_BACKWARD.
8656     * @return The user specified next view, or null if there is none.
8657     */
8658    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8659        switch (direction) {
8660            case FOCUS_LEFT:
8661                if (mNextFocusLeftId == View.NO_ID) return null;
8662                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8663            case FOCUS_RIGHT:
8664                if (mNextFocusRightId == View.NO_ID) return null;
8665                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8666            case FOCUS_UP:
8667                if (mNextFocusUpId == View.NO_ID) return null;
8668                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8669            case FOCUS_DOWN:
8670                if (mNextFocusDownId == View.NO_ID) return null;
8671                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8672            case FOCUS_FORWARD:
8673                if (mNextFocusForwardId == View.NO_ID) return null;
8674                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8675            case FOCUS_BACKWARD: {
8676                if (mID == View.NO_ID) return null;
8677                final int id = mID;
8678                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8679                    @Override
8680                    public boolean apply(View t) {
8681                        return t.mNextFocusForwardId == id;
8682                    }
8683                });
8684            }
8685        }
8686        return null;
8687    }
8688
8689    private View findViewInsideOutShouldExist(View root, int id) {
8690        if (mMatchIdPredicate == null) {
8691            mMatchIdPredicate = new MatchIdPredicate();
8692        }
8693        mMatchIdPredicate.mId = id;
8694        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8695        if (result == null) {
8696            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8697        }
8698        return result;
8699    }
8700
8701    /**
8702     * Find and return all focusable views that are descendants of this view,
8703     * possibly including this view if it is focusable itself.
8704     *
8705     * @param direction The direction of the focus
8706     * @return A list of focusable views
8707     */
8708    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8709        ArrayList<View> result = new ArrayList<View>(24);
8710        addFocusables(result, direction);
8711        return result;
8712    }
8713
8714    /**
8715     * Add any focusable views that are descendants of this view (possibly
8716     * including this view if it is focusable itself) to views.  If we are in touch mode,
8717     * only add views that are also focusable in touch mode.
8718     *
8719     * @param views Focusable views found so far
8720     * @param direction The direction of the focus
8721     */
8722    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8723        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
8724    }
8725
8726    /**
8727     * Adds any focusable views that are descendants of this view (possibly
8728     * including this view if it is focusable itself) to views. This method
8729     * adds all focusable views regardless if we are in touch mode or
8730     * only views focusable in touch mode if we are in touch mode or
8731     * only views that can take accessibility focus if accessibility is enabled
8732     * depending on the focusable mode parameter.
8733     *
8734     * @param views Focusable views found so far or null if all we are interested is
8735     *        the number of focusables.
8736     * @param direction The direction of the focus.
8737     * @param focusableMode The type of focusables to be added.
8738     *
8739     * @see #FOCUSABLES_ALL
8740     * @see #FOCUSABLES_TOUCH_MODE
8741     */
8742    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8743            @FocusableMode int focusableMode) {
8744        if (views == null) {
8745            return;
8746        }
8747        if (!isFocusable()) {
8748            return;
8749        }
8750        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8751                && isInTouchMode() && !isFocusableInTouchMode()) {
8752            return;
8753        }
8754        views.add(this);
8755    }
8756
8757    /**
8758     * Finds the Views that contain given text. The containment is case insensitive.
8759     * The search is performed by either the text that the View renders or the content
8760     * description that describes the view for accessibility purposes and the view does
8761     * not render or both. Clients can specify how the search is to be performed via
8762     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8763     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8764     *
8765     * @param outViews The output list of matching Views.
8766     * @param searched The text to match against.
8767     *
8768     * @see #FIND_VIEWS_WITH_TEXT
8769     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8770     * @see #setContentDescription(CharSequence)
8771     */
8772    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8773            @FindViewFlags int flags) {
8774        if (getAccessibilityNodeProvider() != null) {
8775            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8776                outViews.add(this);
8777            }
8778        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8779                && (searched != null && searched.length() > 0)
8780                && (mContentDescription != null && mContentDescription.length() > 0)) {
8781            String searchedLowerCase = searched.toString().toLowerCase();
8782            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8783            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8784                outViews.add(this);
8785            }
8786        }
8787    }
8788
8789    /**
8790     * Find and return all touchable views that are descendants of this view,
8791     * possibly including this view if it is touchable itself.
8792     *
8793     * @return A list of touchable views
8794     */
8795    public ArrayList<View> getTouchables() {
8796        ArrayList<View> result = new ArrayList<View>();
8797        addTouchables(result);
8798        return result;
8799    }
8800
8801    /**
8802     * Add any touchable views that are descendants of this view (possibly
8803     * including this view if it is touchable itself) to views.
8804     *
8805     * @param views Touchable views found so far
8806     */
8807    public void addTouchables(ArrayList<View> views) {
8808        final int viewFlags = mViewFlags;
8809
8810        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8811                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8812                && (viewFlags & ENABLED_MASK) == ENABLED) {
8813            views.add(this);
8814        }
8815    }
8816
8817    /**
8818     * Returns whether this View is accessibility focused.
8819     *
8820     * @return True if this View is accessibility focused.
8821     */
8822    public boolean isAccessibilityFocused() {
8823        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8824    }
8825
8826    /**
8827     * Call this to try to give accessibility focus to this view.
8828     *
8829     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8830     * returns false or the view is no visible or the view already has accessibility
8831     * focus.
8832     *
8833     * See also {@link #focusSearch(int)}, which is what you call to say that you
8834     * have focus, and you want your parent to look for the next one.
8835     *
8836     * @return Whether this view actually took accessibility focus.
8837     *
8838     * @hide
8839     */
8840    public boolean requestAccessibilityFocus() {
8841        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8842        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8843            return false;
8844        }
8845        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8846            return false;
8847        }
8848        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8849            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8850            ViewRootImpl viewRootImpl = getViewRootImpl();
8851            if (viewRootImpl != null) {
8852                viewRootImpl.setAccessibilityFocus(this, null);
8853            }
8854            invalidate();
8855            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8856            return true;
8857        }
8858        return false;
8859    }
8860
8861    /**
8862     * Call this to try to clear accessibility focus of this view.
8863     *
8864     * See also {@link #focusSearch(int)}, which is what you call to say that you
8865     * have focus, and you want your parent to look for the next one.
8866     *
8867     * @hide
8868     */
8869    public void clearAccessibilityFocus() {
8870        clearAccessibilityFocusNoCallbacks();
8871
8872        // Clear the global reference of accessibility focus if this view or
8873        // any of its descendants had accessibility focus. This will NOT send
8874        // an event or update internal state if focus is cleared from a
8875        // descendant view, which may leave views in inconsistent states.
8876        final ViewRootImpl viewRootImpl = getViewRootImpl();
8877        if (viewRootImpl != null) {
8878            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8879            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8880                viewRootImpl.setAccessibilityFocus(null, null);
8881            }
8882        }
8883    }
8884
8885    private void sendAccessibilityHoverEvent(int eventType) {
8886        // Since we are not delivering to a client accessibility events from not
8887        // important views (unless the clinet request that) we need to fire the
8888        // event from the deepest view exposed to the client. As a consequence if
8889        // the user crosses a not exposed view the client will see enter and exit
8890        // of the exposed predecessor followed by and enter and exit of that same
8891        // predecessor when entering and exiting the not exposed descendant. This
8892        // is fine since the client has a clear idea which view is hovered at the
8893        // price of a couple more events being sent. This is a simple and
8894        // working solution.
8895        View source = this;
8896        while (true) {
8897            if (source.includeForAccessibility()) {
8898                source.sendAccessibilityEvent(eventType);
8899                return;
8900            }
8901            ViewParent parent = source.getParent();
8902            if (parent instanceof View) {
8903                source = (View) parent;
8904            } else {
8905                return;
8906            }
8907        }
8908    }
8909
8910    /**
8911     * Clears accessibility focus without calling any callback methods
8912     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8913     * is used for clearing accessibility focus when giving this focus to
8914     * another view.
8915     */
8916    void clearAccessibilityFocusNoCallbacks() {
8917        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8918            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8919            invalidate();
8920            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8921        }
8922    }
8923
8924    /**
8925     * Call this to try to give focus to a specific view or to one of its
8926     * descendants.
8927     *
8928     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8929     * false), or if it is focusable and it is not focusable in touch mode
8930     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8931     *
8932     * See also {@link #focusSearch(int)}, which is what you call to say that you
8933     * have focus, and you want your parent to look for the next one.
8934     *
8935     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8936     * {@link #FOCUS_DOWN} and <code>null</code>.
8937     *
8938     * @return Whether this view or one of its descendants actually took focus.
8939     */
8940    public final boolean requestFocus() {
8941        return requestFocus(View.FOCUS_DOWN);
8942    }
8943
8944    /**
8945     * Call this to try to give focus to a specific view or to one of its
8946     * descendants and give it a hint about what direction focus is heading.
8947     *
8948     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8949     * false), or if it is focusable and it is not focusable in touch mode
8950     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8951     *
8952     * See also {@link #focusSearch(int)}, which is what you call to say that you
8953     * have focus, and you want your parent to look for the next one.
8954     *
8955     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8956     * <code>null</code> set for the previously focused rectangle.
8957     *
8958     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8959     * @return Whether this view or one of its descendants actually took focus.
8960     */
8961    public final boolean requestFocus(int direction) {
8962        return requestFocus(direction, null);
8963    }
8964
8965    /**
8966     * Call this to try to give focus to a specific view or to one of its descendants
8967     * and give it hints about the direction and a specific rectangle that the focus
8968     * is coming from.  The rectangle can help give larger views a finer grained hint
8969     * about where focus is coming from, and therefore, where to show selection, or
8970     * forward focus change internally.
8971     *
8972     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8973     * false), or if it is focusable and it is not focusable in touch mode
8974     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8975     *
8976     * A View will not take focus if it is not visible.
8977     *
8978     * A View will not take focus if one of its parents has
8979     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
8980     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
8981     *
8982     * See also {@link #focusSearch(int)}, which is what you call to say that you
8983     * have focus, and you want your parent to look for the next one.
8984     *
8985     * You may wish to override this method if your custom {@link View} has an internal
8986     * {@link View} that it wishes to forward the request to.
8987     *
8988     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8989     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8990     *        to give a finer grained hint about where focus is coming from.  May be null
8991     *        if there is no hint.
8992     * @return Whether this view or one of its descendants actually took focus.
8993     */
8994    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8995        return requestFocusNoSearch(direction, previouslyFocusedRect);
8996    }
8997
8998    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8999        // need to be focusable
9000        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9001                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9002            return false;
9003        }
9004
9005        // need to be focusable in touch mode if in touch mode
9006        if (isInTouchMode() &&
9007            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9008               return false;
9009        }
9010
9011        // need to not have any parents blocking us
9012        if (hasAncestorThatBlocksDescendantFocus()) {
9013            return false;
9014        }
9015
9016        handleFocusGainInternal(direction, previouslyFocusedRect);
9017        return true;
9018    }
9019
9020    /**
9021     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9022     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9023     * touch mode to request focus when they are touched.
9024     *
9025     * @return Whether this view or one of its descendants actually took focus.
9026     *
9027     * @see #isInTouchMode()
9028     *
9029     */
9030    public final boolean requestFocusFromTouch() {
9031        // Leave touch mode if we need to
9032        if (isInTouchMode()) {
9033            ViewRootImpl viewRoot = getViewRootImpl();
9034            if (viewRoot != null) {
9035                viewRoot.ensureTouchMode(false);
9036            }
9037        }
9038        return requestFocus(View.FOCUS_DOWN);
9039    }
9040
9041    /**
9042     * @return Whether any ancestor of this view blocks descendant focus.
9043     */
9044    private boolean hasAncestorThatBlocksDescendantFocus() {
9045        final boolean focusableInTouchMode = isFocusableInTouchMode();
9046        ViewParent ancestor = mParent;
9047        while (ancestor instanceof ViewGroup) {
9048            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9049            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9050                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9051                return true;
9052            } else {
9053                ancestor = vgAncestor.getParent();
9054            }
9055        }
9056        return false;
9057    }
9058
9059    /**
9060     * Gets the mode for determining whether this View is important for accessibility
9061     * which is if it fires accessibility events and if it is reported to
9062     * accessibility services that query the screen.
9063     *
9064     * @return The mode for determining whether a View is important for accessibility.
9065     *
9066     * @attr ref android.R.styleable#View_importantForAccessibility
9067     *
9068     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9069     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9070     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9071     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9072     */
9073    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9074            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9075            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9076            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9077            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9078                    to = "noHideDescendants")
9079        })
9080    public int getImportantForAccessibility() {
9081        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9082                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9083    }
9084
9085    /**
9086     * Sets the live region mode for this view. This indicates to accessibility
9087     * services whether they should automatically notify the user about changes
9088     * to the view's content description or text, or to the content descriptions
9089     * or text of the view's children (where applicable).
9090     * <p>
9091     * For example, in a login screen with a TextView that displays an "incorrect
9092     * password" notification, that view should be marked as a live region with
9093     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9094     * <p>
9095     * To disable change notifications for this view, use
9096     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9097     * mode for most views.
9098     * <p>
9099     * To indicate that the user should be notified of changes, use
9100     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9101     * <p>
9102     * If the view's changes should interrupt ongoing speech and notify the user
9103     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9104     *
9105     * @param mode The live region mode for this view, one of:
9106     *        <ul>
9107     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9108     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9109     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9110     *        </ul>
9111     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9112     */
9113    public void setAccessibilityLiveRegion(int mode) {
9114        if (mode != getAccessibilityLiveRegion()) {
9115            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9116            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9117                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9118            notifyViewAccessibilityStateChangedIfNeeded(
9119                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9120        }
9121    }
9122
9123    /**
9124     * Gets the live region mode for this View.
9125     *
9126     * @return The live region mode for the view.
9127     *
9128     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9129     *
9130     * @see #setAccessibilityLiveRegion(int)
9131     */
9132    public int getAccessibilityLiveRegion() {
9133        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9134                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9135    }
9136
9137    /**
9138     * Sets how to determine whether this view is important for accessibility
9139     * which is if it fires accessibility events and if it is reported to
9140     * accessibility services that query the screen.
9141     *
9142     * @param mode How to determine whether this view is important for accessibility.
9143     *
9144     * @attr ref android.R.styleable#View_importantForAccessibility
9145     *
9146     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9147     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9148     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9149     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9150     */
9151    public void setImportantForAccessibility(int mode) {
9152        final int oldMode = getImportantForAccessibility();
9153        if (mode != oldMode) {
9154            final boolean hideDescendants =
9155                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9156
9157            // If this node or its descendants are no longer important, try to
9158            // clear accessibility focus.
9159            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9160                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9161                if (focusHost != null) {
9162                    focusHost.clearAccessibilityFocus();
9163                }
9164            }
9165
9166            // If we're moving between AUTO and another state, we might not need
9167            // to send a subtree changed notification. We'll store the computed
9168            // importance, since we'll need to check it later to make sure.
9169            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9170                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9171            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9172            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9173            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9174                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9175            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9176                notifySubtreeAccessibilityStateChangedIfNeeded();
9177            } else {
9178                notifyViewAccessibilityStateChangedIfNeeded(
9179                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9180            }
9181        }
9182    }
9183
9184    /**
9185     * Returns the view within this view's hierarchy that is hosting
9186     * accessibility focus.
9187     *
9188     * @param searchDescendants whether to search for focus in descendant views
9189     * @return the view hosting accessibility focus, or {@code null}
9190     */
9191    private View findAccessibilityFocusHost(boolean searchDescendants) {
9192        if (isAccessibilityFocusedViewOrHost()) {
9193            return this;
9194        }
9195
9196        if (searchDescendants) {
9197            final ViewRootImpl viewRoot = getViewRootImpl();
9198            if (viewRoot != null) {
9199                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9200                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9201                    return focusHost;
9202                }
9203            }
9204        }
9205
9206        return null;
9207    }
9208
9209    /**
9210     * Computes whether this view should be exposed for accessibility. In
9211     * general, views that are interactive or provide information are exposed
9212     * while views that serve only as containers are hidden.
9213     * <p>
9214     * If an ancestor of this view has importance
9215     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9216     * returns <code>false</code>.
9217     * <p>
9218     * Otherwise, the value is computed according to the view's
9219     * {@link #getImportantForAccessibility()} value:
9220     * <ol>
9221     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9222     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9223     * </code>
9224     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9225     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9226     * view satisfies any of the following:
9227     * <ul>
9228     * <li>Is actionable, e.g. {@link #isClickable()},
9229     * {@link #isLongClickable()}, or {@link #isFocusable()}
9230     * <li>Has an {@link AccessibilityDelegate}
9231     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9232     * {@link OnKeyListener}, etc.
9233     * <li>Is an accessibility live region, e.g.
9234     * {@link #getAccessibilityLiveRegion()} is not
9235     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9236     * </ul>
9237     * </ol>
9238     *
9239     * @return Whether the view is exposed for accessibility.
9240     * @see #setImportantForAccessibility(int)
9241     * @see #getImportantForAccessibility()
9242     */
9243    public boolean isImportantForAccessibility() {
9244        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9245                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9246        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9247                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9248            return false;
9249        }
9250
9251        // Check parent mode to ensure we're not hidden.
9252        ViewParent parent = mParent;
9253        while (parent instanceof View) {
9254            if (((View) parent).getImportantForAccessibility()
9255                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9256                return false;
9257            }
9258            parent = parent.getParent();
9259        }
9260
9261        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9262                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9263                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9264    }
9265
9266    /**
9267     * Gets the parent for accessibility purposes. Note that the parent for
9268     * accessibility is not necessary the immediate parent. It is the first
9269     * predecessor that is important for accessibility.
9270     *
9271     * @return The parent for accessibility purposes.
9272     */
9273    public ViewParent getParentForAccessibility() {
9274        if (mParent instanceof View) {
9275            View parentView = (View) mParent;
9276            if (parentView.includeForAccessibility()) {
9277                return mParent;
9278            } else {
9279                return mParent.getParentForAccessibility();
9280            }
9281        }
9282        return null;
9283    }
9284
9285    /**
9286     * Adds the children of this View relevant for accessibility to the given list
9287     * as output. Since some Views are not important for accessibility the added
9288     * child views are not necessarily direct children of this view, rather they are
9289     * the first level of descendants important for accessibility.
9290     *
9291     * @param outChildren The output list that will receive children for accessibility.
9292     */
9293    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9294
9295    }
9296
9297    /**
9298     * Whether to regard this view for accessibility. A view is regarded for
9299     * accessibility if it is important for accessibility or the querying
9300     * accessibility service has explicitly requested that view not
9301     * important for accessibility are regarded.
9302     *
9303     * @return Whether to regard the view for accessibility.
9304     *
9305     * @hide
9306     */
9307    public boolean includeForAccessibility() {
9308        if (mAttachInfo != null) {
9309            return (mAttachInfo.mAccessibilityFetchFlags
9310                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9311                    || isImportantForAccessibility();
9312        }
9313        return false;
9314    }
9315
9316    /**
9317     * Returns whether the View is considered actionable from
9318     * accessibility perspective. Such view are important for
9319     * accessibility.
9320     *
9321     * @return True if the view is actionable for accessibility.
9322     *
9323     * @hide
9324     */
9325    public boolean isActionableForAccessibility() {
9326        return (isClickable() || isLongClickable() || isFocusable());
9327    }
9328
9329    /**
9330     * Returns whether the View has registered callbacks which makes it
9331     * important for accessibility.
9332     *
9333     * @return True if the view is actionable for accessibility.
9334     */
9335    private boolean hasListenersForAccessibility() {
9336        ListenerInfo info = getListenerInfo();
9337        return mTouchDelegate != null || info.mOnKeyListener != null
9338                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9339                || info.mOnHoverListener != null || info.mOnDragListener != null;
9340    }
9341
9342    /**
9343     * Notifies that the accessibility state of this view changed. The change
9344     * is local to this view and does not represent structural changes such
9345     * as children and parent. For example, the view became focusable. The
9346     * notification is at at most once every
9347     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9348     * to avoid unnecessary load to the system. Also once a view has a pending
9349     * notification this method is a NOP until the notification has been sent.
9350     *
9351     * @hide
9352     */
9353    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9354        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9355            return;
9356        }
9357        if (mSendViewStateChangedAccessibilityEvent == null) {
9358            mSendViewStateChangedAccessibilityEvent =
9359                    new SendViewStateChangedAccessibilityEvent();
9360        }
9361        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9362    }
9363
9364    /**
9365     * Notifies that the accessibility state of this view changed. The change
9366     * is *not* local to this view and does represent structural changes such
9367     * as children and parent. For example, the view size changed. The
9368     * notification is at at most once every
9369     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9370     * to avoid unnecessary load to the system. Also once a view has a pending
9371     * notification this method is a NOP until the notification has been sent.
9372     *
9373     * @hide
9374     */
9375    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9376        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9377            return;
9378        }
9379        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9380            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9381            if (mParent != null) {
9382                try {
9383                    mParent.notifySubtreeAccessibilityStateChanged(
9384                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9385                } catch (AbstractMethodError e) {
9386                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9387                            " does not fully implement ViewParent", e);
9388                }
9389            }
9390        }
9391    }
9392
9393    /**
9394     * Change the visibility of the View without triggering any other changes. This is
9395     * important for transitions, where visibility changes should not adjust focus or
9396     * trigger a new layout. This is only used when the visibility has already been changed
9397     * and we need a transient value during an animation. When the animation completes,
9398     * the original visibility value is always restored.
9399     *
9400     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9401     * @hide
9402     */
9403    public void setTransitionVisibility(@Visibility int visibility) {
9404        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9405    }
9406
9407    /**
9408     * Reset the flag indicating the accessibility state of the subtree rooted
9409     * at this view changed.
9410     */
9411    void resetSubtreeAccessibilityStateChanged() {
9412        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9413    }
9414
9415    /**
9416     * Report an accessibility action to this view's parents for delegated processing.
9417     *
9418     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9419     * call this method to delegate an accessibility action to a supporting parent. If the parent
9420     * returns true from its
9421     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9422     * method this method will return true to signify that the action was consumed.</p>
9423     *
9424     * <p>This method is useful for implementing nested scrolling child views. If
9425     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9426     * a custom view implementation may invoke this method to allow a parent to consume the
9427     * scroll first. If this method returns true the custom view should skip its own scrolling
9428     * behavior.</p>
9429     *
9430     * @param action Accessibility action to delegate
9431     * @param arguments Optional action arguments
9432     * @return true if the action was consumed by a parent
9433     */
9434    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9435        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9436            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9437                return true;
9438            }
9439        }
9440        return false;
9441    }
9442
9443    /**
9444     * Performs the specified accessibility action on the view. For
9445     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9446     * <p>
9447     * If an {@link AccessibilityDelegate} has been specified via calling
9448     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9449     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9450     * is responsible for handling this call.
9451     * </p>
9452     *
9453     * <p>The default implementation will delegate
9454     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9455     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9456     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9457     *
9458     * @param action The action to perform.
9459     * @param arguments Optional action arguments.
9460     * @return Whether the action was performed.
9461     */
9462    public boolean performAccessibilityAction(int action, Bundle arguments) {
9463      if (mAccessibilityDelegate != null) {
9464          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9465      } else {
9466          return performAccessibilityActionInternal(action, arguments);
9467      }
9468    }
9469
9470   /**
9471    * @see #performAccessibilityAction(int, Bundle)
9472    *
9473    * Note: Called from the default {@link AccessibilityDelegate}.
9474    *
9475    * @hide
9476    */
9477    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9478        if (isNestedScrollingEnabled()
9479                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9480                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9481                || action == R.id.accessibilityActionScrollUp
9482                || action == R.id.accessibilityActionScrollLeft
9483                || action == R.id.accessibilityActionScrollDown
9484                || action == R.id.accessibilityActionScrollRight)) {
9485            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9486                return true;
9487            }
9488        }
9489
9490        switch (action) {
9491            case AccessibilityNodeInfo.ACTION_CLICK: {
9492                if (isClickable()) {
9493                    performClick();
9494                    return true;
9495                }
9496            } break;
9497            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9498                if (isLongClickable()) {
9499                    performLongClick();
9500                    return true;
9501                }
9502            } break;
9503            case AccessibilityNodeInfo.ACTION_FOCUS: {
9504                if (!hasFocus()) {
9505                    // Get out of touch mode since accessibility
9506                    // wants to move focus around.
9507                    getViewRootImpl().ensureTouchMode(false);
9508                    return requestFocus();
9509                }
9510            } break;
9511            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9512                if (hasFocus()) {
9513                    clearFocus();
9514                    return !isFocused();
9515                }
9516            } break;
9517            case AccessibilityNodeInfo.ACTION_SELECT: {
9518                if (!isSelected()) {
9519                    setSelected(true);
9520                    return isSelected();
9521                }
9522            } break;
9523            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9524                if (isSelected()) {
9525                    setSelected(false);
9526                    return !isSelected();
9527                }
9528            } break;
9529            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9530                if (!isAccessibilityFocused()) {
9531                    return requestAccessibilityFocus();
9532                }
9533            } break;
9534            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9535                if (isAccessibilityFocused()) {
9536                    clearAccessibilityFocus();
9537                    return true;
9538                }
9539            } break;
9540            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9541                if (arguments != null) {
9542                    final int granularity = arguments.getInt(
9543                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9544                    final boolean extendSelection = arguments.getBoolean(
9545                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9546                    return traverseAtGranularity(granularity, true, extendSelection);
9547                }
9548            } break;
9549            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9550                if (arguments != null) {
9551                    final int granularity = arguments.getInt(
9552                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9553                    final boolean extendSelection = arguments.getBoolean(
9554                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9555                    return traverseAtGranularity(granularity, false, extendSelection);
9556                }
9557            } break;
9558            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9559                CharSequence text = getIterableTextForAccessibility();
9560                if (text == null) {
9561                    return false;
9562                }
9563                final int start = (arguments != null) ? arguments.getInt(
9564                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9565                final int end = (arguments != null) ? arguments.getInt(
9566                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9567                // Only cursor position can be specified (selection length == 0)
9568                if ((getAccessibilitySelectionStart() != start
9569                        || getAccessibilitySelectionEnd() != end)
9570                        && (start == end)) {
9571                    setAccessibilitySelection(start, end);
9572                    notifyViewAccessibilityStateChangedIfNeeded(
9573                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9574                    return true;
9575                }
9576            } break;
9577            case R.id.accessibilityActionShowOnScreen: {
9578                if (mAttachInfo != null) {
9579                    final Rect r = mAttachInfo.mTmpInvalRect;
9580                    getDrawingRect(r);
9581                    return requestRectangleOnScreen(r, true);
9582                }
9583            } break;
9584            case R.id.accessibilityActionContextClick: {
9585                if (isContextClickable()) {
9586                    performContextClick();
9587                    return true;
9588                }
9589            } break;
9590        }
9591        return false;
9592    }
9593
9594    private boolean traverseAtGranularity(int granularity, boolean forward,
9595            boolean extendSelection) {
9596        CharSequence text = getIterableTextForAccessibility();
9597        if (text == null || text.length() == 0) {
9598            return false;
9599        }
9600        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9601        if (iterator == null) {
9602            return false;
9603        }
9604        int current = getAccessibilitySelectionEnd();
9605        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9606            current = forward ? 0 : text.length();
9607        }
9608        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9609        if (range == null) {
9610            return false;
9611        }
9612        final int segmentStart = range[0];
9613        final int segmentEnd = range[1];
9614        int selectionStart;
9615        int selectionEnd;
9616        if (extendSelection && isAccessibilitySelectionExtendable()) {
9617            selectionStart = getAccessibilitySelectionStart();
9618            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9619                selectionStart = forward ? segmentStart : segmentEnd;
9620            }
9621            selectionEnd = forward ? segmentEnd : segmentStart;
9622        } else {
9623            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9624        }
9625        setAccessibilitySelection(selectionStart, selectionEnd);
9626        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9627                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9628        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9629        return true;
9630    }
9631
9632    /**
9633     * Gets the text reported for accessibility purposes.
9634     *
9635     * @return The accessibility text.
9636     *
9637     * @hide
9638     */
9639    public CharSequence getIterableTextForAccessibility() {
9640        return getContentDescription();
9641    }
9642
9643    /**
9644     * Gets whether accessibility selection can be extended.
9645     *
9646     * @return If selection is extensible.
9647     *
9648     * @hide
9649     */
9650    public boolean isAccessibilitySelectionExtendable() {
9651        return false;
9652    }
9653
9654    /**
9655     * @hide
9656     */
9657    public int getAccessibilitySelectionStart() {
9658        return mAccessibilityCursorPosition;
9659    }
9660
9661    /**
9662     * @hide
9663     */
9664    public int getAccessibilitySelectionEnd() {
9665        return getAccessibilitySelectionStart();
9666    }
9667
9668    /**
9669     * @hide
9670     */
9671    public void setAccessibilitySelection(int start, int end) {
9672        if (start ==  end && end == mAccessibilityCursorPosition) {
9673            return;
9674        }
9675        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9676            mAccessibilityCursorPosition = start;
9677        } else {
9678            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9679        }
9680        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9681    }
9682
9683    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9684            int fromIndex, int toIndex) {
9685        if (mParent == null) {
9686            return;
9687        }
9688        AccessibilityEvent event = AccessibilityEvent.obtain(
9689                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9690        onInitializeAccessibilityEvent(event);
9691        onPopulateAccessibilityEvent(event);
9692        event.setFromIndex(fromIndex);
9693        event.setToIndex(toIndex);
9694        event.setAction(action);
9695        event.setMovementGranularity(granularity);
9696        mParent.requestSendAccessibilityEvent(this, event);
9697    }
9698
9699    /**
9700     * @hide
9701     */
9702    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9703        switch (granularity) {
9704            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9705                CharSequence text = getIterableTextForAccessibility();
9706                if (text != null && text.length() > 0) {
9707                    CharacterTextSegmentIterator iterator =
9708                        CharacterTextSegmentIterator.getInstance(
9709                                mContext.getResources().getConfiguration().locale);
9710                    iterator.initialize(text.toString());
9711                    return iterator;
9712                }
9713            } break;
9714            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9715                CharSequence text = getIterableTextForAccessibility();
9716                if (text != null && text.length() > 0) {
9717                    WordTextSegmentIterator iterator =
9718                        WordTextSegmentIterator.getInstance(
9719                                mContext.getResources().getConfiguration().locale);
9720                    iterator.initialize(text.toString());
9721                    return iterator;
9722                }
9723            } break;
9724            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9725                CharSequence text = getIterableTextForAccessibility();
9726                if (text != null && text.length() > 0) {
9727                    ParagraphTextSegmentIterator iterator =
9728                        ParagraphTextSegmentIterator.getInstance();
9729                    iterator.initialize(text.toString());
9730                    return iterator;
9731                }
9732            } break;
9733        }
9734        return null;
9735    }
9736
9737    /**
9738     * @hide
9739     */
9740    public void dispatchStartTemporaryDetach() {
9741        onStartTemporaryDetach();
9742    }
9743
9744    /**
9745     * This is called when a container is going to temporarily detach a child, with
9746     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9747     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9748     * {@link #onDetachedFromWindow()} when the container is done.
9749     */
9750    public void onStartTemporaryDetach() {
9751        removeUnsetPressCallback();
9752        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9753    }
9754
9755    /**
9756     * @hide
9757     */
9758    public void dispatchFinishTemporaryDetach() {
9759        onFinishTemporaryDetach();
9760    }
9761
9762    /**
9763     * Called after {@link #onStartTemporaryDetach} when the container is done
9764     * changing the view.
9765     */
9766    public void onFinishTemporaryDetach() {
9767    }
9768
9769    /**
9770     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9771     * for this view's window.  Returns null if the view is not currently attached
9772     * to the window.  Normally you will not need to use this directly, but
9773     * just use the standard high-level event callbacks like
9774     * {@link #onKeyDown(int, KeyEvent)}.
9775     */
9776    public KeyEvent.DispatcherState getKeyDispatcherState() {
9777        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9778    }
9779
9780    /**
9781     * Dispatch a key event before it is processed by any input method
9782     * associated with the view hierarchy.  This can be used to intercept
9783     * key events in special situations before the IME consumes them; a
9784     * typical example would be handling the BACK key to update the application's
9785     * UI instead of allowing the IME to see it and close itself.
9786     *
9787     * @param event The key event to be dispatched.
9788     * @return True if the event was handled, false otherwise.
9789     */
9790    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9791        return onKeyPreIme(event.getKeyCode(), event);
9792    }
9793
9794    /**
9795     * Dispatch a key event to the next view on the focus path. This path runs
9796     * from the top of the view tree down to the currently focused view. If this
9797     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9798     * the next node down the focus path. This method also fires any key
9799     * listeners.
9800     *
9801     * @param event The key event to be dispatched.
9802     * @return True if the event was handled, false otherwise.
9803     */
9804    public boolean dispatchKeyEvent(KeyEvent event) {
9805        if (mInputEventConsistencyVerifier != null) {
9806            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9807        }
9808
9809        // Give any attached key listener a first crack at the event.
9810        //noinspection SimplifiableIfStatement
9811        ListenerInfo li = mListenerInfo;
9812        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9813                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9814            return true;
9815        }
9816
9817        if (event.dispatch(this, mAttachInfo != null
9818                ? mAttachInfo.mKeyDispatchState : null, this)) {
9819            return true;
9820        }
9821
9822        if (mInputEventConsistencyVerifier != null) {
9823            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9824        }
9825        return false;
9826    }
9827
9828    /**
9829     * Dispatches a key shortcut event.
9830     *
9831     * @param event The key event to be dispatched.
9832     * @return True if the event was handled by the view, false otherwise.
9833     */
9834    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9835        return onKeyShortcut(event.getKeyCode(), event);
9836    }
9837
9838    /**
9839     * Pass the touch screen motion event down to the target view, or this
9840     * view if it is the target.
9841     *
9842     * @param event The motion event to be dispatched.
9843     * @return True if the event was handled by the view, false otherwise.
9844     */
9845    public boolean dispatchTouchEvent(MotionEvent event) {
9846        // If the event should be handled by accessibility focus first.
9847        if (event.isTargetAccessibilityFocus()) {
9848            // We don't have focus or no virtual descendant has it, do not handle the event.
9849            if (!isAccessibilityFocusedViewOrHost()) {
9850                return false;
9851            }
9852            // We have focus and got the event, then use normal event dispatch.
9853            event.setTargetAccessibilityFocus(false);
9854        }
9855
9856        boolean result = false;
9857
9858        if (mInputEventConsistencyVerifier != null) {
9859            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9860        }
9861
9862        final int actionMasked = event.getActionMasked();
9863        if (actionMasked == MotionEvent.ACTION_DOWN) {
9864            // Defensive cleanup for new gesture
9865            stopNestedScroll();
9866        }
9867
9868        if (onFilterTouchEventForSecurity(event)) {
9869            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
9870                result = true;
9871            }
9872            //noinspection SimplifiableIfStatement
9873            ListenerInfo li = mListenerInfo;
9874            if (li != null && li.mOnTouchListener != null
9875                    && (mViewFlags & ENABLED_MASK) == ENABLED
9876                    && li.mOnTouchListener.onTouch(this, event)) {
9877                result = true;
9878            }
9879
9880            if (!result && onTouchEvent(event)) {
9881                result = true;
9882            }
9883        }
9884
9885        if (!result && mInputEventConsistencyVerifier != null) {
9886            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9887        }
9888
9889        // Clean up after nested scrolls if this is the end of a gesture;
9890        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9891        // of the gesture.
9892        if (actionMasked == MotionEvent.ACTION_UP ||
9893                actionMasked == MotionEvent.ACTION_CANCEL ||
9894                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9895            stopNestedScroll();
9896        }
9897
9898        return result;
9899    }
9900
9901    boolean isAccessibilityFocusedViewOrHost() {
9902        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9903                .getAccessibilityFocusedHost() == this);
9904    }
9905
9906    /**
9907     * Filter the touch event to apply security policies.
9908     *
9909     * @param event The motion event to be filtered.
9910     * @return True if the event should be dispatched, false if the event should be dropped.
9911     *
9912     * @see #getFilterTouchesWhenObscured
9913     */
9914    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9915        //noinspection RedundantIfStatement
9916        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9917                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9918            // Window is obscured, drop this touch.
9919            return false;
9920        }
9921        return true;
9922    }
9923
9924    /**
9925     * Pass a trackball motion event down to the focused view.
9926     *
9927     * @param event The motion event to be dispatched.
9928     * @return True if the event was handled by the view, false otherwise.
9929     */
9930    public boolean dispatchTrackballEvent(MotionEvent event) {
9931        if (mInputEventConsistencyVerifier != null) {
9932            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9933        }
9934
9935        return onTrackballEvent(event);
9936    }
9937
9938    /**
9939     * Dispatch a generic motion event.
9940     * <p>
9941     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9942     * are delivered to the view under the pointer.  All other generic motion events are
9943     * delivered to the focused view.  Hover events are handled specially and are delivered
9944     * to {@link #onHoverEvent(MotionEvent)}.
9945     * </p>
9946     *
9947     * @param event The motion event to be dispatched.
9948     * @return True if the event was handled by the view, false otherwise.
9949     */
9950    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9951        if (mInputEventConsistencyVerifier != null) {
9952            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
9953        }
9954
9955        final int source = event.getSource();
9956        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
9957            final int action = event.getAction();
9958            if (action == MotionEvent.ACTION_HOVER_ENTER
9959                    || action == MotionEvent.ACTION_HOVER_MOVE
9960                    || action == MotionEvent.ACTION_HOVER_EXIT) {
9961                if (dispatchHoverEvent(event)) {
9962                    return true;
9963                }
9964            } else if (dispatchGenericPointerEvent(event)) {
9965                return true;
9966            }
9967        } else if (dispatchGenericFocusedEvent(event)) {
9968            return true;
9969        }
9970
9971        if (dispatchGenericMotionEventInternal(event)) {
9972            return true;
9973        }
9974
9975        if (mInputEventConsistencyVerifier != null) {
9976            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9977        }
9978        return false;
9979    }
9980
9981    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
9982        //noinspection SimplifiableIfStatement
9983        ListenerInfo li = mListenerInfo;
9984        if (li != null && li.mOnGenericMotionListener != null
9985                && (mViewFlags & ENABLED_MASK) == ENABLED
9986                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
9987            return true;
9988        }
9989
9990        if (onGenericMotionEvent(event)) {
9991            return true;
9992        }
9993
9994        final int actionButton = event.getActionButton();
9995        switch (event.getActionMasked()) {
9996            case MotionEvent.ACTION_BUTTON_PRESS:
9997                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
9998                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
9999                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10000                    if (performContextClick()) {
10001                        mInContextButtonPress = true;
10002                        setPressed(true, event.getX(), event.getY());
10003                        removeTapCallback();
10004                        removeLongPressCallback();
10005                        return true;
10006                    }
10007                }
10008                break;
10009
10010            case MotionEvent.ACTION_BUTTON_RELEASE:
10011                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10012                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10013                    mInContextButtonPress = false;
10014                    mIgnoreNextUpEvent = true;
10015                }
10016                break;
10017        }
10018
10019        if (mInputEventConsistencyVerifier != null) {
10020            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10021        }
10022        return false;
10023    }
10024
10025    /**
10026     * Dispatch a hover event.
10027     * <p>
10028     * Do not call this method directly.
10029     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10030     * </p>
10031     *
10032     * @param event The motion event to be dispatched.
10033     * @return True if the event was handled by the view, false otherwise.
10034     */
10035    protected boolean dispatchHoverEvent(MotionEvent event) {
10036        ListenerInfo li = mListenerInfo;
10037        //noinspection SimplifiableIfStatement
10038        if (li != null && li.mOnHoverListener != null
10039                && (mViewFlags & ENABLED_MASK) == ENABLED
10040                && li.mOnHoverListener.onHover(this, event)) {
10041            return true;
10042        }
10043
10044        return onHoverEvent(event);
10045    }
10046
10047    /**
10048     * Returns true if the view has a child to which it has recently sent
10049     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10050     * it does not have a hovered child, then it must be the innermost hovered view.
10051     * @hide
10052     */
10053    protected boolean hasHoveredChild() {
10054        return false;
10055    }
10056
10057    /**
10058     * Dispatch a generic motion event to the view under the first pointer.
10059     * <p>
10060     * Do not call this method directly.
10061     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10062     * </p>
10063     *
10064     * @param event The motion event to be dispatched.
10065     * @return True if the event was handled by the view, false otherwise.
10066     */
10067    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10068        return false;
10069    }
10070
10071    /**
10072     * Dispatch a generic motion event to the currently focused view.
10073     * <p>
10074     * Do not call this method directly.
10075     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10076     * </p>
10077     *
10078     * @param event The motion event to be dispatched.
10079     * @return True if the event was handled by the view, false otherwise.
10080     */
10081    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10082        return false;
10083    }
10084
10085    /**
10086     * Dispatch a pointer event.
10087     * <p>
10088     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10089     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10090     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10091     * and should not be expected to handle other pointing device features.
10092     * </p>
10093     *
10094     * @param event The motion event to be dispatched.
10095     * @return True if the event was handled by the view, false otherwise.
10096     * @hide
10097     */
10098    public final boolean dispatchPointerEvent(MotionEvent event) {
10099        if (event.isTouchEvent()) {
10100            return dispatchTouchEvent(event);
10101        } else {
10102            return dispatchGenericMotionEvent(event);
10103        }
10104    }
10105
10106    /**
10107     * Called when the window containing this view gains or loses window focus.
10108     * ViewGroups should override to route to their children.
10109     *
10110     * @param hasFocus True if the window containing this view now has focus,
10111     *        false otherwise.
10112     */
10113    public void dispatchWindowFocusChanged(boolean hasFocus) {
10114        onWindowFocusChanged(hasFocus);
10115    }
10116
10117    /**
10118     * Called when the window containing this view gains or loses focus.  Note
10119     * that this is separate from view focus: to receive key events, both
10120     * your view and its window must have focus.  If a window is displayed
10121     * on top of yours that takes input focus, then your own window will lose
10122     * focus but the view focus will remain unchanged.
10123     *
10124     * @param hasWindowFocus True if the window containing this view now has
10125     *        focus, false otherwise.
10126     */
10127    public void onWindowFocusChanged(boolean hasWindowFocus) {
10128        InputMethodManager imm = InputMethodManager.peekInstance();
10129        if (!hasWindowFocus) {
10130            if (isPressed()) {
10131                setPressed(false);
10132            }
10133            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10134                imm.focusOut(this);
10135            }
10136            removeLongPressCallback();
10137            removeTapCallback();
10138            onFocusLost();
10139        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10140            imm.focusIn(this);
10141        }
10142        refreshDrawableState();
10143    }
10144
10145    /**
10146     * Returns true if this view is in a window that currently has window focus.
10147     * Note that this is not the same as the view itself having focus.
10148     *
10149     * @return True if this view is in a window that currently has window focus.
10150     */
10151    public boolean hasWindowFocus() {
10152        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10153    }
10154
10155    /**
10156     * Dispatch a view visibility change down the view hierarchy.
10157     * ViewGroups should override to route to their children.
10158     * @param changedView The view whose visibility changed. Could be 'this' or
10159     * an ancestor view.
10160     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10161     * {@link #INVISIBLE} or {@link #GONE}.
10162     */
10163    protected void dispatchVisibilityChanged(@NonNull View changedView,
10164            @Visibility int visibility) {
10165        onVisibilityChanged(changedView, visibility);
10166    }
10167
10168    /**
10169     * Called when the visibility of the view or an ancestor of the view has
10170     * changed.
10171     *
10172     * @param changedView The view whose visibility changed. May be
10173     *                    {@code this} or an ancestor view.
10174     * @param visibility The new visibility, one of {@link #VISIBLE},
10175     *                   {@link #INVISIBLE} or {@link #GONE}.
10176     */
10177    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10178    }
10179
10180    /**
10181     * Dispatch a hint about whether this view is displayed. For instance, when
10182     * a View moves out of the screen, it might receives a display hint indicating
10183     * the view is not displayed. Applications should not <em>rely</em> on this hint
10184     * as there is no guarantee that they will receive one.
10185     *
10186     * @param hint A hint about whether or not this view is displayed:
10187     * {@link #VISIBLE} or {@link #INVISIBLE}.
10188     */
10189    public void dispatchDisplayHint(@Visibility int hint) {
10190        onDisplayHint(hint);
10191    }
10192
10193    /**
10194     * Gives this view a hint about whether is displayed or not. For instance, when
10195     * a View moves out of the screen, it might receives a display hint indicating
10196     * the view is not displayed. Applications should not <em>rely</em> on this hint
10197     * as there is no guarantee that they will receive one.
10198     *
10199     * @param hint A hint about whether or not this view is displayed:
10200     * {@link #VISIBLE} or {@link #INVISIBLE}.
10201     */
10202    protected void onDisplayHint(@Visibility int hint) {
10203    }
10204
10205    /**
10206     * Dispatch a window visibility change down the view hierarchy.
10207     * ViewGroups should override to route to their children.
10208     *
10209     * @param visibility The new visibility of the window.
10210     *
10211     * @see #onWindowVisibilityChanged(int)
10212     */
10213    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10214        onWindowVisibilityChanged(visibility);
10215    }
10216
10217    /**
10218     * Called when the window containing has change its visibility
10219     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10220     * that this tells you whether or not your window is being made visible
10221     * to the window manager; this does <em>not</em> tell you whether or not
10222     * your window is obscured by other windows on the screen, even if it
10223     * is itself visible.
10224     *
10225     * @param visibility The new visibility of the window.
10226     */
10227    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10228        if (visibility == VISIBLE) {
10229            initialAwakenScrollBars();
10230        }
10231    }
10232
10233    /**
10234     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10235     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10236     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10237     *
10238     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10239     *                  ancestors or by window visibility
10240     * @return true if this view is visible to the user, not counting clipping or overlapping
10241     */
10242    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10243        final boolean thisVisible = getVisibility() == VISIBLE;
10244        if (thisVisible) {
10245            onVisibilityAggregated(isVisible);
10246        }
10247        return thisVisible && isVisible;
10248    }
10249
10250    /**
10251     * Called when the user-visibility of this View is potentially affected by a change
10252     * to this view itself, an ancestor view or the window this view is attached to.
10253     *
10254     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10255     *                  and this view's window is also visible
10256     */
10257    @CallSuper
10258    public void onVisibilityAggregated(boolean isVisible) {
10259        if (isVisible && mAttachInfo != null) {
10260            initialAwakenScrollBars();
10261        }
10262
10263        final Drawable dr = mBackground;
10264        if (dr != null && isVisible != dr.isVisible()) {
10265            dr.setVisible(isVisible, false);
10266        }
10267        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10268        if (fg != null && isVisible != fg.isVisible()) {
10269            fg.setVisible(isVisible, false);
10270        }
10271    }
10272
10273    /**
10274     * Returns the current visibility of the window this view is attached to
10275     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10276     *
10277     * @return Returns the current visibility of the view's window.
10278     */
10279    @Visibility
10280    public int getWindowVisibility() {
10281        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10282    }
10283
10284    /**
10285     * Retrieve the overall visible display size in which the window this view is
10286     * attached to has been positioned in.  This takes into account screen
10287     * decorations above the window, for both cases where the window itself
10288     * is being position inside of them or the window is being placed under
10289     * then and covered insets are used for the window to position its content
10290     * inside.  In effect, this tells you the available area where content can
10291     * be placed and remain visible to users.
10292     *
10293     * <p>This function requires an IPC back to the window manager to retrieve
10294     * the requested information, so should not be used in performance critical
10295     * code like drawing.
10296     *
10297     * @param outRect Filled in with the visible display frame.  If the view
10298     * is not attached to a window, this is simply the raw display size.
10299     */
10300    public void getWindowVisibleDisplayFrame(Rect outRect) {
10301        if (mAttachInfo != null) {
10302            try {
10303                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10304            } catch (RemoteException e) {
10305                return;
10306            }
10307            // XXX This is really broken, and probably all needs to be done
10308            // in the window manager, and we need to know more about whether
10309            // we want the area behind or in front of the IME.
10310            final Rect insets = mAttachInfo.mVisibleInsets;
10311            outRect.left += insets.left;
10312            outRect.top += insets.top;
10313            outRect.right -= insets.right;
10314            outRect.bottom -= insets.bottom;
10315            return;
10316        }
10317        // The view is not attached to a display so we don't have a context.
10318        // Make a best guess about the display size.
10319        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10320        d.getRectSize(outRect);
10321    }
10322
10323    /**
10324     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10325     * is currently in without any insets.
10326     *
10327     * @hide
10328     */
10329    public void getWindowDisplayFrame(Rect outRect) {
10330        if (mAttachInfo != null) {
10331            try {
10332                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10333            } catch (RemoteException e) {
10334                return;
10335            }
10336            return;
10337        }
10338        // The view is not attached to a display so we don't have a context.
10339        // Make a best guess about the display size.
10340        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10341        d.getRectSize(outRect);
10342    }
10343
10344    /**
10345     * Dispatch a notification about a resource configuration change down
10346     * the view hierarchy.
10347     * ViewGroups should override to route to their children.
10348     *
10349     * @param newConfig The new resource configuration.
10350     *
10351     * @see #onConfigurationChanged(android.content.res.Configuration)
10352     */
10353    public void dispatchConfigurationChanged(Configuration newConfig) {
10354        onConfigurationChanged(newConfig);
10355    }
10356
10357    /**
10358     * Called when the current configuration of the resources being used
10359     * by the application have changed.  You can use this to decide when
10360     * to reload resources that can changed based on orientation and other
10361     * configuration characteristics.  You only need to use this if you are
10362     * not relying on the normal {@link android.app.Activity} mechanism of
10363     * recreating the activity instance upon a configuration change.
10364     *
10365     * @param newConfig The new resource configuration.
10366     */
10367    protected void onConfigurationChanged(Configuration newConfig) {
10368    }
10369
10370    /**
10371     * Private function to aggregate all per-view attributes in to the view
10372     * root.
10373     */
10374    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10375        performCollectViewAttributes(attachInfo, visibility);
10376    }
10377
10378    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10379        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10380            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10381                attachInfo.mKeepScreenOn = true;
10382            }
10383            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10384            ListenerInfo li = mListenerInfo;
10385            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10386                attachInfo.mHasSystemUiListeners = true;
10387            }
10388        }
10389    }
10390
10391    void needGlobalAttributesUpdate(boolean force) {
10392        final AttachInfo ai = mAttachInfo;
10393        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10394            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10395                    || ai.mHasSystemUiListeners) {
10396                ai.mRecomputeGlobalAttributes = true;
10397            }
10398        }
10399    }
10400
10401    /**
10402     * Returns whether the device is currently in touch mode.  Touch mode is entered
10403     * once the user begins interacting with the device by touch, and affects various
10404     * things like whether focus is always visible to the user.
10405     *
10406     * @return Whether the device is in touch mode.
10407     */
10408    @ViewDebug.ExportedProperty
10409    public boolean isInTouchMode() {
10410        if (mAttachInfo != null) {
10411            return mAttachInfo.mInTouchMode;
10412        } else {
10413            return ViewRootImpl.isInTouchMode();
10414        }
10415    }
10416
10417    /**
10418     * Returns the context the view is running in, through which it can
10419     * access the current theme, resources, etc.
10420     *
10421     * @return The view's Context.
10422     */
10423    @ViewDebug.CapturedViewProperty
10424    public final Context getContext() {
10425        return mContext;
10426    }
10427
10428    /**
10429     * Handle a key event before it is processed by any input method
10430     * associated with the view hierarchy.  This can be used to intercept
10431     * key events in special situations before the IME consumes them; a
10432     * typical example would be handling the BACK key to update the application's
10433     * UI instead of allowing the IME to see it and close itself.
10434     *
10435     * @param keyCode The value in event.getKeyCode().
10436     * @param event Description of the key event.
10437     * @return If you handled the event, return true. If you want to allow the
10438     *         event to be handled by the next receiver, return false.
10439     */
10440    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10441        return false;
10442    }
10443
10444    /**
10445     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10446     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10447     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10448     * is released, if the view is enabled and clickable.
10449     * <p>
10450     * Key presses in software keyboards will generally NOT trigger this
10451     * listener, although some may elect to do so in some situations. Do not
10452     * rely on this to catch software key presses.
10453     *
10454     * @param keyCode a key code that represents the button pressed, from
10455     *                {@link android.view.KeyEvent}
10456     * @param event the KeyEvent object that defines the button action
10457     */
10458    public boolean onKeyDown(int keyCode, KeyEvent event) {
10459        if (KeyEvent.isConfirmKey(keyCode)) {
10460            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10461                return true;
10462            }
10463
10464            // Long clickable items don't necessarily have to be clickable.
10465            if (((mViewFlags & CLICKABLE) == CLICKABLE
10466                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10467                    && (event.getRepeatCount() == 0)) {
10468                // For the purposes of menu anchoring and drawable hotspots,
10469                // key events are considered to be at the center of the view.
10470                final float x = getWidth() / 2f;
10471                final float y = getHeight() / 2f;
10472                setPressed(true, x, y);
10473                checkForLongClick(0, x, y);
10474                return true;
10475            }
10476        }
10477
10478        return false;
10479    }
10480
10481    /**
10482     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10483     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10484     * the event).
10485     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10486     * although some may elect to do so in some situations. Do not rely on this to
10487     * catch software key presses.
10488     */
10489    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10490        return false;
10491    }
10492
10493    /**
10494     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10495     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10496     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10497     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10498     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10499     * although some may elect to do so in some situations. Do not rely on this to
10500     * catch software key presses.
10501     *
10502     * @param keyCode A key code that represents the button pressed, from
10503     *                {@link android.view.KeyEvent}.
10504     * @param event   The KeyEvent object that defines the button action.
10505     */
10506    public boolean onKeyUp(int keyCode, KeyEvent event) {
10507        if (KeyEvent.isConfirmKey(keyCode)) {
10508            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10509                return true;
10510            }
10511            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10512                setPressed(false);
10513
10514                if (!mHasPerformedLongPress) {
10515                    // This is a tap, so remove the longpress check
10516                    removeLongPressCallback();
10517                    return performClick();
10518                }
10519            }
10520        }
10521        return false;
10522    }
10523
10524    /**
10525     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10526     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10527     * the event).
10528     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10529     * although some may elect to do so in some situations. Do not rely on this to
10530     * catch software key presses.
10531     *
10532     * @param keyCode     A key code that represents the button pressed, from
10533     *                    {@link android.view.KeyEvent}.
10534     * @param repeatCount The number of times the action was made.
10535     * @param event       The KeyEvent object that defines the button action.
10536     */
10537    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10538        return false;
10539    }
10540
10541    /**
10542     * Called on the focused view when a key shortcut event is not handled.
10543     * Override this method to implement local key shortcuts for the View.
10544     * Key shortcuts can also be implemented by setting the
10545     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10546     *
10547     * @param keyCode The value in event.getKeyCode().
10548     * @param event Description of the key event.
10549     * @return If you handled the event, return true. If you want to allow the
10550     *         event to be handled by the next receiver, return false.
10551     */
10552    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10553        return false;
10554    }
10555
10556    /**
10557     * Check whether the called view is a text editor, in which case it
10558     * would make sense to automatically display a soft input window for
10559     * it.  Subclasses should override this if they implement
10560     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10561     * a call on that method would return a non-null InputConnection, and
10562     * they are really a first-class editor that the user would normally
10563     * start typing on when the go into a window containing your view.
10564     *
10565     * <p>The default implementation always returns false.  This does
10566     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10567     * will not be called or the user can not otherwise perform edits on your
10568     * view; it is just a hint to the system that this is not the primary
10569     * purpose of this view.
10570     *
10571     * @return Returns true if this view is a text editor, else false.
10572     */
10573    public boolean onCheckIsTextEditor() {
10574        return false;
10575    }
10576
10577    /**
10578     * Create a new InputConnection for an InputMethod to interact
10579     * with the view.  The default implementation returns null, since it doesn't
10580     * support input methods.  You can override this to implement such support.
10581     * This is only needed for views that take focus and text input.
10582     *
10583     * <p>When implementing this, you probably also want to implement
10584     * {@link #onCheckIsTextEditor()} to indicate you will return a
10585     * non-null InputConnection.</p>
10586     *
10587     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10588     * object correctly and in its entirety, so that the connected IME can rely
10589     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10590     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10591     * must be filled in with the correct cursor position for IMEs to work correctly
10592     * with your application.</p>
10593     *
10594     * @param outAttrs Fill in with attribute information about the connection.
10595     */
10596    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10597        return null;
10598    }
10599
10600    /**
10601     * Called by the {@link android.view.inputmethod.InputMethodManager}
10602     * when a view who is not the current
10603     * input connection target is trying to make a call on the manager.  The
10604     * default implementation returns false; you can override this to return
10605     * true for certain views if you are performing InputConnection proxying
10606     * to them.
10607     * @param view The View that is making the InputMethodManager call.
10608     * @return Return true to allow the call, false to reject.
10609     */
10610    public boolean checkInputConnectionProxy(View view) {
10611        return false;
10612    }
10613
10614    /**
10615     * Show the context menu for this view. It is not safe to hold on to the
10616     * menu after returning from this method.
10617     *
10618     * You should normally not overload this method. Overload
10619     * {@link #onCreateContextMenu(ContextMenu)} or define an
10620     * {@link OnCreateContextMenuListener} to add items to the context menu.
10621     *
10622     * @param menu The context menu to populate
10623     */
10624    public void createContextMenu(ContextMenu menu) {
10625        ContextMenuInfo menuInfo = getContextMenuInfo();
10626
10627        // Sets the current menu info so all items added to menu will have
10628        // my extra info set.
10629        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10630
10631        onCreateContextMenu(menu);
10632        ListenerInfo li = mListenerInfo;
10633        if (li != null && li.mOnCreateContextMenuListener != null) {
10634            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10635        }
10636
10637        // Clear the extra information so subsequent items that aren't mine don't
10638        // have my extra info.
10639        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10640
10641        if (mParent != null) {
10642            mParent.createContextMenu(menu);
10643        }
10644    }
10645
10646    /**
10647     * Views should implement this if they have extra information to associate
10648     * with the context menu. The return result is supplied as a parameter to
10649     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10650     * callback.
10651     *
10652     * @return Extra information about the item for which the context menu
10653     *         should be shown. This information will vary across different
10654     *         subclasses of View.
10655     */
10656    protected ContextMenuInfo getContextMenuInfo() {
10657        return null;
10658    }
10659
10660    /**
10661     * Views should implement this if the view itself is going to add items to
10662     * the context menu.
10663     *
10664     * @param menu the context menu to populate
10665     */
10666    protected void onCreateContextMenu(ContextMenu menu) {
10667    }
10668
10669    /**
10670     * Implement this method to handle trackball motion events.  The
10671     * <em>relative</em> movement of the trackball since the last event
10672     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10673     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10674     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10675     * they will often be fractional values, representing the more fine-grained
10676     * movement information available from a trackball).
10677     *
10678     * @param event The motion event.
10679     * @return True if the event was handled, false otherwise.
10680     */
10681    public boolean onTrackballEvent(MotionEvent event) {
10682        return false;
10683    }
10684
10685    /**
10686     * Implement this method to handle generic motion events.
10687     * <p>
10688     * Generic motion events describe joystick movements, mouse hovers, track pad
10689     * touches, scroll wheel movements and other input events.  The
10690     * {@link MotionEvent#getSource() source} of the motion event specifies
10691     * the class of input that was received.  Implementations of this method
10692     * must examine the bits in the source before processing the event.
10693     * The following code example shows how this is done.
10694     * </p><p>
10695     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10696     * are delivered to the view under the pointer.  All other generic motion events are
10697     * delivered to the focused view.
10698     * </p>
10699     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10700     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10701     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10702     *             // process the joystick movement...
10703     *             return true;
10704     *         }
10705     *     }
10706     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10707     *         switch (event.getAction()) {
10708     *             case MotionEvent.ACTION_HOVER_MOVE:
10709     *                 // process the mouse hover movement...
10710     *                 return true;
10711     *             case MotionEvent.ACTION_SCROLL:
10712     *                 // process the scroll wheel movement...
10713     *                 return true;
10714     *         }
10715     *     }
10716     *     return super.onGenericMotionEvent(event);
10717     * }</pre>
10718     *
10719     * @param event The generic motion event being processed.
10720     * @return True if the event was handled, false otherwise.
10721     */
10722    public boolean onGenericMotionEvent(MotionEvent event) {
10723        return false;
10724    }
10725
10726    /**
10727     * Implement this method to handle hover events.
10728     * <p>
10729     * This method is called whenever a pointer is hovering into, over, or out of the
10730     * bounds of a view and the view is not currently being touched.
10731     * Hover events are represented as pointer events with action
10732     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10733     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10734     * </p>
10735     * <ul>
10736     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10737     * when the pointer enters the bounds of the view.</li>
10738     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10739     * when the pointer has already entered the bounds of the view and has moved.</li>
10740     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10741     * when the pointer has exited the bounds of the view or when the pointer is
10742     * about to go down due to a button click, tap, or similar user action that
10743     * causes the view to be touched.</li>
10744     * </ul>
10745     * <p>
10746     * The view should implement this method to return true to indicate that it is
10747     * handling the hover event, such as by changing its drawable state.
10748     * </p><p>
10749     * The default implementation calls {@link #setHovered} to update the hovered state
10750     * of the view when a hover enter or hover exit event is received, if the view
10751     * is enabled and is clickable.  The default implementation also sends hover
10752     * accessibility events.
10753     * </p>
10754     *
10755     * @param event The motion event that describes the hover.
10756     * @return True if the view handled the hover event.
10757     *
10758     * @see #isHovered
10759     * @see #setHovered
10760     * @see #onHoverChanged
10761     */
10762    public boolean onHoverEvent(MotionEvent event) {
10763        // The root view may receive hover (or touch) events that are outside the bounds of
10764        // the window.  This code ensures that we only send accessibility events for
10765        // hovers that are actually within the bounds of the root view.
10766        final int action = event.getActionMasked();
10767        if (!mSendingHoverAccessibilityEvents) {
10768            if ((action == MotionEvent.ACTION_HOVER_ENTER
10769                    || action == MotionEvent.ACTION_HOVER_MOVE)
10770                    && !hasHoveredChild()
10771                    && pointInView(event.getX(), event.getY())) {
10772                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10773                mSendingHoverAccessibilityEvents = true;
10774            }
10775        } else {
10776            if (action == MotionEvent.ACTION_HOVER_EXIT
10777                    || (action == MotionEvent.ACTION_MOVE
10778                            && !pointInView(event.getX(), event.getY()))) {
10779                mSendingHoverAccessibilityEvents = false;
10780                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10781            }
10782        }
10783
10784        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10785                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10786                && isOnScrollbar(event.getX(), event.getY())) {
10787            awakenScrollBars();
10788        }
10789        if (isHoverable()) {
10790            switch (action) {
10791                case MotionEvent.ACTION_HOVER_ENTER:
10792                    setHovered(true);
10793                    break;
10794                case MotionEvent.ACTION_HOVER_EXIT:
10795                    setHovered(false);
10796                    break;
10797            }
10798
10799            // Dispatch the event to onGenericMotionEvent before returning true.
10800            // This is to provide compatibility with existing applications that
10801            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10802            // break because of the new default handling for hoverable views
10803            // in onHoverEvent.
10804            // Note that onGenericMotionEvent will be called by default when
10805            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10806            dispatchGenericMotionEventInternal(event);
10807            // The event was already handled by calling setHovered(), so always
10808            // return true.
10809            return true;
10810        }
10811
10812        return false;
10813    }
10814
10815    /**
10816     * Returns true if the view should handle {@link #onHoverEvent}
10817     * by calling {@link #setHovered} to change its hovered state.
10818     *
10819     * @return True if the view is hoverable.
10820     */
10821    private boolean isHoverable() {
10822        final int viewFlags = mViewFlags;
10823        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10824            return false;
10825        }
10826
10827        return (viewFlags & CLICKABLE) == CLICKABLE
10828                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10829                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10830    }
10831
10832    /**
10833     * Returns true if the view is currently hovered.
10834     *
10835     * @return True if the view is currently hovered.
10836     *
10837     * @see #setHovered
10838     * @see #onHoverChanged
10839     */
10840    @ViewDebug.ExportedProperty
10841    public boolean isHovered() {
10842        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10843    }
10844
10845    /**
10846     * Sets whether the view is currently hovered.
10847     * <p>
10848     * Calling this method also changes the drawable state of the view.  This
10849     * enables the view to react to hover by using different drawable resources
10850     * to change its appearance.
10851     * </p><p>
10852     * The {@link #onHoverChanged} method is called when the hovered state changes.
10853     * </p>
10854     *
10855     * @param hovered True if the view is hovered.
10856     *
10857     * @see #isHovered
10858     * @see #onHoverChanged
10859     */
10860    public void setHovered(boolean hovered) {
10861        if (hovered) {
10862            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10863                mPrivateFlags |= PFLAG_HOVERED;
10864                refreshDrawableState();
10865                onHoverChanged(true);
10866            }
10867        } else {
10868            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10869                mPrivateFlags &= ~PFLAG_HOVERED;
10870                refreshDrawableState();
10871                onHoverChanged(false);
10872            }
10873        }
10874    }
10875
10876    /**
10877     * Implement this method to handle hover state changes.
10878     * <p>
10879     * This method is called whenever the hover state changes as a result of a
10880     * call to {@link #setHovered}.
10881     * </p>
10882     *
10883     * @param hovered The current hover state, as returned by {@link #isHovered}.
10884     *
10885     * @see #isHovered
10886     * @see #setHovered
10887     */
10888    public void onHoverChanged(boolean hovered) {
10889    }
10890
10891    /**
10892     * Handles scroll bar dragging by mouse input.
10893     *
10894     * @hide
10895     * @param event The motion event.
10896     *
10897     * @return true if the event was handled as a scroll bar dragging, false otherwise.
10898     */
10899    protected boolean handleScrollBarDragging(MotionEvent event) {
10900        if (mScrollCache == null) {
10901            return false;
10902        }
10903        final float x = event.getX();
10904        final float y = event.getY();
10905        final int action = event.getAction();
10906        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
10907                && action != MotionEvent.ACTION_DOWN)
10908                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
10909                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
10910            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10911            return false;
10912        }
10913
10914        switch (action) {
10915            case MotionEvent.ACTION_MOVE:
10916                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
10917                    return false;
10918                }
10919                if (mScrollCache.mScrollBarDraggingState
10920                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
10921                    final Rect bounds = mScrollCache.mScrollBarBounds;
10922                    getVerticalScrollBarBounds(bounds);
10923                    final int range = computeVerticalScrollRange();
10924                    final int offset = computeVerticalScrollOffset();
10925                    final int extent = computeVerticalScrollExtent();
10926
10927                    final int thumbLength = ScrollBarUtils.getThumbLength(
10928                            bounds.height(), bounds.width(), extent, range);
10929                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10930                            bounds.height(), thumbLength, extent, range, offset);
10931
10932                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
10933                    final float maxThumbOffset = bounds.height() - thumbLength;
10934                    final float newThumbOffset =
10935                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
10936                    final int height = getHeight();
10937                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
10938                            && height > 0 && extent > 0) {
10939                        final int newY = Math.round((range - extent)
10940                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
10941                        if (newY != getScrollY()) {
10942                            mScrollCache.mScrollBarDraggingPos = y;
10943                            setScrollY(newY);
10944                        }
10945                    }
10946                    return true;
10947                }
10948                if (mScrollCache.mScrollBarDraggingState
10949                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
10950                    final Rect bounds = mScrollCache.mScrollBarBounds;
10951                    getHorizontalScrollBarBounds(bounds);
10952                    final int range = computeHorizontalScrollRange();
10953                    final int offset = computeHorizontalScrollOffset();
10954                    final int extent = computeHorizontalScrollExtent();
10955
10956                    final int thumbLength = ScrollBarUtils.getThumbLength(
10957                            bounds.width(), bounds.height(), extent, range);
10958                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10959                            bounds.width(), thumbLength, extent, range, offset);
10960
10961                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
10962                    final float maxThumbOffset = bounds.width() - thumbLength;
10963                    final float newThumbOffset =
10964                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
10965                    final int width = getWidth();
10966                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
10967                            && width > 0 && extent > 0) {
10968                        final int newX = Math.round((range - extent)
10969                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
10970                        if (newX != getScrollX()) {
10971                            mScrollCache.mScrollBarDraggingPos = x;
10972                            setScrollX(newX);
10973                        }
10974                    }
10975                    return true;
10976                }
10977            case MotionEvent.ACTION_DOWN:
10978                if (mScrollCache.state == ScrollabilityCache.OFF) {
10979                    return false;
10980                }
10981                if (isOnVerticalScrollbarThumb(x, y)) {
10982                    mScrollCache.mScrollBarDraggingState =
10983                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
10984                    mScrollCache.mScrollBarDraggingPos = y;
10985                    return true;
10986                }
10987                if (isOnHorizontalScrollbarThumb(x, y)) {
10988                    mScrollCache.mScrollBarDraggingState =
10989                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
10990                    mScrollCache.mScrollBarDraggingPos = x;
10991                    return true;
10992                }
10993        }
10994        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10995        return false;
10996    }
10997
10998    /**
10999     * Implement this method to handle touch screen motion events.
11000     * <p>
11001     * If this method is used to detect click actions, it is recommended that
11002     * the actions be performed by implementing and calling
11003     * {@link #performClick()}. This will ensure consistent system behavior,
11004     * including:
11005     * <ul>
11006     * <li>obeying click sound preferences
11007     * <li>dispatching OnClickListener calls
11008     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11009     * accessibility features are enabled
11010     * </ul>
11011     *
11012     * @param event The motion event.
11013     * @return True if the event was handled, false otherwise.
11014     */
11015    public boolean onTouchEvent(MotionEvent event) {
11016        final float x = event.getX();
11017        final float y = event.getY();
11018        final int viewFlags = mViewFlags;
11019        final int action = event.getAction();
11020
11021        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11022            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11023                setPressed(false);
11024            }
11025            // A disabled view that is clickable still consumes the touch
11026            // events, it just doesn't respond to them.
11027            return (((viewFlags & CLICKABLE) == CLICKABLE
11028                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11029                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11030        }
11031        if (mTouchDelegate != null) {
11032            if (mTouchDelegate.onTouchEvent(event)) {
11033                return true;
11034            }
11035        }
11036
11037        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11038                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11039                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11040            switch (action) {
11041                case MotionEvent.ACTION_UP:
11042                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11043                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11044                        // take focus if we don't have it already and we should in
11045                        // touch mode.
11046                        boolean focusTaken = false;
11047                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11048                            focusTaken = requestFocus();
11049                        }
11050
11051                        if (prepressed) {
11052                            // The button is being released before we actually
11053                            // showed it as pressed.  Make it show the pressed
11054                            // state now (before scheduling the click) to ensure
11055                            // the user sees it.
11056                            setPressed(true, x, y);
11057                       }
11058
11059                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11060                            // This is a tap, so remove the longpress check
11061                            removeLongPressCallback();
11062
11063                            // Only perform take click actions if we were in the pressed state
11064                            if (!focusTaken) {
11065                                // Use a Runnable and post this rather than calling
11066                                // performClick directly. This lets other visual state
11067                                // of the view update before click actions start.
11068                                if (mPerformClick == null) {
11069                                    mPerformClick = new PerformClick();
11070                                }
11071                                if (!post(mPerformClick)) {
11072                                    performClick();
11073                                }
11074                            }
11075                        }
11076
11077                        if (mUnsetPressedState == null) {
11078                            mUnsetPressedState = new UnsetPressedState();
11079                        }
11080
11081                        if (prepressed) {
11082                            postDelayed(mUnsetPressedState,
11083                                    ViewConfiguration.getPressedStateDuration());
11084                        } else if (!post(mUnsetPressedState)) {
11085                            // If the post failed, unpress right now
11086                            mUnsetPressedState.run();
11087                        }
11088
11089                        removeTapCallback();
11090                    }
11091                    mIgnoreNextUpEvent = false;
11092                    break;
11093
11094                case MotionEvent.ACTION_DOWN:
11095                    mHasPerformedLongPress = false;
11096
11097                    if (performButtonActionOnTouchDown(event)) {
11098                        break;
11099                    }
11100
11101                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11102                    boolean isInScrollingContainer = isInScrollingContainer();
11103
11104                    // For views inside a scrolling container, delay the pressed feedback for
11105                    // a short period in case this is a scroll.
11106                    if (isInScrollingContainer) {
11107                        mPrivateFlags |= PFLAG_PREPRESSED;
11108                        if (mPendingCheckForTap == null) {
11109                            mPendingCheckForTap = new CheckForTap();
11110                        }
11111                        mPendingCheckForTap.x = event.getX();
11112                        mPendingCheckForTap.y = event.getY();
11113                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11114                    } else {
11115                        // Not inside a scrolling container, so show the feedback right away
11116                        setPressed(true, x, y);
11117                        checkForLongClick(0, x, y);
11118                    }
11119                    break;
11120
11121                case MotionEvent.ACTION_CANCEL:
11122                    setPressed(false);
11123                    removeTapCallback();
11124                    removeLongPressCallback();
11125                    mInContextButtonPress = false;
11126                    mHasPerformedLongPress = false;
11127                    mIgnoreNextUpEvent = false;
11128                    break;
11129
11130                case MotionEvent.ACTION_MOVE:
11131                    drawableHotspotChanged(x, y);
11132
11133                    // Be lenient about moving outside of buttons
11134                    if (!pointInView(x, y, mTouchSlop)) {
11135                        // Outside button
11136                        removeTapCallback();
11137                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11138                            // Remove any future long press/tap checks
11139                            removeLongPressCallback();
11140
11141                            setPressed(false);
11142                        }
11143                    }
11144                    break;
11145            }
11146
11147            return true;
11148        }
11149
11150        return false;
11151    }
11152
11153    /**
11154     * @hide
11155     */
11156    public boolean isInScrollingContainer() {
11157        ViewParent p = getParent();
11158        while (p != null && p instanceof ViewGroup) {
11159            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11160                return true;
11161            }
11162            p = p.getParent();
11163        }
11164        return false;
11165    }
11166
11167    /**
11168     * Remove the longpress detection timer.
11169     */
11170    private void removeLongPressCallback() {
11171        if (mPendingCheckForLongPress != null) {
11172          removeCallbacks(mPendingCheckForLongPress);
11173        }
11174    }
11175
11176    /**
11177     * Remove the pending click action
11178     */
11179    private void removePerformClickCallback() {
11180        if (mPerformClick != null) {
11181            removeCallbacks(mPerformClick);
11182        }
11183    }
11184
11185    /**
11186     * Remove the prepress detection timer.
11187     */
11188    private void removeUnsetPressCallback() {
11189        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11190            setPressed(false);
11191            removeCallbacks(mUnsetPressedState);
11192        }
11193    }
11194
11195    /**
11196     * Remove the tap detection timer.
11197     */
11198    private void removeTapCallback() {
11199        if (mPendingCheckForTap != null) {
11200            mPrivateFlags &= ~PFLAG_PREPRESSED;
11201            removeCallbacks(mPendingCheckForTap);
11202        }
11203    }
11204
11205    /**
11206     * Cancels a pending long press.  Your subclass can use this if you
11207     * want the context menu to come up if the user presses and holds
11208     * at the same place, but you don't want it to come up if they press
11209     * and then move around enough to cause scrolling.
11210     */
11211    public void cancelLongPress() {
11212        removeLongPressCallback();
11213
11214        /*
11215         * The prepressed state handled by the tap callback is a display
11216         * construct, but the tap callback will post a long press callback
11217         * less its own timeout. Remove it here.
11218         */
11219        removeTapCallback();
11220    }
11221
11222    /**
11223     * Remove the pending callback for sending a
11224     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11225     */
11226    private void removeSendViewScrolledAccessibilityEventCallback() {
11227        if (mSendViewScrolledAccessibilityEvent != null) {
11228            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11229            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11230        }
11231    }
11232
11233    /**
11234     * Sets the TouchDelegate for this View.
11235     */
11236    public void setTouchDelegate(TouchDelegate delegate) {
11237        mTouchDelegate = delegate;
11238    }
11239
11240    /**
11241     * Gets the TouchDelegate for this View.
11242     */
11243    public TouchDelegate getTouchDelegate() {
11244        return mTouchDelegate;
11245    }
11246
11247    /**
11248     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11249     *
11250     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11251     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11252     * available. This method should only be called for touch events.
11253     *
11254     * <p class="note">This api is not intended for most applications. Buffered dispatch
11255     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11256     * streams will not improve your input latency. Side effects include: increased latency,
11257     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11258     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11259     * you.</p>
11260     */
11261    public final void requestUnbufferedDispatch(MotionEvent event) {
11262        final int action = event.getAction();
11263        if (mAttachInfo == null
11264                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11265                || !event.isTouchEvent()) {
11266            return;
11267        }
11268        mAttachInfo.mUnbufferedDispatchRequested = true;
11269    }
11270
11271    /**
11272     * Set flags controlling behavior of this view.
11273     *
11274     * @param flags Constant indicating the value which should be set
11275     * @param mask Constant indicating the bit range that should be changed
11276     */
11277    void setFlags(int flags, int mask) {
11278        final boolean accessibilityEnabled =
11279                AccessibilityManager.getInstance(mContext).isEnabled();
11280        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11281
11282        int old = mViewFlags;
11283        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11284
11285        int changed = mViewFlags ^ old;
11286        if (changed == 0) {
11287            return;
11288        }
11289        int privateFlags = mPrivateFlags;
11290
11291        /* Check if the FOCUSABLE bit has changed */
11292        if (((changed & FOCUSABLE_MASK) != 0) &&
11293                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11294            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11295                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11296                /* Give up focus if we are no longer focusable */
11297                clearFocus();
11298            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11299                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11300                /*
11301                 * Tell the view system that we are now available to take focus
11302                 * if no one else already has it.
11303                 */
11304                if (mParent != null) mParent.focusableViewAvailable(this);
11305            }
11306        }
11307
11308        final int newVisibility = flags & VISIBILITY_MASK;
11309        if (newVisibility == VISIBLE) {
11310            if ((changed & VISIBILITY_MASK) != 0) {
11311                /*
11312                 * If this view is becoming visible, invalidate it in case it changed while
11313                 * it was not visible. Marking it drawn ensures that the invalidation will
11314                 * go through.
11315                 */
11316                mPrivateFlags |= PFLAG_DRAWN;
11317                invalidate(true);
11318
11319                needGlobalAttributesUpdate(true);
11320
11321                // a view becoming visible is worth notifying the parent
11322                // about in case nothing has focus.  even if this specific view
11323                // isn't focusable, it may contain something that is, so let
11324                // the root view try to give this focus if nothing else does.
11325                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11326                    mParent.focusableViewAvailable(this);
11327                }
11328            }
11329        }
11330
11331        /* Check if the GONE bit has changed */
11332        if ((changed & GONE) != 0) {
11333            needGlobalAttributesUpdate(false);
11334            requestLayout();
11335
11336            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11337                if (hasFocus()) clearFocus();
11338                clearAccessibilityFocus();
11339                destroyDrawingCache();
11340                if (mParent instanceof View) {
11341                    // GONE views noop invalidation, so invalidate the parent
11342                    ((View) mParent).invalidate(true);
11343                }
11344                // Mark the view drawn to ensure that it gets invalidated properly the next
11345                // time it is visible and gets invalidated
11346                mPrivateFlags |= PFLAG_DRAWN;
11347            }
11348            if (mAttachInfo != null) {
11349                mAttachInfo.mViewVisibilityChanged = true;
11350            }
11351        }
11352
11353        /* Check if the VISIBLE bit has changed */
11354        if ((changed & INVISIBLE) != 0) {
11355            needGlobalAttributesUpdate(false);
11356            /*
11357             * If this view is becoming invisible, set the DRAWN flag so that
11358             * the next invalidate() will not be skipped.
11359             */
11360            mPrivateFlags |= PFLAG_DRAWN;
11361
11362            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11363                // root view becoming invisible shouldn't clear focus and accessibility focus
11364                if (getRootView() != this) {
11365                    if (hasFocus()) clearFocus();
11366                    clearAccessibilityFocus();
11367                }
11368            }
11369            if (mAttachInfo != null) {
11370                mAttachInfo.mViewVisibilityChanged = true;
11371            }
11372        }
11373
11374        if ((changed & VISIBILITY_MASK) != 0) {
11375            // If the view is invisible, cleanup its display list to free up resources
11376            if (newVisibility != VISIBLE && mAttachInfo != null) {
11377                cleanupDraw();
11378            }
11379
11380            if (mParent instanceof ViewGroup) {
11381                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11382                        (changed & VISIBILITY_MASK), newVisibility);
11383                ((View) mParent).invalidate(true);
11384            } else if (mParent != null) {
11385                mParent.invalidateChild(this, null);
11386            }
11387
11388            if (mAttachInfo != null) {
11389                dispatchVisibilityChanged(this, newVisibility);
11390
11391                // Aggregated visibility changes are dispatched to attached views
11392                // in visible windows where the parent is currently shown/drawn
11393                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11394                // discounting clipping or overlapping. This makes it a good place
11395                // to change animation states.
11396                if (mParent != null && getWindowVisibility() == VISIBLE &&
11397                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11398                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11399                }
11400                notifySubtreeAccessibilityStateChangedIfNeeded();
11401            }
11402        }
11403
11404        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11405            destroyDrawingCache();
11406        }
11407
11408        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11409            destroyDrawingCache();
11410            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11411            invalidateParentCaches();
11412        }
11413
11414        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11415            destroyDrawingCache();
11416            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11417        }
11418
11419        if ((changed & DRAW_MASK) != 0) {
11420            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11421                if (mBackground != null
11422                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11423                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11424                } else {
11425                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11426                }
11427            } else {
11428                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11429            }
11430            requestLayout();
11431            invalidate(true);
11432        }
11433
11434        if ((changed & KEEP_SCREEN_ON) != 0) {
11435            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11436                mParent.recomputeViewAttributes(this);
11437            }
11438        }
11439
11440        if (accessibilityEnabled) {
11441            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11442                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11443                    || (changed & CONTEXT_CLICKABLE) != 0) {
11444                if (oldIncludeForAccessibility != includeForAccessibility()) {
11445                    notifySubtreeAccessibilityStateChangedIfNeeded();
11446                } else {
11447                    notifyViewAccessibilityStateChangedIfNeeded(
11448                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11449                }
11450            } else if ((changed & ENABLED_MASK) != 0) {
11451                notifyViewAccessibilityStateChangedIfNeeded(
11452                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11453            }
11454        }
11455    }
11456
11457    /**
11458     * Change the view's z order in the tree, so it's on top of other sibling
11459     * views. This ordering change may affect layout, if the parent container
11460     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11461     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11462     * method should be followed by calls to {@link #requestLayout()} and
11463     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11464     * with the new child ordering.
11465     *
11466     * @see ViewGroup#bringChildToFront(View)
11467     */
11468    public void bringToFront() {
11469        if (mParent != null) {
11470            mParent.bringChildToFront(this);
11471        }
11472    }
11473
11474    /**
11475     * This is called in response to an internal scroll in this view (i.e., the
11476     * view scrolled its own contents). This is typically as a result of
11477     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11478     * called.
11479     *
11480     * @param l Current horizontal scroll origin.
11481     * @param t Current vertical scroll origin.
11482     * @param oldl Previous horizontal scroll origin.
11483     * @param oldt Previous vertical scroll origin.
11484     */
11485    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11486        notifySubtreeAccessibilityStateChangedIfNeeded();
11487
11488        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11489            postSendViewScrolledAccessibilityEventCallback();
11490        }
11491
11492        mBackgroundSizeChanged = true;
11493        if (mForegroundInfo != null) {
11494            mForegroundInfo.mBoundsChanged = true;
11495        }
11496
11497        final AttachInfo ai = mAttachInfo;
11498        if (ai != null) {
11499            ai.mViewScrollChanged = true;
11500        }
11501
11502        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11503            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11504        }
11505    }
11506
11507    /**
11508     * Interface definition for a callback to be invoked when the scroll
11509     * X or Y positions of a view change.
11510     * <p>
11511     * <b>Note:</b> Some views handle scrolling independently from View and may
11512     * have their own separate listeners for scroll-type events. For example,
11513     * {@link android.widget.ListView ListView} allows clients to register an
11514     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11515     * to listen for changes in list scroll position.
11516     *
11517     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11518     */
11519    public interface OnScrollChangeListener {
11520        /**
11521         * Called when the scroll position of a view changes.
11522         *
11523         * @param v The view whose scroll position has changed.
11524         * @param scrollX Current horizontal scroll origin.
11525         * @param scrollY Current vertical scroll origin.
11526         * @param oldScrollX Previous horizontal scroll origin.
11527         * @param oldScrollY Previous vertical scroll origin.
11528         */
11529        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11530    }
11531
11532    /**
11533     * Interface definition for a callback to be invoked when the layout bounds of a view
11534     * changes due to layout processing.
11535     */
11536    public interface OnLayoutChangeListener {
11537        /**
11538         * Called when the layout bounds of a view changes due to layout processing.
11539         *
11540         * @param v The view whose bounds have changed.
11541         * @param left The new value of the view's left property.
11542         * @param top The new value of the view's top property.
11543         * @param right The new value of the view's right property.
11544         * @param bottom The new value of the view's bottom property.
11545         * @param oldLeft The previous value of the view's left property.
11546         * @param oldTop The previous value of the view's top property.
11547         * @param oldRight The previous value of the view's right property.
11548         * @param oldBottom The previous value of the view's bottom property.
11549         */
11550        void onLayoutChange(View v, int left, int top, int right, int bottom,
11551            int oldLeft, int oldTop, int oldRight, int oldBottom);
11552    }
11553
11554    /**
11555     * This is called during layout when the size of this view has changed. If
11556     * you were just added to the view hierarchy, you're called with the old
11557     * values of 0.
11558     *
11559     * @param w Current width of this view.
11560     * @param h Current height of this view.
11561     * @param oldw Old width of this view.
11562     * @param oldh Old height of this view.
11563     */
11564    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11565    }
11566
11567    /**
11568     * Called by draw to draw the child views. This may be overridden
11569     * by derived classes to gain control just before its children are drawn
11570     * (but after its own view has been drawn).
11571     * @param canvas the canvas on which to draw the view
11572     */
11573    protected void dispatchDraw(Canvas canvas) {
11574
11575    }
11576
11577    /**
11578     * Gets the parent of this view. Note that the parent is a
11579     * ViewParent and not necessarily a View.
11580     *
11581     * @return Parent of this view.
11582     */
11583    public final ViewParent getParent() {
11584        return mParent;
11585    }
11586
11587    /**
11588     * Set the horizontal scrolled position of your view. This will cause a call to
11589     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11590     * invalidated.
11591     * @param value the x position to scroll to
11592     */
11593    public void setScrollX(int value) {
11594        scrollTo(value, mScrollY);
11595    }
11596
11597    /**
11598     * Set the vertical scrolled position of your view. This will cause a call to
11599     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11600     * invalidated.
11601     * @param value the y position to scroll to
11602     */
11603    public void setScrollY(int value) {
11604        scrollTo(mScrollX, value);
11605    }
11606
11607    /**
11608     * Return the scrolled left position of this view. This is the left edge of
11609     * the displayed part of your view. You do not need to draw any pixels
11610     * farther left, since those are outside of the frame of your view on
11611     * screen.
11612     *
11613     * @return The left edge of the displayed part of your view, in pixels.
11614     */
11615    public final int getScrollX() {
11616        return mScrollX;
11617    }
11618
11619    /**
11620     * Return the scrolled top position of this view. This is the top edge of
11621     * the displayed part of your view. You do not need to draw any pixels above
11622     * it, since those are outside of the frame of your view on screen.
11623     *
11624     * @return The top edge of the displayed part of your view, in pixels.
11625     */
11626    public final int getScrollY() {
11627        return mScrollY;
11628    }
11629
11630    /**
11631     * Return the width of the your view.
11632     *
11633     * @return The width of your view, in pixels.
11634     */
11635    @ViewDebug.ExportedProperty(category = "layout")
11636    public final int getWidth() {
11637        return mRight - mLeft;
11638    }
11639
11640    /**
11641     * Return the height of your view.
11642     *
11643     * @return The height of your view, in pixels.
11644     */
11645    @ViewDebug.ExportedProperty(category = "layout")
11646    public final int getHeight() {
11647        return mBottom - mTop;
11648    }
11649
11650    /**
11651     * Return the visible drawing bounds of your view. Fills in the output
11652     * rectangle with the values from getScrollX(), getScrollY(),
11653     * getWidth(), and getHeight(). These bounds do not account for any
11654     * transformation properties currently set on the view, such as
11655     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11656     *
11657     * @param outRect The (scrolled) drawing bounds of the view.
11658     */
11659    public void getDrawingRect(Rect outRect) {
11660        outRect.left = mScrollX;
11661        outRect.top = mScrollY;
11662        outRect.right = mScrollX + (mRight - mLeft);
11663        outRect.bottom = mScrollY + (mBottom - mTop);
11664    }
11665
11666    /**
11667     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11668     * raw width component (that is the result is masked by
11669     * {@link #MEASURED_SIZE_MASK}).
11670     *
11671     * @return The raw measured width of this view.
11672     */
11673    public final int getMeasuredWidth() {
11674        return mMeasuredWidth & MEASURED_SIZE_MASK;
11675    }
11676
11677    /**
11678     * Return the full width measurement information for this view as computed
11679     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11680     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11681     * This should be used during measurement and layout calculations only. Use
11682     * {@link #getWidth()} to see how wide a view is after layout.
11683     *
11684     * @return The measured width of this view as a bit mask.
11685     */
11686    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11687            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11688                    name = "MEASURED_STATE_TOO_SMALL"),
11689    })
11690    public final int getMeasuredWidthAndState() {
11691        return mMeasuredWidth;
11692    }
11693
11694    /**
11695     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11696     * raw width component (that is the result is masked by
11697     * {@link #MEASURED_SIZE_MASK}).
11698     *
11699     * @return The raw measured height of this view.
11700     */
11701    public final int getMeasuredHeight() {
11702        return mMeasuredHeight & MEASURED_SIZE_MASK;
11703    }
11704
11705    /**
11706     * Return the full height measurement information for this view as computed
11707     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11708     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11709     * This should be used during measurement and layout calculations only. Use
11710     * {@link #getHeight()} to see how wide a view is after layout.
11711     *
11712     * @return The measured width of this view as a bit mask.
11713     */
11714    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11715            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11716                    name = "MEASURED_STATE_TOO_SMALL"),
11717    })
11718    public final int getMeasuredHeightAndState() {
11719        return mMeasuredHeight;
11720    }
11721
11722    /**
11723     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11724     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11725     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11726     * and the height component is at the shifted bits
11727     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11728     */
11729    public final int getMeasuredState() {
11730        return (mMeasuredWidth&MEASURED_STATE_MASK)
11731                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11732                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11733    }
11734
11735    /**
11736     * The transform matrix of this view, which is calculated based on the current
11737     * rotation, scale, and pivot properties.
11738     *
11739     * @see #getRotation()
11740     * @see #getScaleX()
11741     * @see #getScaleY()
11742     * @see #getPivotX()
11743     * @see #getPivotY()
11744     * @return The current transform matrix for the view
11745     */
11746    public Matrix getMatrix() {
11747        ensureTransformationInfo();
11748        final Matrix matrix = mTransformationInfo.mMatrix;
11749        mRenderNode.getMatrix(matrix);
11750        return matrix;
11751    }
11752
11753    /**
11754     * Returns true if the transform matrix is the identity matrix.
11755     * Recomputes the matrix if necessary.
11756     *
11757     * @return True if the transform matrix is the identity matrix, false otherwise.
11758     */
11759    final boolean hasIdentityMatrix() {
11760        return mRenderNode.hasIdentityMatrix();
11761    }
11762
11763    void ensureTransformationInfo() {
11764        if (mTransformationInfo == null) {
11765            mTransformationInfo = new TransformationInfo();
11766        }
11767    }
11768
11769    /**
11770     * Utility method to retrieve the inverse of the current mMatrix property.
11771     * We cache the matrix to avoid recalculating it when transform properties
11772     * have not changed.
11773     *
11774     * @return The inverse of the current matrix of this view.
11775     * @hide
11776     */
11777    public final Matrix getInverseMatrix() {
11778        ensureTransformationInfo();
11779        if (mTransformationInfo.mInverseMatrix == null) {
11780            mTransformationInfo.mInverseMatrix = new Matrix();
11781        }
11782        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11783        mRenderNode.getInverseMatrix(matrix);
11784        return matrix;
11785    }
11786
11787    /**
11788     * Gets the distance along the Z axis from the camera to this view.
11789     *
11790     * @see #setCameraDistance(float)
11791     *
11792     * @return The distance along the Z axis.
11793     */
11794    public float getCameraDistance() {
11795        final float dpi = mResources.getDisplayMetrics().densityDpi;
11796        return -(mRenderNode.getCameraDistance() * dpi);
11797    }
11798
11799    /**
11800     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11801     * views are drawn) from the camera to this view. The camera's distance
11802     * affects 3D transformations, for instance rotations around the X and Y
11803     * axis. If the rotationX or rotationY properties are changed and this view is
11804     * large (more than half the size of the screen), it is recommended to always
11805     * use a camera distance that's greater than the height (X axis rotation) or
11806     * the width (Y axis rotation) of this view.</p>
11807     *
11808     * <p>The distance of the camera from the view plane can have an affect on the
11809     * perspective distortion of the view when it is rotated around the x or y axis.
11810     * For example, a large distance will result in a large viewing angle, and there
11811     * will not be much perspective distortion of the view as it rotates. A short
11812     * distance may cause much more perspective distortion upon rotation, and can
11813     * also result in some drawing artifacts if the rotated view ends up partially
11814     * behind the camera (which is why the recommendation is to use a distance at
11815     * least as far as the size of the view, if the view is to be rotated.)</p>
11816     *
11817     * <p>The distance is expressed in "depth pixels." The default distance depends
11818     * on the screen density. For instance, on a medium density display, the
11819     * default distance is 1280. On a high density display, the default distance
11820     * is 1920.</p>
11821     *
11822     * <p>If you want to specify a distance that leads to visually consistent
11823     * results across various densities, use the following formula:</p>
11824     * <pre>
11825     * float scale = context.getResources().getDisplayMetrics().density;
11826     * view.setCameraDistance(distance * scale);
11827     * </pre>
11828     *
11829     * <p>The density scale factor of a high density display is 1.5,
11830     * and 1920 = 1280 * 1.5.</p>
11831     *
11832     * @param distance The distance in "depth pixels", if negative the opposite
11833     *        value is used
11834     *
11835     * @see #setRotationX(float)
11836     * @see #setRotationY(float)
11837     */
11838    public void setCameraDistance(float distance) {
11839        final float dpi = mResources.getDisplayMetrics().densityDpi;
11840
11841        invalidateViewProperty(true, false);
11842        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11843        invalidateViewProperty(false, false);
11844
11845        invalidateParentIfNeededAndWasQuickRejected();
11846    }
11847
11848    /**
11849     * The degrees that the view is rotated around the pivot point.
11850     *
11851     * @see #setRotation(float)
11852     * @see #getPivotX()
11853     * @see #getPivotY()
11854     *
11855     * @return The degrees of rotation.
11856     */
11857    @ViewDebug.ExportedProperty(category = "drawing")
11858    public float getRotation() {
11859        return mRenderNode.getRotation();
11860    }
11861
11862    /**
11863     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11864     * result in clockwise rotation.
11865     *
11866     * @param rotation The degrees of rotation.
11867     *
11868     * @see #getRotation()
11869     * @see #getPivotX()
11870     * @see #getPivotY()
11871     * @see #setRotationX(float)
11872     * @see #setRotationY(float)
11873     *
11874     * @attr ref android.R.styleable#View_rotation
11875     */
11876    public void setRotation(float rotation) {
11877        if (rotation != getRotation()) {
11878            // Double-invalidation is necessary to capture view's old and new areas
11879            invalidateViewProperty(true, false);
11880            mRenderNode.setRotation(rotation);
11881            invalidateViewProperty(false, true);
11882
11883            invalidateParentIfNeededAndWasQuickRejected();
11884            notifySubtreeAccessibilityStateChangedIfNeeded();
11885        }
11886    }
11887
11888    /**
11889     * The degrees that the view is rotated around the vertical axis through the pivot point.
11890     *
11891     * @see #getPivotX()
11892     * @see #getPivotY()
11893     * @see #setRotationY(float)
11894     *
11895     * @return The degrees of Y rotation.
11896     */
11897    @ViewDebug.ExportedProperty(category = "drawing")
11898    public float getRotationY() {
11899        return mRenderNode.getRotationY();
11900    }
11901
11902    /**
11903     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11904     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11905     * down the y axis.
11906     *
11907     * When rotating large views, it is recommended to adjust the camera distance
11908     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11909     *
11910     * @param rotationY The degrees of Y rotation.
11911     *
11912     * @see #getRotationY()
11913     * @see #getPivotX()
11914     * @see #getPivotY()
11915     * @see #setRotation(float)
11916     * @see #setRotationX(float)
11917     * @see #setCameraDistance(float)
11918     *
11919     * @attr ref android.R.styleable#View_rotationY
11920     */
11921    public void setRotationY(float rotationY) {
11922        if (rotationY != getRotationY()) {
11923            invalidateViewProperty(true, false);
11924            mRenderNode.setRotationY(rotationY);
11925            invalidateViewProperty(false, true);
11926
11927            invalidateParentIfNeededAndWasQuickRejected();
11928            notifySubtreeAccessibilityStateChangedIfNeeded();
11929        }
11930    }
11931
11932    /**
11933     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11934     *
11935     * @see #getPivotX()
11936     * @see #getPivotY()
11937     * @see #setRotationX(float)
11938     *
11939     * @return The degrees of X rotation.
11940     */
11941    @ViewDebug.ExportedProperty(category = "drawing")
11942    public float getRotationX() {
11943        return mRenderNode.getRotationX();
11944    }
11945
11946    /**
11947     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
11948     * Increasing values result in clockwise rotation from the viewpoint of looking down the
11949     * x axis.
11950     *
11951     * When rotating large views, it is recommended to adjust the camera distance
11952     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11953     *
11954     * @param rotationX The degrees of X rotation.
11955     *
11956     * @see #getRotationX()
11957     * @see #getPivotX()
11958     * @see #getPivotY()
11959     * @see #setRotation(float)
11960     * @see #setRotationY(float)
11961     * @see #setCameraDistance(float)
11962     *
11963     * @attr ref android.R.styleable#View_rotationX
11964     */
11965    public void setRotationX(float rotationX) {
11966        if (rotationX != getRotationX()) {
11967            invalidateViewProperty(true, false);
11968            mRenderNode.setRotationX(rotationX);
11969            invalidateViewProperty(false, true);
11970
11971            invalidateParentIfNeededAndWasQuickRejected();
11972            notifySubtreeAccessibilityStateChangedIfNeeded();
11973        }
11974    }
11975
11976    /**
11977     * The amount that the view is scaled in x around the pivot point, as a proportion of
11978     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
11979     *
11980     * <p>By default, this is 1.0f.
11981     *
11982     * @see #getPivotX()
11983     * @see #getPivotY()
11984     * @return The scaling factor.
11985     */
11986    @ViewDebug.ExportedProperty(category = "drawing")
11987    public float getScaleX() {
11988        return mRenderNode.getScaleX();
11989    }
11990
11991    /**
11992     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
11993     * the view's unscaled width. A value of 1 means that no scaling is applied.
11994     *
11995     * @param scaleX The scaling factor.
11996     * @see #getPivotX()
11997     * @see #getPivotY()
11998     *
11999     * @attr ref android.R.styleable#View_scaleX
12000     */
12001    public void setScaleX(float scaleX) {
12002        if (scaleX != getScaleX()) {
12003            invalidateViewProperty(true, false);
12004            mRenderNode.setScaleX(scaleX);
12005            invalidateViewProperty(false, true);
12006
12007            invalidateParentIfNeededAndWasQuickRejected();
12008            notifySubtreeAccessibilityStateChangedIfNeeded();
12009        }
12010    }
12011
12012    /**
12013     * The amount that the view is scaled in y around the pivot point, as a proportion of
12014     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12015     *
12016     * <p>By default, this is 1.0f.
12017     *
12018     * @see #getPivotX()
12019     * @see #getPivotY()
12020     * @return The scaling factor.
12021     */
12022    @ViewDebug.ExportedProperty(category = "drawing")
12023    public float getScaleY() {
12024        return mRenderNode.getScaleY();
12025    }
12026
12027    /**
12028     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12029     * the view's unscaled width. A value of 1 means that no scaling is applied.
12030     *
12031     * @param scaleY The scaling factor.
12032     * @see #getPivotX()
12033     * @see #getPivotY()
12034     *
12035     * @attr ref android.R.styleable#View_scaleY
12036     */
12037    public void setScaleY(float scaleY) {
12038        if (scaleY != getScaleY()) {
12039            invalidateViewProperty(true, false);
12040            mRenderNode.setScaleY(scaleY);
12041            invalidateViewProperty(false, true);
12042
12043            invalidateParentIfNeededAndWasQuickRejected();
12044            notifySubtreeAccessibilityStateChangedIfNeeded();
12045        }
12046    }
12047
12048    /**
12049     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12050     * and {@link #setScaleX(float) scaled}.
12051     *
12052     * @see #getRotation()
12053     * @see #getScaleX()
12054     * @see #getScaleY()
12055     * @see #getPivotY()
12056     * @return The x location of the pivot point.
12057     *
12058     * @attr ref android.R.styleable#View_transformPivotX
12059     */
12060    @ViewDebug.ExportedProperty(category = "drawing")
12061    public float getPivotX() {
12062        return mRenderNode.getPivotX();
12063    }
12064
12065    /**
12066     * Sets the x location of the point around which the view is
12067     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12068     * By default, the pivot point is centered on the object.
12069     * Setting this property disables this behavior and causes the view to use only the
12070     * explicitly set pivotX and pivotY values.
12071     *
12072     * @param pivotX The x location of the pivot point.
12073     * @see #getRotation()
12074     * @see #getScaleX()
12075     * @see #getScaleY()
12076     * @see #getPivotY()
12077     *
12078     * @attr ref android.R.styleable#View_transformPivotX
12079     */
12080    public void setPivotX(float pivotX) {
12081        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12082            invalidateViewProperty(true, false);
12083            mRenderNode.setPivotX(pivotX);
12084            invalidateViewProperty(false, true);
12085
12086            invalidateParentIfNeededAndWasQuickRejected();
12087        }
12088    }
12089
12090    /**
12091     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12092     * and {@link #setScaleY(float) scaled}.
12093     *
12094     * @see #getRotation()
12095     * @see #getScaleX()
12096     * @see #getScaleY()
12097     * @see #getPivotY()
12098     * @return The y location of the pivot point.
12099     *
12100     * @attr ref android.R.styleable#View_transformPivotY
12101     */
12102    @ViewDebug.ExportedProperty(category = "drawing")
12103    public float getPivotY() {
12104        return mRenderNode.getPivotY();
12105    }
12106
12107    /**
12108     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12109     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12110     * Setting this property disables this behavior and causes the view to use only the
12111     * explicitly set pivotX and pivotY values.
12112     *
12113     * @param pivotY The y location of the pivot point.
12114     * @see #getRotation()
12115     * @see #getScaleX()
12116     * @see #getScaleY()
12117     * @see #getPivotY()
12118     *
12119     * @attr ref android.R.styleable#View_transformPivotY
12120     */
12121    public void setPivotY(float pivotY) {
12122        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12123            invalidateViewProperty(true, false);
12124            mRenderNode.setPivotY(pivotY);
12125            invalidateViewProperty(false, true);
12126
12127            invalidateParentIfNeededAndWasQuickRejected();
12128        }
12129    }
12130
12131    /**
12132     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12133     * completely transparent and 1 means the view is completely opaque.
12134     *
12135     * <p>By default this is 1.0f.
12136     * @return The opacity of the view.
12137     */
12138    @ViewDebug.ExportedProperty(category = "drawing")
12139    public float getAlpha() {
12140        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12141    }
12142
12143    /**
12144     * Sets the behavior for overlapping rendering for this view (see {@link
12145     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12146     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12147     * providing the value which is then used internally. That is, when {@link
12148     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12149     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12150     * instead.
12151     *
12152     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12153     * instead of that returned by {@link #hasOverlappingRendering()}.
12154     *
12155     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12156     */
12157    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12158        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12159        if (hasOverlappingRendering) {
12160            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12161        } else {
12162            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12163        }
12164    }
12165
12166    /**
12167     * Returns the value for overlapping rendering that is used internally. This is either
12168     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12169     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12170     *
12171     * @return The value for overlapping rendering being used internally.
12172     */
12173    public final boolean getHasOverlappingRendering() {
12174        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12175                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12176                hasOverlappingRendering();
12177    }
12178
12179    /**
12180     * Returns whether this View has content which overlaps.
12181     *
12182     * <p>This function, intended to be overridden by specific View types, is an optimization when
12183     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12184     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12185     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12186     * directly. An example of overlapping rendering is a TextView with a background image, such as
12187     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12188     * ImageView with only the foreground image. The default implementation returns true; subclasses
12189     * should override if they have cases which can be optimized.</p>
12190     *
12191     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12192     * necessitates that a View return true if it uses the methods internally without passing the
12193     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12194     *
12195     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12196     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12197     *
12198     * @return true if the content in this view might overlap, false otherwise.
12199     */
12200    @ViewDebug.ExportedProperty(category = "drawing")
12201    public boolean hasOverlappingRendering() {
12202        return true;
12203    }
12204
12205    /**
12206     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12207     * completely transparent and 1 means the view is completely opaque.
12208     *
12209     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12210     * can have significant performance implications, especially for large views. It is best to use
12211     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12212     *
12213     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12214     * strongly recommended for performance reasons to either override
12215     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12216     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12217     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12218     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12219     * of rendering cost, even for simple or small views. Starting with
12220     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12221     * applied to the view at the rendering level.</p>
12222     *
12223     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12224     * responsible for applying the opacity itself.</p>
12225     *
12226     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12227     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12228     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12229     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12230     *
12231     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12232     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12233     * {@link #hasOverlappingRendering}.</p>
12234     *
12235     * @param alpha The opacity of the view.
12236     *
12237     * @see #hasOverlappingRendering()
12238     * @see #setLayerType(int, android.graphics.Paint)
12239     *
12240     * @attr ref android.R.styleable#View_alpha
12241     */
12242    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12243        ensureTransformationInfo();
12244        if (mTransformationInfo.mAlpha != alpha) {
12245            mTransformationInfo.mAlpha = alpha;
12246            if (onSetAlpha((int) (alpha * 255))) {
12247                mPrivateFlags |= PFLAG_ALPHA_SET;
12248                // subclass is handling alpha - don't optimize rendering cache invalidation
12249                invalidateParentCaches();
12250                invalidate(true);
12251            } else {
12252                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12253                invalidateViewProperty(true, false);
12254                mRenderNode.setAlpha(getFinalAlpha());
12255                notifyViewAccessibilityStateChangedIfNeeded(
12256                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12257            }
12258        }
12259    }
12260
12261    /**
12262     * Faster version of setAlpha() which performs the same steps except there are
12263     * no calls to invalidate(). The caller of this function should perform proper invalidation
12264     * on the parent and this object. The return value indicates whether the subclass handles
12265     * alpha (the return value for onSetAlpha()).
12266     *
12267     * @param alpha The new value for the alpha property
12268     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12269     *         the new value for the alpha property is different from the old value
12270     */
12271    boolean setAlphaNoInvalidation(float alpha) {
12272        ensureTransformationInfo();
12273        if (mTransformationInfo.mAlpha != alpha) {
12274            mTransformationInfo.mAlpha = alpha;
12275            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12276            if (subclassHandlesAlpha) {
12277                mPrivateFlags |= PFLAG_ALPHA_SET;
12278                return true;
12279            } else {
12280                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12281                mRenderNode.setAlpha(getFinalAlpha());
12282            }
12283        }
12284        return false;
12285    }
12286
12287    /**
12288     * This property is hidden and intended only for use by the Fade transition, which
12289     * animates it to produce a visual translucency that does not side-effect (or get
12290     * affected by) the real alpha property. This value is composited with the other
12291     * alpha value (and the AlphaAnimation value, when that is present) to produce
12292     * a final visual translucency result, which is what is passed into the DisplayList.
12293     *
12294     * @hide
12295     */
12296    public void setTransitionAlpha(float alpha) {
12297        ensureTransformationInfo();
12298        if (mTransformationInfo.mTransitionAlpha != alpha) {
12299            mTransformationInfo.mTransitionAlpha = alpha;
12300            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12301            invalidateViewProperty(true, false);
12302            mRenderNode.setAlpha(getFinalAlpha());
12303        }
12304    }
12305
12306    /**
12307     * Calculates the visual alpha of this view, which is a combination of the actual
12308     * alpha value and the transitionAlpha value (if set).
12309     */
12310    private float getFinalAlpha() {
12311        if (mTransformationInfo != null) {
12312            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12313        }
12314        return 1;
12315    }
12316
12317    /**
12318     * This property is hidden and intended only for use by the Fade transition, which
12319     * animates it to produce a visual translucency that does not side-effect (or get
12320     * affected by) the real alpha property. This value is composited with the other
12321     * alpha value (and the AlphaAnimation value, when that is present) to produce
12322     * a final visual translucency result, which is what is passed into the DisplayList.
12323     *
12324     * @hide
12325     */
12326    @ViewDebug.ExportedProperty(category = "drawing")
12327    public float getTransitionAlpha() {
12328        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12329    }
12330
12331    /**
12332     * Top position of this view relative to its parent.
12333     *
12334     * @return The top of this view, in pixels.
12335     */
12336    @ViewDebug.CapturedViewProperty
12337    public final int getTop() {
12338        return mTop;
12339    }
12340
12341    /**
12342     * Sets the top position of this view relative to its parent. This method is meant to be called
12343     * by the layout system and should not generally be called otherwise, because the property
12344     * may be changed at any time by the layout.
12345     *
12346     * @param top The top of this view, in pixels.
12347     */
12348    public final void setTop(int top) {
12349        if (top != mTop) {
12350            final boolean matrixIsIdentity = hasIdentityMatrix();
12351            if (matrixIsIdentity) {
12352                if (mAttachInfo != null) {
12353                    int minTop;
12354                    int yLoc;
12355                    if (top < mTop) {
12356                        minTop = top;
12357                        yLoc = top - mTop;
12358                    } else {
12359                        minTop = mTop;
12360                        yLoc = 0;
12361                    }
12362                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12363                }
12364            } else {
12365                // Double-invalidation is necessary to capture view's old and new areas
12366                invalidate(true);
12367            }
12368
12369            int width = mRight - mLeft;
12370            int oldHeight = mBottom - mTop;
12371
12372            mTop = top;
12373            mRenderNode.setTop(mTop);
12374
12375            sizeChange(width, mBottom - mTop, width, oldHeight);
12376
12377            if (!matrixIsIdentity) {
12378                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12379                invalidate(true);
12380            }
12381            mBackgroundSizeChanged = true;
12382            if (mForegroundInfo != null) {
12383                mForegroundInfo.mBoundsChanged = true;
12384            }
12385            invalidateParentIfNeeded();
12386            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12387                // View was rejected last time it was drawn by its parent; this may have changed
12388                invalidateParentIfNeeded();
12389            }
12390        }
12391    }
12392
12393    /**
12394     * Bottom position of this view relative to its parent.
12395     *
12396     * @return The bottom of this view, in pixels.
12397     */
12398    @ViewDebug.CapturedViewProperty
12399    public final int getBottom() {
12400        return mBottom;
12401    }
12402
12403    /**
12404     * True if this view has changed since the last time being drawn.
12405     *
12406     * @return The dirty state of this view.
12407     */
12408    public boolean isDirty() {
12409        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12410    }
12411
12412    /**
12413     * Sets the bottom position of this view relative to its parent. This method is meant to be
12414     * called by the layout system and should not generally be called otherwise, because the
12415     * property may be changed at any time by the layout.
12416     *
12417     * @param bottom The bottom of this view, in pixels.
12418     */
12419    public final void setBottom(int bottom) {
12420        if (bottom != mBottom) {
12421            final boolean matrixIsIdentity = hasIdentityMatrix();
12422            if (matrixIsIdentity) {
12423                if (mAttachInfo != null) {
12424                    int maxBottom;
12425                    if (bottom < mBottom) {
12426                        maxBottom = mBottom;
12427                    } else {
12428                        maxBottom = bottom;
12429                    }
12430                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12431                }
12432            } else {
12433                // Double-invalidation is necessary to capture view's old and new areas
12434                invalidate(true);
12435            }
12436
12437            int width = mRight - mLeft;
12438            int oldHeight = mBottom - mTop;
12439
12440            mBottom = bottom;
12441            mRenderNode.setBottom(mBottom);
12442
12443            sizeChange(width, mBottom - mTop, width, oldHeight);
12444
12445            if (!matrixIsIdentity) {
12446                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12447                invalidate(true);
12448            }
12449            mBackgroundSizeChanged = true;
12450            if (mForegroundInfo != null) {
12451                mForegroundInfo.mBoundsChanged = true;
12452            }
12453            invalidateParentIfNeeded();
12454            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12455                // View was rejected last time it was drawn by its parent; this may have changed
12456                invalidateParentIfNeeded();
12457            }
12458        }
12459    }
12460
12461    /**
12462     * Left position of this view relative to its parent.
12463     *
12464     * @return The left edge of this view, in pixels.
12465     */
12466    @ViewDebug.CapturedViewProperty
12467    public final int getLeft() {
12468        return mLeft;
12469    }
12470
12471    /**
12472     * Sets the left position of this view relative to its parent. This method is meant to be called
12473     * by the layout system and should not generally be called otherwise, because the property
12474     * may be changed at any time by the layout.
12475     *
12476     * @param left The left of this view, in pixels.
12477     */
12478    public final void setLeft(int left) {
12479        if (left != mLeft) {
12480            final boolean matrixIsIdentity = hasIdentityMatrix();
12481            if (matrixIsIdentity) {
12482                if (mAttachInfo != null) {
12483                    int minLeft;
12484                    int xLoc;
12485                    if (left < mLeft) {
12486                        minLeft = left;
12487                        xLoc = left - mLeft;
12488                    } else {
12489                        minLeft = mLeft;
12490                        xLoc = 0;
12491                    }
12492                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12493                }
12494            } else {
12495                // Double-invalidation is necessary to capture view's old and new areas
12496                invalidate(true);
12497            }
12498
12499            int oldWidth = mRight - mLeft;
12500            int height = mBottom - mTop;
12501
12502            mLeft = left;
12503            mRenderNode.setLeft(left);
12504
12505            sizeChange(mRight - mLeft, height, oldWidth, height);
12506
12507            if (!matrixIsIdentity) {
12508                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12509                invalidate(true);
12510            }
12511            mBackgroundSizeChanged = true;
12512            if (mForegroundInfo != null) {
12513                mForegroundInfo.mBoundsChanged = true;
12514            }
12515            invalidateParentIfNeeded();
12516            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12517                // View was rejected last time it was drawn by its parent; this may have changed
12518                invalidateParentIfNeeded();
12519            }
12520        }
12521    }
12522
12523    /**
12524     * Right position of this view relative to its parent.
12525     *
12526     * @return The right edge of this view, in pixels.
12527     */
12528    @ViewDebug.CapturedViewProperty
12529    public final int getRight() {
12530        return mRight;
12531    }
12532
12533    /**
12534     * Sets the right position of this view relative to its parent. This method is meant to be called
12535     * by the layout system and should not generally be called otherwise, because the property
12536     * may be changed at any time by the layout.
12537     *
12538     * @param right The right of this view, in pixels.
12539     */
12540    public final void setRight(int right) {
12541        if (right != mRight) {
12542            final boolean matrixIsIdentity = hasIdentityMatrix();
12543            if (matrixIsIdentity) {
12544                if (mAttachInfo != null) {
12545                    int maxRight;
12546                    if (right < mRight) {
12547                        maxRight = mRight;
12548                    } else {
12549                        maxRight = right;
12550                    }
12551                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12552                }
12553            } else {
12554                // Double-invalidation is necessary to capture view's old and new areas
12555                invalidate(true);
12556            }
12557
12558            int oldWidth = mRight - mLeft;
12559            int height = mBottom - mTop;
12560
12561            mRight = right;
12562            mRenderNode.setRight(mRight);
12563
12564            sizeChange(mRight - mLeft, height, oldWidth, height);
12565
12566            if (!matrixIsIdentity) {
12567                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12568                invalidate(true);
12569            }
12570            mBackgroundSizeChanged = true;
12571            if (mForegroundInfo != null) {
12572                mForegroundInfo.mBoundsChanged = true;
12573            }
12574            invalidateParentIfNeeded();
12575            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12576                // View was rejected last time it was drawn by its parent; this may have changed
12577                invalidateParentIfNeeded();
12578            }
12579        }
12580    }
12581
12582    /**
12583     * The visual x position of this view, in pixels. This is equivalent to the
12584     * {@link #setTranslationX(float) translationX} property plus the current
12585     * {@link #getLeft() left} property.
12586     *
12587     * @return The visual x position of this view, in pixels.
12588     */
12589    @ViewDebug.ExportedProperty(category = "drawing")
12590    public float getX() {
12591        return mLeft + getTranslationX();
12592    }
12593
12594    /**
12595     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12596     * {@link #setTranslationX(float) translationX} property to be the difference between
12597     * the x value passed in and the current {@link #getLeft() left} property.
12598     *
12599     * @param x The visual x position of this view, in pixels.
12600     */
12601    public void setX(float x) {
12602        setTranslationX(x - mLeft);
12603    }
12604
12605    /**
12606     * The visual y position of this view, in pixels. This is equivalent to the
12607     * {@link #setTranslationY(float) translationY} property plus the current
12608     * {@link #getTop() top} property.
12609     *
12610     * @return The visual y position of this view, in pixels.
12611     */
12612    @ViewDebug.ExportedProperty(category = "drawing")
12613    public float getY() {
12614        return mTop + getTranslationY();
12615    }
12616
12617    /**
12618     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12619     * {@link #setTranslationY(float) translationY} property to be the difference between
12620     * the y value passed in and the current {@link #getTop() top} property.
12621     *
12622     * @param y The visual y position of this view, in pixels.
12623     */
12624    public void setY(float y) {
12625        setTranslationY(y - mTop);
12626    }
12627
12628    /**
12629     * The visual z position of this view, in pixels. This is equivalent to the
12630     * {@link #setTranslationZ(float) translationZ} property plus the current
12631     * {@link #getElevation() elevation} property.
12632     *
12633     * @return The visual z position of this view, in pixels.
12634     */
12635    @ViewDebug.ExportedProperty(category = "drawing")
12636    public float getZ() {
12637        return getElevation() + getTranslationZ();
12638    }
12639
12640    /**
12641     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12642     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12643     * the x value passed in and the current {@link #getElevation() elevation} property.
12644     *
12645     * @param z The visual z position of this view, in pixels.
12646     */
12647    public void setZ(float z) {
12648        setTranslationZ(z - getElevation());
12649    }
12650
12651    /**
12652     * The base elevation of this view relative to its parent, in pixels.
12653     *
12654     * @return The base depth position of the view, in pixels.
12655     */
12656    @ViewDebug.ExportedProperty(category = "drawing")
12657    public float getElevation() {
12658        return mRenderNode.getElevation();
12659    }
12660
12661    /**
12662     * Sets the base elevation of this view, in pixels.
12663     *
12664     * @attr ref android.R.styleable#View_elevation
12665     */
12666    public void setElevation(float elevation) {
12667        if (elevation != getElevation()) {
12668            invalidateViewProperty(true, false);
12669            mRenderNode.setElevation(elevation);
12670            invalidateViewProperty(false, true);
12671
12672            invalidateParentIfNeededAndWasQuickRejected();
12673        }
12674    }
12675
12676    /**
12677     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12678     * This position is post-layout, in addition to wherever the object's
12679     * layout placed it.
12680     *
12681     * @return The horizontal position of this view relative to its left position, in pixels.
12682     */
12683    @ViewDebug.ExportedProperty(category = "drawing")
12684    public float getTranslationX() {
12685        return mRenderNode.getTranslationX();
12686    }
12687
12688    /**
12689     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12690     * This effectively positions the object post-layout, in addition to wherever the object's
12691     * layout placed it.
12692     *
12693     * @param translationX The horizontal position of this view relative to its left position,
12694     * in pixels.
12695     *
12696     * @attr ref android.R.styleable#View_translationX
12697     */
12698    public void setTranslationX(float translationX) {
12699        if (translationX != getTranslationX()) {
12700            invalidateViewProperty(true, false);
12701            mRenderNode.setTranslationX(translationX);
12702            invalidateViewProperty(false, true);
12703
12704            invalidateParentIfNeededAndWasQuickRejected();
12705            notifySubtreeAccessibilityStateChangedIfNeeded();
12706        }
12707    }
12708
12709    /**
12710     * The vertical location of this view relative to its {@link #getTop() top} position.
12711     * This position is post-layout, in addition to wherever the object's
12712     * layout placed it.
12713     *
12714     * @return The vertical position of this view relative to its top position,
12715     * in pixels.
12716     */
12717    @ViewDebug.ExportedProperty(category = "drawing")
12718    public float getTranslationY() {
12719        return mRenderNode.getTranslationY();
12720    }
12721
12722    /**
12723     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12724     * This effectively positions the object post-layout, in addition to wherever the object's
12725     * layout placed it.
12726     *
12727     * @param translationY The vertical position of this view relative to its top position,
12728     * in pixels.
12729     *
12730     * @attr ref android.R.styleable#View_translationY
12731     */
12732    public void setTranslationY(float translationY) {
12733        if (translationY != getTranslationY()) {
12734            invalidateViewProperty(true, false);
12735            mRenderNode.setTranslationY(translationY);
12736            invalidateViewProperty(false, true);
12737
12738            invalidateParentIfNeededAndWasQuickRejected();
12739            notifySubtreeAccessibilityStateChangedIfNeeded();
12740        }
12741    }
12742
12743    /**
12744     * The depth location of this view relative to its {@link #getElevation() elevation}.
12745     *
12746     * @return The depth of this view relative to its elevation.
12747     */
12748    @ViewDebug.ExportedProperty(category = "drawing")
12749    public float getTranslationZ() {
12750        return mRenderNode.getTranslationZ();
12751    }
12752
12753    /**
12754     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12755     *
12756     * @attr ref android.R.styleable#View_translationZ
12757     */
12758    public void setTranslationZ(float translationZ) {
12759        if (translationZ != getTranslationZ()) {
12760            invalidateViewProperty(true, false);
12761            mRenderNode.setTranslationZ(translationZ);
12762            invalidateViewProperty(false, true);
12763
12764            invalidateParentIfNeededAndWasQuickRejected();
12765        }
12766    }
12767
12768    /** @hide */
12769    public void setAnimationMatrix(Matrix matrix) {
12770        invalidateViewProperty(true, false);
12771        mRenderNode.setAnimationMatrix(matrix);
12772        invalidateViewProperty(false, true);
12773
12774        invalidateParentIfNeededAndWasQuickRejected();
12775    }
12776
12777    /**
12778     * Returns the current StateListAnimator if exists.
12779     *
12780     * @return StateListAnimator or null if it does not exists
12781     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12782     */
12783    public StateListAnimator getStateListAnimator() {
12784        return mStateListAnimator;
12785    }
12786
12787    /**
12788     * Attaches the provided StateListAnimator to this View.
12789     * <p>
12790     * Any previously attached StateListAnimator will be detached.
12791     *
12792     * @param stateListAnimator The StateListAnimator to update the view
12793     * @see {@link android.animation.StateListAnimator}
12794     */
12795    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12796        if (mStateListAnimator == stateListAnimator) {
12797            return;
12798        }
12799        if (mStateListAnimator != null) {
12800            mStateListAnimator.setTarget(null);
12801        }
12802        mStateListAnimator = stateListAnimator;
12803        if (stateListAnimator != null) {
12804            stateListAnimator.setTarget(this);
12805            if (isAttachedToWindow()) {
12806                stateListAnimator.setState(getDrawableState());
12807            }
12808        }
12809    }
12810
12811    /**
12812     * Returns whether the Outline should be used to clip the contents of the View.
12813     * <p>
12814     * Note that this flag will only be respected if the View's Outline returns true from
12815     * {@link Outline#canClip()}.
12816     *
12817     * @see #setOutlineProvider(ViewOutlineProvider)
12818     * @see #setClipToOutline(boolean)
12819     */
12820    public final boolean getClipToOutline() {
12821        return mRenderNode.getClipToOutline();
12822    }
12823
12824    /**
12825     * Sets whether the View's Outline should be used to clip the contents of the View.
12826     * <p>
12827     * Only a single non-rectangular clip can be applied on a View at any time.
12828     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12829     * circular reveal} animation take priority over Outline clipping, and
12830     * child Outline clipping takes priority over Outline clipping done by a
12831     * parent.
12832     * <p>
12833     * Note that this flag will only be respected if the View's Outline returns true from
12834     * {@link Outline#canClip()}.
12835     *
12836     * @see #setOutlineProvider(ViewOutlineProvider)
12837     * @see #getClipToOutline()
12838     */
12839    public void setClipToOutline(boolean clipToOutline) {
12840        damageInParent();
12841        if (getClipToOutline() != clipToOutline) {
12842            mRenderNode.setClipToOutline(clipToOutline);
12843        }
12844    }
12845
12846    // correspond to the enum values of View_outlineProvider
12847    private static final int PROVIDER_BACKGROUND = 0;
12848    private static final int PROVIDER_NONE = 1;
12849    private static final int PROVIDER_BOUNDS = 2;
12850    private static final int PROVIDER_PADDED_BOUNDS = 3;
12851    private void setOutlineProviderFromAttribute(int providerInt) {
12852        switch (providerInt) {
12853            case PROVIDER_BACKGROUND:
12854                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12855                break;
12856            case PROVIDER_NONE:
12857                setOutlineProvider(null);
12858                break;
12859            case PROVIDER_BOUNDS:
12860                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12861                break;
12862            case PROVIDER_PADDED_BOUNDS:
12863                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12864                break;
12865        }
12866    }
12867
12868    /**
12869     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12870     * the shape of the shadow it casts, and enables outline clipping.
12871     * <p>
12872     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12873     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12874     * outline provider with this method allows this behavior to be overridden.
12875     * <p>
12876     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12877     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12878     * <p>
12879     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12880     *
12881     * @see #setClipToOutline(boolean)
12882     * @see #getClipToOutline()
12883     * @see #getOutlineProvider()
12884     */
12885    public void setOutlineProvider(ViewOutlineProvider provider) {
12886        mOutlineProvider = provider;
12887        invalidateOutline();
12888    }
12889
12890    /**
12891     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12892     * that defines the shape of the shadow it casts, and enables outline clipping.
12893     *
12894     * @see #setOutlineProvider(ViewOutlineProvider)
12895     */
12896    public ViewOutlineProvider getOutlineProvider() {
12897        return mOutlineProvider;
12898    }
12899
12900    /**
12901     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12902     *
12903     * @see #setOutlineProvider(ViewOutlineProvider)
12904     */
12905    public void invalidateOutline() {
12906        rebuildOutline();
12907
12908        notifySubtreeAccessibilityStateChangedIfNeeded();
12909        invalidateViewProperty(false, false);
12910    }
12911
12912    /**
12913     * Internal version of {@link #invalidateOutline()} which invalidates the
12914     * outline without invalidating the view itself. This is intended to be called from
12915     * within methods in the View class itself which are the result of the view being
12916     * invalidated already. For example, when we are drawing the background of a View,
12917     * we invalidate the outline in case it changed in the meantime, but we do not
12918     * need to invalidate the view because we're already drawing the background as part
12919     * of drawing the view in response to an earlier invalidation of the view.
12920     */
12921    private void rebuildOutline() {
12922        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12923        if (mAttachInfo == null) return;
12924
12925        if (mOutlineProvider == null) {
12926            // no provider, remove outline
12927            mRenderNode.setOutline(null);
12928        } else {
12929            final Outline outline = mAttachInfo.mTmpOutline;
12930            outline.setEmpty();
12931            outline.setAlpha(1.0f);
12932
12933            mOutlineProvider.getOutline(this, outline);
12934            mRenderNode.setOutline(outline);
12935        }
12936    }
12937
12938    /**
12939     * HierarchyViewer only
12940     *
12941     * @hide
12942     */
12943    @ViewDebug.ExportedProperty(category = "drawing")
12944    public boolean hasShadow() {
12945        return mRenderNode.hasShadow();
12946    }
12947
12948
12949    /** @hide */
12950    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
12951        mRenderNode.setRevealClip(shouldClip, x, y, radius);
12952        invalidateViewProperty(false, false);
12953    }
12954
12955    /**
12956     * Hit rectangle in parent's coordinates
12957     *
12958     * @param outRect The hit rectangle of the view.
12959     */
12960    public void getHitRect(Rect outRect) {
12961        if (hasIdentityMatrix() || mAttachInfo == null) {
12962            outRect.set(mLeft, mTop, mRight, mBottom);
12963        } else {
12964            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
12965            tmpRect.set(0, 0, getWidth(), getHeight());
12966            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
12967            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
12968                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
12969        }
12970    }
12971
12972    /**
12973     * Determines whether the given point, in local coordinates is inside the view.
12974     */
12975    /*package*/ final boolean pointInView(float localX, float localY) {
12976        return pointInView(localX, localY, 0);
12977    }
12978
12979    /**
12980     * Utility method to determine whether the given point, in local coordinates,
12981     * is inside the view, where the area of the view is expanded by the slop factor.
12982     * This method is called while processing touch-move events to determine if the event
12983     * is still within the view.
12984     *
12985     * @hide
12986     */
12987    public boolean pointInView(float localX, float localY, float slop) {
12988        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
12989                localY < ((mBottom - mTop) + slop);
12990    }
12991
12992    /**
12993     * When a view has focus and the user navigates away from it, the next view is searched for
12994     * starting from the rectangle filled in by this method.
12995     *
12996     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
12997     * of the view.  However, if your view maintains some idea of internal selection,
12998     * such as a cursor, or a selected row or column, you should override this method and
12999     * fill in a more specific rectangle.
13000     *
13001     * @param r The rectangle to fill in, in this view's coordinates.
13002     */
13003    public void getFocusedRect(Rect r) {
13004        getDrawingRect(r);
13005    }
13006
13007    /**
13008     * If some part of this view is not clipped by any of its parents, then
13009     * return that area in r in global (root) coordinates. To convert r to local
13010     * coordinates (without taking possible View rotations into account), offset
13011     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13012     * If the view is completely clipped or translated out, return false.
13013     *
13014     * @param r If true is returned, r holds the global coordinates of the
13015     *        visible portion of this view.
13016     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13017     *        between this view and its root. globalOffet may be null.
13018     * @return true if r is non-empty (i.e. part of the view is visible at the
13019     *         root level.
13020     */
13021    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13022        int width = mRight - mLeft;
13023        int height = mBottom - mTop;
13024        if (width > 0 && height > 0) {
13025            r.set(0, 0, width, height);
13026            if (globalOffset != null) {
13027                globalOffset.set(-mScrollX, -mScrollY);
13028            }
13029            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13030        }
13031        return false;
13032    }
13033
13034    public final boolean getGlobalVisibleRect(Rect r) {
13035        return getGlobalVisibleRect(r, null);
13036    }
13037
13038    public final boolean getLocalVisibleRect(Rect r) {
13039        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13040        if (getGlobalVisibleRect(r, offset)) {
13041            r.offset(-offset.x, -offset.y); // make r local
13042            return true;
13043        }
13044        return false;
13045    }
13046
13047    /**
13048     * Offset this view's vertical location by the specified number of pixels.
13049     *
13050     * @param offset the number of pixels to offset the view by
13051     */
13052    public void offsetTopAndBottom(int offset) {
13053        if (offset != 0) {
13054            final boolean matrixIsIdentity = hasIdentityMatrix();
13055            if (matrixIsIdentity) {
13056                if (isHardwareAccelerated()) {
13057                    invalidateViewProperty(false, false);
13058                } else {
13059                    final ViewParent p = mParent;
13060                    if (p != null && mAttachInfo != null) {
13061                        final Rect r = mAttachInfo.mTmpInvalRect;
13062                        int minTop;
13063                        int maxBottom;
13064                        int yLoc;
13065                        if (offset < 0) {
13066                            minTop = mTop + offset;
13067                            maxBottom = mBottom;
13068                            yLoc = offset;
13069                        } else {
13070                            minTop = mTop;
13071                            maxBottom = mBottom + offset;
13072                            yLoc = 0;
13073                        }
13074                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13075                        p.invalidateChild(this, r);
13076                    }
13077                }
13078            } else {
13079                invalidateViewProperty(false, false);
13080            }
13081
13082            mTop += offset;
13083            mBottom += offset;
13084            mRenderNode.offsetTopAndBottom(offset);
13085            if (isHardwareAccelerated()) {
13086                invalidateViewProperty(false, false);
13087                invalidateParentIfNeededAndWasQuickRejected();
13088            } else {
13089                if (!matrixIsIdentity) {
13090                    invalidateViewProperty(false, true);
13091                }
13092                invalidateParentIfNeeded();
13093            }
13094            notifySubtreeAccessibilityStateChangedIfNeeded();
13095        }
13096    }
13097
13098    /**
13099     * Offset this view's horizontal location by the specified amount of pixels.
13100     *
13101     * @param offset the number of pixels to offset the view by
13102     */
13103    public void offsetLeftAndRight(int offset) {
13104        if (offset != 0) {
13105            final boolean matrixIsIdentity = hasIdentityMatrix();
13106            if (matrixIsIdentity) {
13107                if (isHardwareAccelerated()) {
13108                    invalidateViewProperty(false, false);
13109                } else {
13110                    final ViewParent p = mParent;
13111                    if (p != null && mAttachInfo != null) {
13112                        final Rect r = mAttachInfo.mTmpInvalRect;
13113                        int minLeft;
13114                        int maxRight;
13115                        if (offset < 0) {
13116                            minLeft = mLeft + offset;
13117                            maxRight = mRight;
13118                        } else {
13119                            minLeft = mLeft;
13120                            maxRight = mRight + offset;
13121                        }
13122                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13123                        p.invalidateChild(this, r);
13124                    }
13125                }
13126            } else {
13127                invalidateViewProperty(false, false);
13128            }
13129
13130            mLeft += offset;
13131            mRight += offset;
13132            mRenderNode.offsetLeftAndRight(offset);
13133            if (isHardwareAccelerated()) {
13134                invalidateViewProperty(false, false);
13135                invalidateParentIfNeededAndWasQuickRejected();
13136            } else {
13137                if (!matrixIsIdentity) {
13138                    invalidateViewProperty(false, true);
13139                }
13140                invalidateParentIfNeeded();
13141            }
13142            notifySubtreeAccessibilityStateChangedIfNeeded();
13143        }
13144    }
13145
13146    /**
13147     * Get the LayoutParams associated with this view. All views should have
13148     * layout parameters. These supply parameters to the <i>parent</i> of this
13149     * view specifying how it should be arranged. There are many subclasses of
13150     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13151     * of ViewGroup that are responsible for arranging their children.
13152     *
13153     * This method may return null if this View is not attached to a parent
13154     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13155     * was not invoked successfully. When a View is attached to a parent
13156     * ViewGroup, this method must not return null.
13157     *
13158     * @return The LayoutParams associated with this view, or null if no
13159     *         parameters have been set yet
13160     */
13161    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13162    public ViewGroup.LayoutParams getLayoutParams() {
13163        return mLayoutParams;
13164    }
13165
13166    /**
13167     * Set the layout parameters associated with this view. These supply
13168     * parameters to the <i>parent</i> of this view specifying how it should be
13169     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13170     * correspond to the different subclasses of ViewGroup that are responsible
13171     * for arranging their children.
13172     *
13173     * @param params The layout parameters for this view, cannot be null
13174     */
13175    public void setLayoutParams(ViewGroup.LayoutParams params) {
13176        if (params == null) {
13177            throw new NullPointerException("Layout parameters cannot be null");
13178        }
13179        mLayoutParams = params;
13180        resolveLayoutParams();
13181        if (mParent instanceof ViewGroup) {
13182            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13183        }
13184        requestLayout();
13185    }
13186
13187    /**
13188     * Resolve the layout parameters depending on the resolved layout direction
13189     *
13190     * @hide
13191     */
13192    public void resolveLayoutParams() {
13193        if (mLayoutParams != null) {
13194            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13195        }
13196    }
13197
13198    /**
13199     * Set the scrolled position of your view. This will cause a call to
13200     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13201     * invalidated.
13202     * @param x the x position to scroll to
13203     * @param y the y position to scroll to
13204     */
13205    public void scrollTo(int x, int y) {
13206        if (mScrollX != x || mScrollY != y) {
13207            int oldX = mScrollX;
13208            int oldY = mScrollY;
13209            mScrollX = x;
13210            mScrollY = y;
13211            invalidateParentCaches();
13212            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13213            if (!awakenScrollBars()) {
13214                postInvalidateOnAnimation();
13215            }
13216        }
13217    }
13218
13219    /**
13220     * Move the scrolled position of your view. This will cause a call to
13221     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13222     * invalidated.
13223     * @param x the amount of pixels to scroll by horizontally
13224     * @param y the amount of pixels to scroll by vertically
13225     */
13226    public void scrollBy(int x, int y) {
13227        scrollTo(mScrollX + x, mScrollY + y);
13228    }
13229
13230    /**
13231     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13232     * animation to fade the scrollbars out after a default delay. If a subclass
13233     * provides animated scrolling, the start delay should equal the duration
13234     * of the scrolling animation.</p>
13235     *
13236     * <p>The animation starts only if at least one of the scrollbars is
13237     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13238     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13239     * this method returns true, and false otherwise. If the animation is
13240     * started, this method calls {@link #invalidate()}; in that case the
13241     * caller should not call {@link #invalidate()}.</p>
13242     *
13243     * <p>This method should be invoked every time a subclass directly updates
13244     * the scroll parameters.</p>
13245     *
13246     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13247     * and {@link #scrollTo(int, int)}.</p>
13248     *
13249     * @return true if the animation is played, false otherwise
13250     *
13251     * @see #awakenScrollBars(int)
13252     * @see #scrollBy(int, int)
13253     * @see #scrollTo(int, int)
13254     * @see #isHorizontalScrollBarEnabled()
13255     * @see #isVerticalScrollBarEnabled()
13256     * @see #setHorizontalScrollBarEnabled(boolean)
13257     * @see #setVerticalScrollBarEnabled(boolean)
13258     */
13259    protected boolean awakenScrollBars() {
13260        return mScrollCache != null &&
13261                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13262    }
13263
13264    /**
13265     * Trigger the scrollbars to draw.
13266     * This method differs from awakenScrollBars() only in its default duration.
13267     * initialAwakenScrollBars() will show the scroll bars for longer than
13268     * usual to give the user more of a chance to notice them.
13269     *
13270     * @return true if the animation is played, false otherwise.
13271     */
13272    private boolean initialAwakenScrollBars() {
13273        return mScrollCache != null &&
13274                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13275    }
13276
13277    /**
13278     * <p>
13279     * Trigger the scrollbars to draw. When invoked this method starts an
13280     * animation to fade the scrollbars out after a fixed delay. If a subclass
13281     * provides animated scrolling, the start delay should equal the duration of
13282     * the scrolling animation.
13283     * </p>
13284     *
13285     * <p>
13286     * The animation starts only if at least one of the scrollbars is enabled,
13287     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13288     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13289     * this method returns true, and false otherwise. If the animation is
13290     * started, this method calls {@link #invalidate()}; in that case the caller
13291     * should not call {@link #invalidate()}.
13292     * </p>
13293     *
13294     * <p>
13295     * This method should be invoked every time a subclass directly updates the
13296     * scroll parameters.
13297     * </p>
13298     *
13299     * @param startDelay the delay, in milliseconds, after which the animation
13300     *        should start; when the delay is 0, the animation starts
13301     *        immediately
13302     * @return true if the animation is played, false otherwise
13303     *
13304     * @see #scrollBy(int, int)
13305     * @see #scrollTo(int, int)
13306     * @see #isHorizontalScrollBarEnabled()
13307     * @see #isVerticalScrollBarEnabled()
13308     * @see #setHorizontalScrollBarEnabled(boolean)
13309     * @see #setVerticalScrollBarEnabled(boolean)
13310     */
13311    protected boolean awakenScrollBars(int startDelay) {
13312        return awakenScrollBars(startDelay, true);
13313    }
13314
13315    /**
13316     * <p>
13317     * Trigger the scrollbars to draw. When invoked this method starts an
13318     * animation to fade the scrollbars out after a fixed delay. If a subclass
13319     * provides animated scrolling, the start delay should equal the duration of
13320     * the scrolling animation.
13321     * </p>
13322     *
13323     * <p>
13324     * The animation starts only if at least one of the scrollbars is enabled,
13325     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13326     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13327     * this method returns true, and false otherwise. If the animation is
13328     * started, this method calls {@link #invalidate()} if the invalidate parameter
13329     * is set to true; in that case the caller
13330     * should not call {@link #invalidate()}.
13331     * </p>
13332     *
13333     * <p>
13334     * This method should be invoked every time a subclass directly updates the
13335     * scroll parameters.
13336     * </p>
13337     *
13338     * @param startDelay the delay, in milliseconds, after which the animation
13339     *        should start; when the delay is 0, the animation starts
13340     *        immediately
13341     *
13342     * @param invalidate Whether this method should call invalidate
13343     *
13344     * @return true if the animation is played, false otherwise
13345     *
13346     * @see #scrollBy(int, int)
13347     * @see #scrollTo(int, int)
13348     * @see #isHorizontalScrollBarEnabled()
13349     * @see #isVerticalScrollBarEnabled()
13350     * @see #setHorizontalScrollBarEnabled(boolean)
13351     * @see #setVerticalScrollBarEnabled(boolean)
13352     */
13353    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13354        final ScrollabilityCache scrollCache = mScrollCache;
13355
13356        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13357            return false;
13358        }
13359
13360        if (scrollCache.scrollBar == null) {
13361            scrollCache.scrollBar = new ScrollBarDrawable();
13362            scrollCache.scrollBar.setState(getDrawableState());
13363            scrollCache.scrollBar.setCallback(this);
13364        }
13365
13366        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13367
13368            if (invalidate) {
13369                // Invalidate to show the scrollbars
13370                postInvalidateOnAnimation();
13371            }
13372
13373            if (scrollCache.state == ScrollabilityCache.OFF) {
13374                // FIXME: this is copied from WindowManagerService.
13375                // We should get this value from the system when it
13376                // is possible to do so.
13377                final int KEY_REPEAT_FIRST_DELAY = 750;
13378                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13379            }
13380
13381            // Tell mScrollCache when we should start fading. This may
13382            // extend the fade start time if one was already scheduled
13383            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13384            scrollCache.fadeStartTime = fadeStartTime;
13385            scrollCache.state = ScrollabilityCache.ON;
13386
13387            // Schedule our fader to run, unscheduling any old ones first
13388            if (mAttachInfo != null) {
13389                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13390                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13391            }
13392
13393            return true;
13394        }
13395
13396        return false;
13397    }
13398
13399    /**
13400     * Do not invalidate views which are not visible and which are not running an animation. They
13401     * will not get drawn and they should not set dirty flags as if they will be drawn
13402     */
13403    private boolean skipInvalidate() {
13404        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13405                (!(mParent instanceof ViewGroup) ||
13406                        !((ViewGroup) mParent).isViewTransitioning(this));
13407    }
13408
13409    /**
13410     * Mark the area defined by dirty as needing to be drawn. If the view is
13411     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13412     * point in the future.
13413     * <p>
13414     * This must be called from a UI thread. To call from a non-UI thread, call
13415     * {@link #postInvalidate()}.
13416     * <p>
13417     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13418     * {@code dirty}.
13419     *
13420     * @param dirty the rectangle representing the bounds of the dirty region
13421     */
13422    public void invalidate(Rect dirty) {
13423        final int scrollX = mScrollX;
13424        final int scrollY = mScrollY;
13425        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13426                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13427    }
13428
13429    /**
13430     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13431     * coordinates of the dirty rect are relative to the view. If the view is
13432     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13433     * point in the future.
13434     * <p>
13435     * This must be called from a UI thread. To call from a non-UI thread, call
13436     * {@link #postInvalidate()}.
13437     *
13438     * @param l the left position of the dirty region
13439     * @param t the top position of the dirty region
13440     * @param r the right position of the dirty region
13441     * @param b the bottom position of the dirty region
13442     */
13443    public void invalidate(int l, int t, int r, int b) {
13444        final int scrollX = mScrollX;
13445        final int scrollY = mScrollY;
13446        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13447    }
13448
13449    /**
13450     * Invalidate the whole view. If the view is visible,
13451     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13452     * the future.
13453     * <p>
13454     * This must be called from a UI thread. To call from a non-UI thread, call
13455     * {@link #postInvalidate()}.
13456     */
13457    public void invalidate() {
13458        invalidate(true);
13459    }
13460
13461    /**
13462     * This is where the invalidate() work actually happens. A full invalidate()
13463     * causes the drawing cache to be invalidated, but this function can be
13464     * called with invalidateCache set to false to skip that invalidation step
13465     * for cases that do not need it (for example, a component that remains at
13466     * the same dimensions with the same content).
13467     *
13468     * @param invalidateCache Whether the drawing cache for this view should be
13469     *            invalidated as well. This is usually true for a full
13470     *            invalidate, but may be set to false if the View's contents or
13471     *            dimensions have not changed.
13472     */
13473    void invalidate(boolean invalidateCache) {
13474        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13475    }
13476
13477    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13478            boolean fullInvalidate) {
13479        if (mGhostView != null) {
13480            mGhostView.invalidate(true);
13481            return;
13482        }
13483
13484        if (skipInvalidate()) {
13485            return;
13486        }
13487
13488        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13489                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13490                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13491                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13492            if (fullInvalidate) {
13493                mLastIsOpaque = isOpaque();
13494                mPrivateFlags &= ~PFLAG_DRAWN;
13495            }
13496
13497            mPrivateFlags |= PFLAG_DIRTY;
13498
13499            if (invalidateCache) {
13500                mPrivateFlags |= PFLAG_INVALIDATED;
13501                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13502            }
13503
13504            // Propagate the damage rectangle to the parent view.
13505            final AttachInfo ai = mAttachInfo;
13506            final ViewParent p = mParent;
13507            if (p != null && ai != null && l < r && t < b) {
13508                final Rect damage = ai.mTmpInvalRect;
13509                damage.set(l, t, r, b);
13510                p.invalidateChild(this, damage);
13511            }
13512
13513            // Damage the entire projection receiver, if necessary.
13514            if (mBackground != null && mBackground.isProjected()) {
13515                final View receiver = getProjectionReceiver();
13516                if (receiver != null) {
13517                    receiver.damageInParent();
13518                }
13519            }
13520
13521            // Damage the entire IsolatedZVolume receiving this view's shadow.
13522            if (isHardwareAccelerated() && getZ() != 0) {
13523                damageShadowReceiver();
13524            }
13525        }
13526    }
13527
13528    /**
13529     * @return this view's projection receiver, or {@code null} if none exists
13530     */
13531    private View getProjectionReceiver() {
13532        ViewParent p = getParent();
13533        while (p != null && p instanceof View) {
13534            final View v = (View) p;
13535            if (v.isProjectionReceiver()) {
13536                return v;
13537            }
13538            p = p.getParent();
13539        }
13540
13541        return null;
13542    }
13543
13544    /**
13545     * @return whether the view is a projection receiver
13546     */
13547    private boolean isProjectionReceiver() {
13548        return mBackground != null;
13549    }
13550
13551    /**
13552     * Damage area of the screen that can be covered by this View's shadow.
13553     *
13554     * This method will guarantee that any changes to shadows cast by a View
13555     * are damaged on the screen for future redraw.
13556     */
13557    private void damageShadowReceiver() {
13558        final AttachInfo ai = mAttachInfo;
13559        if (ai != null) {
13560            ViewParent p = getParent();
13561            if (p != null && p instanceof ViewGroup) {
13562                final ViewGroup vg = (ViewGroup) p;
13563                vg.damageInParent();
13564            }
13565        }
13566    }
13567
13568    /**
13569     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13570     * set any flags or handle all of the cases handled by the default invalidation methods.
13571     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13572     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13573     * walk up the hierarchy, transforming the dirty rect as necessary.
13574     *
13575     * The method also handles normal invalidation logic if display list properties are not
13576     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13577     * backup approach, to handle these cases used in the various property-setting methods.
13578     *
13579     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13580     * are not being used in this view
13581     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13582     * list properties are not being used in this view
13583     */
13584    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13585        if (!isHardwareAccelerated()
13586                || !mRenderNode.isValid()
13587                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13588            if (invalidateParent) {
13589                invalidateParentCaches();
13590            }
13591            if (forceRedraw) {
13592                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13593            }
13594            invalidate(false);
13595        } else {
13596            damageInParent();
13597        }
13598        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13599            damageShadowReceiver();
13600        }
13601    }
13602
13603    /**
13604     * Tells the parent view to damage this view's bounds.
13605     *
13606     * @hide
13607     */
13608    protected void damageInParent() {
13609        final AttachInfo ai = mAttachInfo;
13610        final ViewParent p = mParent;
13611        if (p != null && ai != null) {
13612            final Rect r = ai.mTmpInvalRect;
13613            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13614            if (mParent instanceof ViewGroup) {
13615                ((ViewGroup) mParent).damageChild(this, r);
13616            } else {
13617                mParent.invalidateChild(this, r);
13618            }
13619        }
13620    }
13621
13622    /**
13623     * Utility method to transform a given Rect by the current matrix of this view.
13624     */
13625    void transformRect(final Rect rect) {
13626        if (!getMatrix().isIdentity()) {
13627            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13628            boundingRect.set(rect);
13629            getMatrix().mapRect(boundingRect);
13630            rect.set((int) Math.floor(boundingRect.left),
13631                    (int) Math.floor(boundingRect.top),
13632                    (int) Math.ceil(boundingRect.right),
13633                    (int) Math.ceil(boundingRect.bottom));
13634        }
13635    }
13636
13637    /**
13638     * Used to indicate that the parent of this view should clear its caches. This functionality
13639     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13640     * which is necessary when various parent-managed properties of the view change, such as
13641     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13642     * clears the parent caches and does not causes an invalidate event.
13643     *
13644     * @hide
13645     */
13646    protected void invalidateParentCaches() {
13647        if (mParent instanceof View) {
13648            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13649        }
13650    }
13651
13652    /**
13653     * Used to indicate that the parent of this view should be invalidated. This functionality
13654     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13655     * which is necessary when various parent-managed properties of the view change, such as
13656     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13657     * an invalidation event to the parent.
13658     *
13659     * @hide
13660     */
13661    protected void invalidateParentIfNeeded() {
13662        if (isHardwareAccelerated() && mParent instanceof View) {
13663            ((View) mParent).invalidate(true);
13664        }
13665    }
13666
13667    /**
13668     * @hide
13669     */
13670    protected void invalidateParentIfNeededAndWasQuickRejected() {
13671        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13672            // View was rejected last time it was drawn by its parent; this may have changed
13673            invalidateParentIfNeeded();
13674        }
13675    }
13676
13677    /**
13678     * Indicates whether this View is opaque. An opaque View guarantees that it will
13679     * draw all the pixels overlapping its bounds using a fully opaque color.
13680     *
13681     * Subclasses of View should override this method whenever possible to indicate
13682     * whether an instance is opaque. Opaque Views are treated in a special way by
13683     * the View hierarchy, possibly allowing it to perform optimizations during
13684     * invalidate/draw passes.
13685     *
13686     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13687     */
13688    @ViewDebug.ExportedProperty(category = "drawing")
13689    public boolean isOpaque() {
13690        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13691                getFinalAlpha() >= 1.0f;
13692    }
13693
13694    /**
13695     * @hide
13696     */
13697    protected void computeOpaqueFlags() {
13698        // Opaque if:
13699        //   - Has a background
13700        //   - Background is opaque
13701        //   - Doesn't have scrollbars or scrollbars overlay
13702
13703        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13704            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13705        } else {
13706            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13707        }
13708
13709        final int flags = mViewFlags;
13710        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13711                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13712                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13713            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13714        } else {
13715            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13716        }
13717    }
13718
13719    /**
13720     * @hide
13721     */
13722    protected boolean hasOpaqueScrollbars() {
13723        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13724    }
13725
13726    /**
13727     * @return A handler associated with the thread running the View. This
13728     * handler can be used to pump events in the UI events queue.
13729     */
13730    public Handler getHandler() {
13731        final AttachInfo attachInfo = mAttachInfo;
13732        if (attachInfo != null) {
13733            return attachInfo.mHandler;
13734        }
13735        return null;
13736    }
13737
13738    /**
13739     * Returns the queue of runnable for this view.
13740     *
13741     * @return the queue of runnables for this view
13742     */
13743    private HandlerActionQueue getRunQueue() {
13744        if (mRunQueue == null) {
13745            mRunQueue = new HandlerActionQueue();
13746        }
13747        return mRunQueue;
13748    }
13749
13750    /**
13751     * Gets the view root associated with the View.
13752     * @return The view root, or null if none.
13753     * @hide
13754     */
13755    public ViewRootImpl getViewRootImpl() {
13756        if (mAttachInfo != null) {
13757            return mAttachInfo.mViewRootImpl;
13758        }
13759        return null;
13760    }
13761
13762    /**
13763     * @hide
13764     */
13765    public ThreadedRenderer getHardwareRenderer() {
13766        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
13767    }
13768
13769    /**
13770     * <p>Causes the Runnable to be added to the message queue.
13771     * The runnable will be run on the user interface thread.</p>
13772     *
13773     * @param action The Runnable that will be executed.
13774     *
13775     * @return Returns true if the Runnable was successfully placed in to the
13776     *         message queue.  Returns false on failure, usually because the
13777     *         looper processing the message queue is exiting.
13778     *
13779     * @see #postDelayed
13780     * @see #removeCallbacks
13781     */
13782    public boolean post(Runnable action) {
13783        final AttachInfo attachInfo = mAttachInfo;
13784        if (attachInfo != null) {
13785            return attachInfo.mHandler.post(action);
13786        }
13787
13788        // Postpone the runnable until we know on which thread it needs to run.
13789        // Assume that the runnable will be successfully placed after attach.
13790        getRunQueue().post(action);
13791        return true;
13792    }
13793
13794    /**
13795     * <p>Causes the Runnable to be added to the message queue, to be run
13796     * after the specified amount of time elapses.
13797     * The runnable will be run on the user interface thread.</p>
13798     *
13799     * @param action The Runnable that will be executed.
13800     * @param delayMillis The delay (in milliseconds) until the Runnable
13801     *        will be executed.
13802     *
13803     * @return true if the Runnable was successfully placed in to the
13804     *         message queue.  Returns false on failure, usually because the
13805     *         looper processing the message queue is exiting.  Note that a
13806     *         result of true does not mean the Runnable will be processed --
13807     *         if the looper is quit before the delivery time of the message
13808     *         occurs then the message will be dropped.
13809     *
13810     * @see #post
13811     * @see #removeCallbacks
13812     */
13813    public boolean postDelayed(Runnable action, long delayMillis) {
13814        final AttachInfo attachInfo = mAttachInfo;
13815        if (attachInfo != null) {
13816            return attachInfo.mHandler.postDelayed(action, delayMillis);
13817        }
13818
13819        // Postpone the runnable until we know on which thread it needs to run.
13820        // Assume that the runnable will be successfully placed after attach.
13821        getRunQueue().postDelayed(action, delayMillis);
13822        return true;
13823    }
13824
13825    /**
13826     * <p>Causes the Runnable to execute on the next animation time step.
13827     * The runnable will be run on the user interface thread.</p>
13828     *
13829     * @param action The Runnable that will be executed.
13830     *
13831     * @see #postOnAnimationDelayed
13832     * @see #removeCallbacks
13833     */
13834    public void postOnAnimation(Runnable action) {
13835        final AttachInfo attachInfo = mAttachInfo;
13836        if (attachInfo != null) {
13837            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13838                    Choreographer.CALLBACK_ANIMATION, action, null);
13839        } else {
13840            // Postpone the runnable until we know
13841            // on which thread it needs to run.
13842            getRunQueue().post(action);
13843        }
13844    }
13845
13846    /**
13847     * <p>Causes the Runnable to execute on the next animation time step,
13848     * after the specified amount of time elapses.
13849     * The runnable will be run on the user interface thread.</p>
13850     *
13851     * @param action The Runnable that will be executed.
13852     * @param delayMillis The delay (in milliseconds) until the Runnable
13853     *        will be executed.
13854     *
13855     * @see #postOnAnimation
13856     * @see #removeCallbacks
13857     */
13858    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13859        final AttachInfo attachInfo = mAttachInfo;
13860        if (attachInfo != null) {
13861            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13862                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13863        } else {
13864            // Postpone the runnable until we know
13865            // on which thread it needs to run.
13866            getRunQueue().postDelayed(action, delayMillis);
13867        }
13868    }
13869
13870    /**
13871     * <p>Removes the specified Runnable from the message queue.</p>
13872     *
13873     * @param action The Runnable to remove from the message handling queue
13874     *
13875     * @return true if this view could ask the Handler to remove the Runnable,
13876     *         false otherwise. When the returned value is true, the Runnable
13877     *         may or may not have been actually removed from the message queue
13878     *         (for instance, if the Runnable was not in the queue already.)
13879     *
13880     * @see #post
13881     * @see #postDelayed
13882     * @see #postOnAnimation
13883     * @see #postOnAnimationDelayed
13884     */
13885    public boolean removeCallbacks(Runnable action) {
13886        if (action != null) {
13887            final AttachInfo attachInfo = mAttachInfo;
13888            if (attachInfo != null) {
13889                attachInfo.mHandler.removeCallbacks(action);
13890                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13891                        Choreographer.CALLBACK_ANIMATION, action, null);
13892            }
13893            getRunQueue().removeCallbacks(action);
13894        }
13895        return true;
13896    }
13897
13898    /**
13899     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13900     * Use this to invalidate the View from a non-UI thread.</p>
13901     *
13902     * <p>This method can be invoked from outside of the UI thread
13903     * only when this View is attached to a window.</p>
13904     *
13905     * @see #invalidate()
13906     * @see #postInvalidateDelayed(long)
13907     */
13908    public void postInvalidate() {
13909        postInvalidateDelayed(0);
13910    }
13911
13912    /**
13913     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13914     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13915     *
13916     * <p>This method can be invoked from outside of the UI thread
13917     * only when this View is attached to a window.</p>
13918     *
13919     * @param left The left coordinate of the rectangle to invalidate.
13920     * @param top The top coordinate of the rectangle to invalidate.
13921     * @param right The right coordinate of the rectangle to invalidate.
13922     * @param bottom The bottom coordinate of the rectangle to invalidate.
13923     *
13924     * @see #invalidate(int, int, int, int)
13925     * @see #invalidate(Rect)
13926     * @see #postInvalidateDelayed(long, int, int, int, int)
13927     */
13928    public void postInvalidate(int left, int top, int right, int bottom) {
13929        postInvalidateDelayed(0, left, top, right, bottom);
13930    }
13931
13932    /**
13933     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13934     * loop. Waits for the specified amount of time.</p>
13935     *
13936     * <p>This method can be invoked from outside of the UI thread
13937     * only when this View is attached to a window.</p>
13938     *
13939     * @param delayMilliseconds the duration in milliseconds to delay the
13940     *         invalidation by
13941     *
13942     * @see #invalidate()
13943     * @see #postInvalidate()
13944     */
13945    public void postInvalidateDelayed(long delayMilliseconds) {
13946        // We try only with the AttachInfo because there's no point in invalidating
13947        // if we are not attached to our window
13948        final AttachInfo attachInfo = mAttachInfo;
13949        if (attachInfo != null) {
13950            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
13951        }
13952    }
13953
13954    /**
13955     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13956     * through the event loop. Waits for the specified amount of time.</p>
13957     *
13958     * <p>This method can be invoked from outside of the UI thread
13959     * only when this View is attached to a window.</p>
13960     *
13961     * @param delayMilliseconds the duration in milliseconds to delay the
13962     *         invalidation by
13963     * @param left The left coordinate of the rectangle to invalidate.
13964     * @param top The top coordinate of the rectangle to invalidate.
13965     * @param right The right coordinate of the rectangle to invalidate.
13966     * @param bottom The bottom coordinate of the rectangle to invalidate.
13967     *
13968     * @see #invalidate(int, int, int, int)
13969     * @see #invalidate(Rect)
13970     * @see #postInvalidate(int, int, int, int)
13971     */
13972    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
13973            int right, int bottom) {
13974
13975        // We try only with the AttachInfo because there's no point in invalidating
13976        // if we are not attached to our window
13977        final AttachInfo attachInfo = mAttachInfo;
13978        if (attachInfo != null) {
13979            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
13980            info.target = this;
13981            info.left = left;
13982            info.top = top;
13983            info.right = right;
13984            info.bottom = bottom;
13985
13986            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
13987        }
13988    }
13989
13990    /**
13991     * <p>Cause an invalidate to happen on the next animation time step, typically the
13992     * next display frame.</p>
13993     *
13994     * <p>This method can be invoked from outside of the UI thread
13995     * only when this View is attached to a window.</p>
13996     *
13997     * @see #invalidate()
13998     */
13999    public void postInvalidateOnAnimation() {
14000        // We try only with the AttachInfo because there's no point in invalidating
14001        // if we are not attached to our window
14002        final AttachInfo attachInfo = mAttachInfo;
14003        if (attachInfo != null) {
14004            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14005        }
14006    }
14007
14008    /**
14009     * <p>Cause an invalidate of the specified area to happen on the next animation
14010     * time step, typically the next display frame.</p>
14011     *
14012     * <p>This method can be invoked from outside of the UI thread
14013     * only when this View is attached to a window.</p>
14014     *
14015     * @param left The left coordinate of the rectangle to invalidate.
14016     * @param top The top coordinate of the rectangle to invalidate.
14017     * @param right The right coordinate of the rectangle to invalidate.
14018     * @param bottom The bottom coordinate of the rectangle to invalidate.
14019     *
14020     * @see #invalidate(int, int, int, int)
14021     * @see #invalidate(Rect)
14022     */
14023    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14024        // We try only with the AttachInfo because there's no point in invalidating
14025        // if we are not attached to our window
14026        final AttachInfo attachInfo = mAttachInfo;
14027        if (attachInfo != null) {
14028            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14029            info.target = this;
14030            info.left = left;
14031            info.top = top;
14032            info.right = right;
14033            info.bottom = bottom;
14034
14035            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14036        }
14037    }
14038
14039    /**
14040     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14041     * This event is sent at most once every
14042     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14043     */
14044    private void postSendViewScrolledAccessibilityEventCallback() {
14045        if (mSendViewScrolledAccessibilityEvent == null) {
14046            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14047        }
14048        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14049            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14050            postDelayed(mSendViewScrolledAccessibilityEvent,
14051                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14052        }
14053    }
14054
14055    /**
14056     * Called by a parent to request that a child update its values for mScrollX
14057     * and mScrollY if necessary. This will typically be done if the child is
14058     * animating a scroll using a {@link android.widget.Scroller Scroller}
14059     * object.
14060     */
14061    public void computeScroll() {
14062    }
14063
14064    /**
14065     * <p>Indicate whether the horizontal edges are faded when the view is
14066     * scrolled horizontally.</p>
14067     *
14068     * @return true if the horizontal edges should are faded on scroll, false
14069     *         otherwise
14070     *
14071     * @see #setHorizontalFadingEdgeEnabled(boolean)
14072     *
14073     * @attr ref android.R.styleable#View_requiresFadingEdge
14074     */
14075    public boolean isHorizontalFadingEdgeEnabled() {
14076        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14077    }
14078
14079    /**
14080     * <p>Define whether the horizontal edges should be faded when this view
14081     * is scrolled horizontally.</p>
14082     *
14083     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14084     *                                    be faded when the view is scrolled
14085     *                                    horizontally
14086     *
14087     * @see #isHorizontalFadingEdgeEnabled()
14088     *
14089     * @attr ref android.R.styleable#View_requiresFadingEdge
14090     */
14091    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14092        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14093            if (horizontalFadingEdgeEnabled) {
14094                initScrollCache();
14095            }
14096
14097            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14098        }
14099    }
14100
14101    /**
14102     * <p>Indicate whether the vertical edges are faded when the view is
14103     * scrolled horizontally.</p>
14104     *
14105     * @return true if the vertical edges should are faded on scroll, false
14106     *         otherwise
14107     *
14108     * @see #setVerticalFadingEdgeEnabled(boolean)
14109     *
14110     * @attr ref android.R.styleable#View_requiresFadingEdge
14111     */
14112    public boolean isVerticalFadingEdgeEnabled() {
14113        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14114    }
14115
14116    /**
14117     * <p>Define whether the vertical edges should be faded when this view
14118     * is scrolled vertically.</p>
14119     *
14120     * @param verticalFadingEdgeEnabled true if the vertical edges should
14121     *                                  be faded when the view is scrolled
14122     *                                  vertically
14123     *
14124     * @see #isVerticalFadingEdgeEnabled()
14125     *
14126     * @attr ref android.R.styleable#View_requiresFadingEdge
14127     */
14128    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14129        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14130            if (verticalFadingEdgeEnabled) {
14131                initScrollCache();
14132            }
14133
14134            mViewFlags ^= FADING_EDGE_VERTICAL;
14135        }
14136    }
14137
14138    /**
14139     * Returns the strength, or intensity, of the top faded edge. The strength is
14140     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14141     * returns 0.0 or 1.0 but no value in between.
14142     *
14143     * Subclasses should override this method to provide a smoother fade transition
14144     * when scrolling occurs.
14145     *
14146     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14147     */
14148    protected float getTopFadingEdgeStrength() {
14149        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14150    }
14151
14152    /**
14153     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14154     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14155     * returns 0.0 or 1.0 but no value in between.
14156     *
14157     * Subclasses should override this method to provide a smoother fade transition
14158     * when scrolling occurs.
14159     *
14160     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14161     */
14162    protected float getBottomFadingEdgeStrength() {
14163        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14164                computeVerticalScrollRange() ? 1.0f : 0.0f;
14165    }
14166
14167    /**
14168     * Returns the strength, or intensity, of the left faded edge. The strength is
14169     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14170     * returns 0.0 or 1.0 but no value in between.
14171     *
14172     * Subclasses should override this method to provide a smoother fade transition
14173     * when scrolling occurs.
14174     *
14175     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14176     */
14177    protected float getLeftFadingEdgeStrength() {
14178        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14179    }
14180
14181    /**
14182     * Returns the strength, or intensity, of the right faded edge. The strength is
14183     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14184     * returns 0.0 or 1.0 but no value in between.
14185     *
14186     * Subclasses should override this method to provide a smoother fade transition
14187     * when scrolling occurs.
14188     *
14189     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14190     */
14191    protected float getRightFadingEdgeStrength() {
14192        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14193                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14194    }
14195
14196    /**
14197     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14198     * scrollbar is not drawn by default.</p>
14199     *
14200     * @return true if the horizontal scrollbar should be painted, false
14201     *         otherwise
14202     *
14203     * @see #setHorizontalScrollBarEnabled(boolean)
14204     */
14205    public boolean isHorizontalScrollBarEnabled() {
14206        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14207    }
14208
14209    /**
14210     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14211     * scrollbar is not drawn by default.</p>
14212     *
14213     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14214     *                                   be painted
14215     *
14216     * @see #isHorizontalScrollBarEnabled()
14217     */
14218    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14219        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14220            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14221            computeOpaqueFlags();
14222            resolvePadding();
14223        }
14224    }
14225
14226    /**
14227     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14228     * scrollbar is not drawn by default.</p>
14229     *
14230     * @return true if the vertical scrollbar should be painted, false
14231     *         otherwise
14232     *
14233     * @see #setVerticalScrollBarEnabled(boolean)
14234     */
14235    public boolean isVerticalScrollBarEnabled() {
14236        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14237    }
14238
14239    /**
14240     * <p>Define whether the vertical scrollbar should be drawn or not. The
14241     * scrollbar is not drawn by default.</p>
14242     *
14243     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14244     *                                 be painted
14245     *
14246     * @see #isVerticalScrollBarEnabled()
14247     */
14248    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14249        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14250            mViewFlags ^= SCROLLBARS_VERTICAL;
14251            computeOpaqueFlags();
14252            resolvePadding();
14253        }
14254    }
14255
14256    /**
14257     * @hide
14258     */
14259    protected void recomputePadding() {
14260        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14261    }
14262
14263    /**
14264     * Define whether scrollbars will fade when the view is not scrolling.
14265     *
14266     * @param fadeScrollbars whether to enable fading
14267     *
14268     * @attr ref android.R.styleable#View_fadeScrollbars
14269     */
14270    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14271        initScrollCache();
14272        final ScrollabilityCache scrollabilityCache = mScrollCache;
14273        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14274        if (fadeScrollbars) {
14275            scrollabilityCache.state = ScrollabilityCache.OFF;
14276        } else {
14277            scrollabilityCache.state = ScrollabilityCache.ON;
14278        }
14279    }
14280
14281    /**
14282     *
14283     * Returns true if scrollbars will fade when this view is not scrolling
14284     *
14285     * @return true if scrollbar fading is enabled
14286     *
14287     * @attr ref android.R.styleable#View_fadeScrollbars
14288     */
14289    public boolean isScrollbarFadingEnabled() {
14290        return mScrollCache != null && mScrollCache.fadeScrollBars;
14291    }
14292
14293    /**
14294     *
14295     * Returns the delay before scrollbars fade.
14296     *
14297     * @return the delay before scrollbars fade
14298     *
14299     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14300     */
14301    public int getScrollBarDefaultDelayBeforeFade() {
14302        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14303                mScrollCache.scrollBarDefaultDelayBeforeFade;
14304    }
14305
14306    /**
14307     * Define the delay before scrollbars fade.
14308     *
14309     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14310     *
14311     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14312     */
14313    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14314        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14315    }
14316
14317    /**
14318     *
14319     * Returns the scrollbar fade duration.
14320     *
14321     * @return the scrollbar fade duration
14322     *
14323     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14324     */
14325    public int getScrollBarFadeDuration() {
14326        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14327                mScrollCache.scrollBarFadeDuration;
14328    }
14329
14330    /**
14331     * Define the scrollbar fade duration.
14332     *
14333     * @param scrollBarFadeDuration - the scrollbar fade duration
14334     *
14335     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14336     */
14337    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14338        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14339    }
14340
14341    /**
14342     *
14343     * Returns the scrollbar size.
14344     *
14345     * @return the scrollbar size
14346     *
14347     * @attr ref android.R.styleable#View_scrollbarSize
14348     */
14349    public int getScrollBarSize() {
14350        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14351                mScrollCache.scrollBarSize;
14352    }
14353
14354    /**
14355     * Define the scrollbar size.
14356     *
14357     * @param scrollBarSize - the scrollbar size
14358     *
14359     * @attr ref android.R.styleable#View_scrollbarSize
14360     */
14361    public void setScrollBarSize(int scrollBarSize) {
14362        getScrollCache().scrollBarSize = scrollBarSize;
14363    }
14364
14365    /**
14366     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14367     * inset. When inset, they add to the padding of the view. And the scrollbars
14368     * can be drawn inside the padding area or on the edge of the view. For example,
14369     * if a view has a background drawable and you want to draw the scrollbars
14370     * inside the padding specified by the drawable, you can use
14371     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14372     * appear at the edge of the view, ignoring the padding, then you can use
14373     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14374     * @param style the style of the scrollbars. Should be one of
14375     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14376     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14377     * @see #SCROLLBARS_INSIDE_OVERLAY
14378     * @see #SCROLLBARS_INSIDE_INSET
14379     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14380     * @see #SCROLLBARS_OUTSIDE_INSET
14381     *
14382     * @attr ref android.R.styleable#View_scrollbarStyle
14383     */
14384    public void setScrollBarStyle(@ScrollBarStyle int style) {
14385        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14386            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14387            computeOpaqueFlags();
14388            resolvePadding();
14389        }
14390    }
14391
14392    /**
14393     * <p>Returns the current scrollbar style.</p>
14394     * @return the current scrollbar style
14395     * @see #SCROLLBARS_INSIDE_OVERLAY
14396     * @see #SCROLLBARS_INSIDE_INSET
14397     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14398     * @see #SCROLLBARS_OUTSIDE_INSET
14399     *
14400     * @attr ref android.R.styleable#View_scrollbarStyle
14401     */
14402    @ViewDebug.ExportedProperty(mapping = {
14403            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14404            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14405            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14406            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14407    })
14408    @ScrollBarStyle
14409    public int getScrollBarStyle() {
14410        return mViewFlags & SCROLLBARS_STYLE_MASK;
14411    }
14412
14413    /**
14414     * <p>Compute the horizontal range that the horizontal scrollbar
14415     * represents.</p>
14416     *
14417     * <p>The range is expressed in arbitrary units that must be the same as the
14418     * units used by {@link #computeHorizontalScrollExtent()} and
14419     * {@link #computeHorizontalScrollOffset()}.</p>
14420     *
14421     * <p>The default range is the drawing width of this view.</p>
14422     *
14423     * @return the total horizontal range represented by the horizontal
14424     *         scrollbar
14425     *
14426     * @see #computeHorizontalScrollExtent()
14427     * @see #computeHorizontalScrollOffset()
14428     * @see android.widget.ScrollBarDrawable
14429     */
14430    protected int computeHorizontalScrollRange() {
14431        return getWidth();
14432    }
14433
14434    /**
14435     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14436     * within the horizontal range. This value is used to compute the position
14437     * of the thumb within the scrollbar's track.</p>
14438     *
14439     * <p>The range is expressed in arbitrary units that must be the same as the
14440     * units used by {@link #computeHorizontalScrollRange()} and
14441     * {@link #computeHorizontalScrollExtent()}.</p>
14442     *
14443     * <p>The default offset is the scroll offset of this view.</p>
14444     *
14445     * @return the horizontal offset of the scrollbar's thumb
14446     *
14447     * @see #computeHorizontalScrollRange()
14448     * @see #computeHorizontalScrollExtent()
14449     * @see android.widget.ScrollBarDrawable
14450     */
14451    protected int computeHorizontalScrollOffset() {
14452        return mScrollX;
14453    }
14454
14455    /**
14456     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14457     * within the horizontal range. This value is used to compute the length
14458     * of the thumb within the scrollbar's track.</p>
14459     *
14460     * <p>The range is expressed in arbitrary units that must be the same as the
14461     * units used by {@link #computeHorizontalScrollRange()} and
14462     * {@link #computeHorizontalScrollOffset()}.</p>
14463     *
14464     * <p>The default extent is the drawing width of this view.</p>
14465     *
14466     * @return the horizontal extent of the scrollbar's thumb
14467     *
14468     * @see #computeHorizontalScrollRange()
14469     * @see #computeHorizontalScrollOffset()
14470     * @see android.widget.ScrollBarDrawable
14471     */
14472    protected int computeHorizontalScrollExtent() {
14473        return getWidth();
14474    }
14475
14476    /**
14477     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14478     *
14479     * <p>The range is expressed in arbitrary units that must be the same as the
14480     * units used by {@link #computeVerticalScrollExtent()} and
14481     * {@link #computeVerticalScrollOffset()}.</p>
14482     *
14483     * @return the total vertical range represented by the vertical scrollbar
14484     *
14485     * <p>The default range is the drawing height of this view.</p>
14486     *
14487     * @see #computeVerticalScrollExtent()
14488     * @see #computeVerticalScrollOffset()
14489     * @see android.widget.ScrollBarDrawable
14490     */
14491    protected int computeVerticalScrollRange() {
14492        return getHeight();
14493    }
14494
14495    /**
14496     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14497     * within the horizontal range. This value is used to compute the position
14498     * of the thumb within the scrollbar's track.</p>
14499     *
14500     * <p>The range is expressed in arbitrary units that must be the same as the
14501     * units used by {@link #computeVerticalScrollRange()} and
14502     * {@link #computeVerticalScrollExtent()}.</p>
14503     *
14504     * <p>The default offset is the scroll offset of this view.</p>
14505     *
14506     * @return the vertical offset of the scrollbar's thumb
14507     *
14508     * @see #computeVerticalScrollRange()
14509     * @see #computeVerticalScrollExtent()
14510     * @see android.widget.ScrollBarDrawable
14511     */
14512    protected int computeVerticalScrollOffset() {
14513        return mScrollY;
14514    }
14515
14516    /**
14517     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14518     * within the vertical range. This value is used to compute the length
14519     * of the thumb within the scrollbar's track.</p>
14520     *
14521     * <p>The range is expressed in arbitrary units that must be the same as the
14522     * units used by {@link #computeVerticalScrollRange()} and
14523     * {@link #computeVerticalScrollOffset()}.</p>
14524     *
14525     * <p>The default extent is the drawing height of this view.</p>
14526     *
14527     * @return the vertical extent of the scrollbar's thumb
14528     *
14529     * @see #computeVerticalScrollRange()
14530     * @see #computeVerticalScrollOffset()
14531     * @see android.widget.ScrollBarDrawable
14532     */
14533    protected int computeVerticalScrollExtent() {
14534        return getHeight();
14535    }
14536
14537    /**
14538     * Check if this view can be scrolled horizontally in a certain direction.
14539     *
14540     * @param direction Negative to check scrolling left, positive to check scrolling right.
14541     * @return true if this view can be scrolled in the specified direction, false otherwise.
14542     */
14543    public boolean canScrollHorizontally(int direction) {
14544        final int offset = computeHorizontalScrollOffset();
14545        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14546        if (range == 0) return false;
14547        if (direction < 0) {
14548            return offset > 0;
14549        } else {
14550            return offset < range - 1;
14551        }
14552    }
14553
14554    /**
14555     * Check if this view can be scrolled vertically in a certain direction.
14556     *
14557     * @param direction Negative to check scrolling up, positive to check scrolling down.
14558     * @return true if this view can be scrolled in the specified direction, false otherwise.
14559     */
14560    public boolean canScrollVertically(int direction) {
14561        final int offset = computeVerticalScrollOffset();
14562        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14563        if (range == 0) return false;
14564        if (direction < 0) {
14565            return offset > 0;
14566        } else {
14567            return offset < range - 1;
14568        }
14569    }
14570
14571    void getScrollIndicatorBounds(@NonNull Rect out) {
14572        out.left = mScrollX;
14573        out.right = mScrollX + mRight - mLeft;
14574        out.top = mScrollY;
14575        out.bottom = mScrollY + mBottom - mTop;
14576    }
14577
14578    private void onDrawScrollIndicators(Canvas c) {
14579        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14580            // No scroll indicators enabled.
14581            return;
14582        }
14583
14584        final Drawable dr = mScrollIndicatorDrawable;
14585        if (dr == null) {
14586            // Scroll indicators aren't supported here.
14587            return;
14588        }
14589
14590        final int h = dr.getIntrinsicHeight();
14591        final int w = dr.getIntrinsicWidth();
14592        final Rect rect = mAttachInfo.mTmpInvalRect;
14593        getScrollIndicatorBounds(rect);
14594
14595        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14596            final boolean canScrollUp = canScrollVertically(-1);
14597            if (canScrollUp) {
14598                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14599                dr.draw(c);
14600            }
14601        }
14602
14603        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14604            final boolean canScrollDown = canScrollVertically(1);
14605            if (canScrollDown) {
14606                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14607                dr.draw(c);
14608            }
14609        }
14610
14611        final int leftRtl;
14612        final int rightRtl;
14613        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14614            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14615            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14616        } else {
14617            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14618            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14619        }
14620
14621        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14622        if ((mPrivateFlags3 & leftMask) != 0) {
14623            final boolean canScrollLeft = canScrollHorizontally(-1);
14624            if (canScrollLeft) {
14625                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14626                dr.draw(c);
14627            }
14628        }
14629
14630        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14631        if ((mPrivateFlags3 & rightMask) != 0) {
14632            final boolean canScrollRight = canScrollHorizontally(1);
14633            if (canScrollRight) {
14634                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14635                dr.draw(c);
14636            }
14637        }
14638    }
14639
14640    private void getHorizontalScrollBarBounds(Rect bounds) {
14641        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14642        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14643                && !isVerticalScrollBarHidden();
14644        final int size = getHorizontalScrollbarHeight();
14645        final int verticalScrollBarGap = drawVerticalScrollBar ?
14646                getVerticalScrollbarWidth() : 0;
14647        final int width = mRight - mLeft;
14648        final int height = mBottom - mTop;
14649        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14650        bounds.left = mScrollX + (mPaddingLeft & inside);
14651        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14652        bounds.bottom = bounds.top + size;
14653    }
14654
14655    private void getVerticalScrollBarBounds(Rect bounds) {
14656        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14657        final int size = getVerticalScrollbarWidth();
14658        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14659        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14660            verticalScrollbarPosition = isLayoutRtl() ?
14661                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14662        }
14663        final int width = mRight - mLeft;
14664        final int height = mBottom - mTop;
14665        switch (verticalScrollbarPosition) {
14666            default:
14667            case SCROLLBAR_POSITION_RIGHT:
14668                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14669                break;
14670            case SCROLLBAR_POSITION_LEFT:
14671                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14672                break;
14673        }
14674        bounds.top = mScrollY + (mPaddingTop & inside);
14675        bounds.right = bounds.left + size;
14676        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14677    }
14678
14679    /**
14680     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14681     * scrollbars are painted only if they have been awakened first.</p>
14682     *
14683     * @param canvas the canvas on which to draw the scrollbars
14684     *
14685     * @see #awakenScrollBars(int)
14686     */
14687    protected final void onDrawScrollBars(Canvas canvas) {
14688        // scrollbars are drawn only when the animation is running
14689        final ScrollabilityCache cache = mScrollCache;
14690        if (cache != null) {
14691
14692            int state = cache.state;
14693
14694            if (state == ScrollabilityCache.OFF) {
14695                return;
14696            }
14697
14698            boolean invalidate = false;
14699
14700            if (state == ScrollabilityCache.FADING) {
14701                // We're fading -- get our fade interpolation
14702                if (cache.interpolatorValues == null) {
14703                    cache.interpolatorValues = new float[1];
14704                }
14705
14706                float[] values = cache.interpolatorValues;
14707
14708                // Stops the animation if we're done
14709                if (cache.scrollBarInterpolator.timeToValues(values) ==
14710                        Interpolator.Result.FREEZE_END) {
14711                    cache.state = ScrollabilityCache.OFF;
14712                } else {
14713                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14714                }
14715
14716                // This will make the scroll bars inval themselves after
14717                // drawing. We only want this when we're fading so that
14718                // we prevent excessive redraws
14719                invalidate = true;
14720            } else {
14721                // We're just on -- but we may have been fading before so
14722                // reset alpha
14723                cache.scrollBar.mutate().setAlpha(255);
14724            }
14725
14726            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14727            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14728                    && !isVerticalScrollBarHidden();
14729
14730            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14731                final ScrollBarDrawable scrollBar = cache.scrollBar;
14732
14733                if (drawHorizontalScrollBar) {
14734                    scrollBar.setParameters(computeHorizontalScrollRange(),
14735                                            computeHorizontalScrollOffset(),
14736                                            computeHorizontalScrollExtent(), false);
14737                    final Rect bounds = cache.mScrollBarBounds;
14738                    getHorizontalScrollBarBounds(bounds);
14739                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14740                            bounds.right, bounds.bottom);
14741                    if (invalidate) {
14742                        invalidate(bounds);
14743                    }
14744                }
14745
14746                if (drawVerticalScrollBar) {
14747                    scrollBar.setParameters(computeVerticalScrollRange(),
14748                                            computeVerticalScrollOffset(),
14749                                            computeVerticalScrollExtent(), true);
14750                    final Rect bounds = cache.mScrollBarBounds;
14751                    getVerticalScrollBarBounds(bounds);
14752                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14753                            bounds.right, bounds.bottom);
14754                    if (invalidate) {
14755                        invalidate(bounds);
14756                    }
14757                }
14758            }
14759        }
14760    }
14761
14762    /**
14763     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14764     * FastScroller is visible.
14765     * @return whether to temporarily hide the vertical scrollbar
14766     * @hide
14767     */
14768    protected boolean isVerticalScrollBarHidden() {
14769        return false;
14770    }
14771
14772    /**
14773     * <p>Draw the horizontal scrollbar if
14774     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14775     *
14776     * @param canvas the canvas on which to draw the scrollbar
14777     * @param scrollBar the scrollbar's drawable
14778     *
14779     * @see #isHorizontalScrollBarEnabled()
14780     * @see #computeHorizontalScrollRange()
14781     * @see #computeHorizontalScrollExtent()
14782     * @see #computeHorizontalScrollOffset()
14783     * @see android.widget.ScrollBarDrawable
14784     * @hide
14785     */
14786    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14787            int l, int t, int r, int b) {
14788        scrollBar.setBounds(l, t, r, b);
14789        scrollBar.draw(canvas);
14790    }
14791
14792    /**
14793     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14794     * returns true.</p>
14795     *
14796     * @param canvas the canvas on which to draw the scrollbar
14797     * @param scrollBar the scrollbar's drawable
14798     *
14799     * @see #isVerticalScrollBarEnabled()
14800     * @see #computeVerticalScrollRange()
14801     * @see #computeVerticalScrollExtent()
14802     * @see #computeVerticalScrollOffset()
14803     * @see android.widget.ScrollBarDrawable
14804     * @hide
14805     */
14806    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14807            int l, int t, int r, int b) {
14808        scrollBar.setBounds(l, t, r, b);
14809        scrollBar.draw(canvas);
14810    }
14811
14812    /**
14813     * Implement this to do your drawing.
14814     *
14815     * @param canvas the canvas on which the background will be drawn
14816     */
14817    protected void onDraw(Canvas canvas) {
14818    }
14819
14820    /*
14821     * Caller is responsible for calling requestLayout if necessary.
14822     * (This allows addViewInLayout to not request a new layout.)
14823     */
14824    void assignParent(ViewParent parent) {
14825        if (mParent == null) {
14826            mParent = parent;
14827        } else if (parent == null) {
14828            mParent = null;
14829        } else {
14830            throw new RuntimeException("view " + this + " being added, but"
14831                    + " it already has a parent");
14832        }
14833    }
14834
14835    /**
14836     * This is called when the view is attached to a window.  At this point it
14837     * has a Surface and will start drawing.  Note that this function is
14838     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14839     * however it may be called any time before the first onDraw -- including
14840     * before or after {@link #onMeasure(int, int)}.
14841     *
14842     * @see #onDetachedFromWindow()
14843     */
14844    @CallSuper
14845    protected void onAttachedToWindow() {
14846        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14847            mParent.requestTransparentRegion(this);
14848        }
14849
14850        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14851
14852        jumpDrawablesToCurrentState();
14853
14854        resetSubtreeAccessibilityStateChanged();
14855
14856        // rebuild, since Outline not maintained while View is detached
14857        rebuildOutline();
14858
14859        if (isFocused()) {
14860            InputMethodManager imm = InputMethodManager.peekInstance();
14861            if (imm != null) {
14862                imm.focusIn(this);
14863            }
14864        }
14865    }
14866
14867    /**
14868     * Resolve all RTL related properties.
14869     *
14870     * @return true if resolution of RTL properties has been done
14871     *
14872     * @hide
14873     */
14874    public boolean resolveRtlPropertiesIfNeeded() {
14875        if (!needRtlPropertiesResolution()) return false;
14876
14877        // Order is important here: LayoutDirection MUST be resolved first
14878        if (!isLayoutDirectionResolved()) {
14879            resolveLayoutDirection();
14880            resolveLayoutParams();
14881        }
14882        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14883        if (!isTextDirectionResolved()) {
14884            resolveTextDirection();
14885        }
14886        if (!isTextAlignmentResolved()) {
14887            resolveTextAlignment();
14888        }
14889        // Should resolve Drawables before Padding because we need the layout direction of the
14890        // Drawable to correctly resolve Padding.
14891        if (!areDrawablesResolved()) {
14892            resolveDrawables();
14893        }
14894        if (!isPaddingResolved()) {
14895            resolvePadding();
14896        }
14897        onRtlPropertiesChanged(getLayoutDirection());
14898        return true;
14899    }
14900
14901    /**
14902     * Reset resolution of all RTL related properties.
14903     *
14904     * @hide
14905     */
14906    public void resetRtlProperties() {
14907        resetResolvedLayoutDirection();
14908        resetResolvedTextDirection();
14909        resetResolvedTextAlignment();
14910        resetResolvedPadding();
14911        resetResolvedDrawables();
14912    }
14913
14914    /**
14915     * @see #onScreenStateChanged(int)
14916     */
14917    void dispatchScreenStateChanged(int screenState) {
14918        onScreenStateChanged(screenState);
14919    }
14920
14921    /**
14922     * This method is called whenever the state of the screen this view is
14923     * attached to changes. A state change will usually occurs when the screen
14924     * turns on or off (whether it happens automatically or the user does it
14925     * manually.)
14926     *
14927     * @param screenState The new state of the screen. Can be either
14928     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14929     */
14930    public void onScreenStateChanged(int screenState) {
14931    }
14932
14933    /**
14934     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
14935     */
14936    private boolean hasRtlSupport() {
14937        return mContext.getApplicationInfo().hasRtlSupport();
14938    }
14939
14940    /**
14941     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
14942     * RTL not supported)
14943     */
14944    private boolean isRtlCompatibilityMode() {
14945        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
14946        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
14947    }
14948
14949    /**
14950     * @return true if RTL properties need resolution.
14951     *
14952     */
14953    private boolean needRtlPropertiesResolution() {
14954        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
14955    }
14956
14957    /**
14958     * Called when any RTL property (layout direction or text direction or text alignment) has
14959     * been changed.
14960     *
14961     * Subclasses need to override this method to take care of cached information that depends on the
14962     * resolved layout direction, or to inform child views that inherit their layout direction.
14963     *
14964     * The default implementation does nothing.
14965     *
14966     * @param layoutDirection the direction of the layout
14967     *
14968     * @see #LAYOUT_DIRECTION_LTR
14969     * @see #LAYOUT_DIRECTION_RTL
14970     */
14971    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
14972    }
14973
14974    /**
14975     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
14976     * that the parent directionality can and will be resolved before its children.
14977     *
14978     * @return true if resolution has been done, false otherwise.
14979     *
14980     * @hide
14981     */
14982    public boolean resolveLayoutDirection() {
14983        // Clear any previous layout direction resolution
14984        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
14985
14986        if (hasRtlSupport()) {
14987            // Set resolved depending on layout direction
14988            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
14989                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
14990                case LAYOUT_DIRECTION_INHERIT:
14991                    // We cannot resolve yet. LTR is by default and let the resolution happen again
14992                    // later to get the correct resolved value
14993                    if (!canResolveLayoutDirection()) return false;
14994
14995                    // Parent has not yet resolved, LTR is still the default
14996                    try {
14997                        if (!mParent.isLayoutDirectionResolved()) return false;
14998
14999                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15000                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15001                        }
15002                    } catch (AbstractMethodError e) {
15003                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15004                                " does not fully implement ViewParent", e);
15005                    }
15006                    break;
15007                case LAYOUT_DIRECTION_RTL:
15008                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15009                    break;
15010                case LAYOUT_DIRECTION_LOCALE:
15011                    if((LAYOUT_DIRECTION_RTL ==
15012                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15013                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15014                    }
15015                    break;
15016                default:
15017                    // Nothing to do, LTR by default
15018            }
15019        }
15020
15021        // Set to resolved
15022        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15023        return true;
15024    }
15025
15026    /**
15027     * Check if layout direction resolution can be done.
15028     *
15029     * @return true if layout direction resolution can be done otherwise return false.
15030     */
15031    public boolean canResolveLayoutDirection() {
15032        switch (getRawLayoutDirection()) {
15033            case LAYOUT_DIRECTION_INHERIT:
15034                if (mParent != null) {
15035                    try {
15036                        return mParent.canResolveLayoutDirection();
15037                    } catch (AbstractMethodError e) {
15038                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15039                                " does not fully implement ViewParent", e);
15040                    }
15041                }
15042                return false;
15043
15044            default:
15045                return true;
15046        }
15047    }
15048
15049    /**
15050     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15051     * {@link #onMeasure(int, int)}.
15052     *
15053     * @hide
15054     */
15055    public void resetResolvedLayoutDirection() {
15056        // Reset the current resolved bits
15057        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15058    }
15059
15060    /**
15061     * @return true if the layout direction is inherited.
15062     *
15063     * @hide
15064     */
15065    public boolean isLayoutDirectionInherited() {
15066        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15067    }
15068
15069    /**
15070     * @return true if layout direction has been resolved.
15071     */
15072    public boolean isLayoutDirectionResolved() {
15073        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15074    }
15075
15076    /**
15077     * Return if padding has been resolved
15078     *
15079     * @hide
15080     */
15081    boolean isPaddingResolved() {
15082        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15083    }
15084
15085    /**
15086     * Resolves padding depending on layout direction, if applicable, and
15087     * recomputes internal padding values to adjust for scroll bars.
15088     *
15089     * @hide
15090     */
15091    public void resolvePadding() {
15092        final int resolvedLayoutDirection = getLayoutDirection();
15093
15094        if (!isRtlCompatibilityMode()) {
15095            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15096            // If start / end padding are defined, they will be resolved (hence overriding) to
15097            // left / right or right / left depending on the resolved layout direction.
15098            // If start / end padding are not defined, use the left / right ones.
15099            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15100                Rect padding = sThreadLocal.get();
15101                if (padding == null) {
15102                    padding = new Rect();
15103                    sThreadLocal.set(padding);
15104                }
15105                mBackground.getPadding(padding);
15106                if (!mLeftPaddingDefined) {
15107                    mUserPaddingLeftInitial = padding.left;
15108                }
15109                if (!mRightPaddingDefined) {
15110                    mUserPaddingRightInitial = padding.right;
15111                }
15112            }
15113            switch (resolvedLayoutDirection) {
15114                case LAYOUT_DIRECTION_RTL:
15115                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15116                        mUserPaddingRight = mUserPaddingStart;
15117                    } else {
15118                        mUserPaddingRight = mUserPaddingRightInitial;
15119                    }
15120                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15121                        mUserPaddingLeft = mUserPaddingEnd;
15122                    } else {
15123                        mUserPaddingLeft = mUserPaddingLeftInitial;
15124                    }
15125                    break;
15126                case LAYOUT_DIRECTION_LTR:
15127                default:
15128                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15129                        mUserPaddingLeft = mUserPaddingStart;
15130                    } else {
15131                        mUserPaddingLeft = mUserPaddingLeftInitial;
15132                    }
15133                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15134                        mUserPaddingRight = mUserPaddingEnd;
15135                    } else {
15136                        mUserPaddingRight = mUserPaddingRightInitial;
15137                    }
15138            }
15139
15140            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15141        }
15142
15143        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15144        onRtlPropertiesChanged(resolvedLayoutDirection);
15145
15146        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15147    }
15148
15149    /**
15150     * Reset the resolved layout direction.
15151     *
15152     * @hide
15153     */
15154    public void resetResolvedPadding() {
15155        resetResolvedPaddingInternal();
15156    }
15157
15158    /**
15159     * Used when we only want to reset *this* view's padding and not trigger overrides
15160     * in ViewGroup that reset children too.
15161     */
15162    void resetResolvedPaddingInternal() {
15163        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15164    }
15165
15166    /**
15167     * This is called when the view is detached from a window.  At this point it
15168     * no longer has a surface for drawing.
15169     *
15170     * @see #onAttachedToWindow()
15171     */
15172    @CallSuper
15173    protected void onDetachedFromWindow() {
15174    }
15175
15176    /**
15177     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15178     * after onDetachedFromWindow().
15179     *
15180     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15181     * The super method should be called at the end of the overridden method to ensure
15182     * subclasses are destroyed first
15183     *
15184     * @hide
15185     */
15186    @CallSuper
15187    protected void onDetachedFromWindowInternal() {
15188        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15189        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15190
15191        removeUnsetPressCallback();
15192        removeLongPressCallback();
15193        removePerformClickCallback();
15194        removeSendViewScrolledAccessibilityEventCallback();
15195        stopNestedScroll();
15196
15197        // Anything that started animating right before detach should already
15198        // be in its final state when re-attached.
15199        jumpDrawablesToCurrentState();
15200
15201        destroyDrawingCache();
15202
15203        cleanupDraw();
15204        releasePointerCapture();
15205        mCurrentAnimation = null;
15206    }
15207
15208    private void cleanupDraw() {
15209        resetDisplayList();
15210        if (mAttachInfo != null) {
15211            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15212        }
15213    }
15214
15215    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15216    }
15217
15218    /**
15219     * @return The number of times this view has been attached to a window
15220     */
15221    protected int getWindowAttachCount() {
15222        return mWindowAttachCount;
15223    }
15224
15225    /**
15226     * Retrieve a unique token identifying the window this view is attached to.
15227     * @return Return the window's token for use in
15228     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15229     */
15230    public IBinder getWindowToken() {
15231        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15232    }
15233
15234    /**
15235     * Retrieve the {@link WindowId} for the window this view is
15236     * currently attached to.
15237     */
15238    public WindowId getWindowId() {
15239        if (mAttachInfo == null) {
15240            return null;
15241        }
15242        if (mAttachInfo.mWindowId == null) {
15243            try {
15244                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15245                        mAttachInfo.mWindowToken);
15246                mAttachInfo.mWindowId = new WindowId(
15247                        mAttachInfo.mIWindowId);
15248            } catch (RemoteException e) {
15249            }
15250        }
15251        return mAttachInfo.mWindowId;
15252    }
15253
15254    /**
15255     * Retrieve a unique token identifying the top-level "real" window of
15256     * the window that this view is attached to.  That is, this is like
15257     * {@link #getWindowToken}, except if the window this view in is a panel
15258     * window (attached to another containing window), then the token of
15259     * the containing window is returned instead.
15260     *
15261     * @return Returns the associated window token, either
15262     * {@link #getWindowToken()} or the containing window's token.
15263     */
15264    public IBinder getApplicationWindowToken() {
15265        AttachInfo ai = mAttachInfo;
15266        if (ai != null) {
15267            IBinder appWindowToken = ai.mPanelParentWindowToken;
15268            if (appWindowToken == null) {
15269                appWindowToken = ai.mWindowToken;
15270            }
15271            return appWindowToken;
15272        }
15273        return null;
15274    }
15275
15276    /**
15277     * Gets the logical display to which the view's window has been attached.
15278     *
15279     * @return The logical display, or null if the view is not currently attached to a window.
15280     */
15281    public Display getDisplay() {
15282        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15283    }
15284
15285    /**
15286     * Retrieve private session object this view hierarchy is using to
15287     * communicate with the window manager.
15288     * @return the session object to communicate with the window manager
15289     */
15290    /*package*/ IWindowSession getWindowSession() {
15291        return mAttachInfo != null ? mAttachInfo.mSession : null;
15292    }
15293
15294    /**
15295     * Return the visibility value of the least visible component passed.
15296     */
15297    int combineVisibility(int vis1, int vis2) {
15298        // This works because VISIBLE < INVISIBLE < GONE.
15299        return Math.max(vis1, vis2);
15300    }
15301
15302    /**
15303     * @param info the {@link android.view.View.AttachInfo} to associated with
15304     *        this view
15305     */
15306    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15307        mAttachInfo = info;
15308        if (mOverlay != null) {
15309            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15310        }
15311        mWindowAttachCount++;
15312        // We will need to evaluate the drawable state at least once.
15313        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15314        if (mFloatingTreeObserver != null) {
15315            info.mTreeObserver.merge(mFloatingTreeObserver);
15316            mFloatingTreeObserver = null;
15317        }
15318
15319        registerPendingFrameMetricsObservers();
15320
15321        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15322            mAttachInfo.mScrollContainers.add(this);
15323            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15324        }
15325        // Transfer all pending runnables.
15326        if (mRunQueue != null) {
15327            mRunQueue.executeActions(info.mHandler);
15328            mRunQueue = null;
15329        }
15330        performCollectViewAttributes(mAttachInfo, visibility);
15331        onAttachedToWindow();
15332
15333        ListenerInfo li = mListenerInfo;
15334        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15335                li != null ? li.mOnAttachStateChangeListeners : null;
15336        if (listeners != null && listeners.size() > 0) {
15337            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15338            // perform the dispatching. The iterator is a safe guard against listeners that
15339            // could mutate the list by calling the various add/remove methods. This prevents
15340            // the array from being modified while we iterate it.
15341            for (OnAttachStateChangeListener listener : listeners) {
15342                listener.onViewAttachedToWindow(this);
15343            }
15344        }
15345
15346        int vis = info.mWindowVisibility;
15347        if (vis != GONE) {
15348            onWindowVisibilityChanged(vis);
15349            if (isShown()) {
15350                // Calling onVisibilityChanged directly here since the subtree will also
15351                // receive dispatchAttachedToWindow and this same call
15352                onVisibilityAggregated(vis == VISIBLE);
15353            }
15354        }
15355
15356        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15357        // As all views in the subtree will already receive dispatchAttachedToWindow
15358        // traversing the subtree again here is not desired.
15359        onVisibilityChanged(this, visibility);
15360
15361        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15362            // If nobody has evaluated the drawable state yet, then do it now.
15363            refreshDrawableState();
15364        }
15365        needGlobalAttributesUpdate(false);
15366    }
15367
15368    void dispatchDetachedFromWindow() {
15369        AttachInfo info = mAttachInfo;
15370        if (info != null) {
15371            int vis = info.mWindowVisibility;
15372            if (vis != GONE) {
15373                onWindowVisibilityChanged(GONE);
15374                if (isShown()) {
15375                    // Invoking onVisibilityAggregated directly here since the subtree
15376                    // will also receive detached from window
15377                    onVisibilityAggregated(false);
15378                }
15379            }
15380        }
15381
15382        onDetachedFromWindow();
15383        onDetachedFromWindowInternal();
15384
15385        InputMethodManager imm = InputMethodManager.peekInstance();
15386        if (imm != null) {
15387            imm.onViewDetachedFromWindow(this);
15388        }
15389
15390        ListenerInfo li = mListenerInfo;
15391        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15392                li != null ? li.mOnAttachStateChangeListeners : null;
15393        if (listeners != null && listeners.size() > 0) {
15394            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15395            // perform the dispatching. The iterator is a safe guard against listeners that
15396            // could mutate the list by calling the various add/remove methods. This prevents
15397            // the array from being modified while we iterate it.
15398            for (OnAttachStateChangeListener listener : listeners) {
15399                listener.onViewDetachedFromWindow(this);
15400            }
15401        }
15402
15403        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15404            mAttachInfo.mScrollContainers.remove(this);
15405            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15406        }
15407
15408        mAttachInfo = null;
15409        if (mOverlay != null) {
15410            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15411        }
15412    }
15413
15414    /**
15415     * Cancel any deferred high-level input events that were previously posted to the event queue.
15416     *
15417     * <p>Many views post high-level events such as click handlers to the event queue
15418     * to run deferred in order to preserve a desired user experience - clearing visible
15419     * pressed states before executing, etc. This method will abort any events of this nature
15420     * that are currently in flight.</p>
15421     *
15422     * <p>Custom views that generate their own high-level deferred input events should override
15423     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15424     *
15425     * <p>This will also cancel pending input events for any child views.</p>
15426     *
15427     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15428     * This will not impact newer events posted after this call that may occur as a result of
15429     * lower-level input events still waiting in the queue. If you are trying to prevent
15430     * double-submitted  events for the duration of some sort of asynchronous transaction
15431     * you should also take other steps to protect against unexpected double inputs e.g. calling
15432     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15433     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15434     */
15435    public final void cancelPendingInputEvents() {
15436        dispatchCancelPendingInputEvents();
15437    }
15438
15439    /**
15440     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15441     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15442     */
15443    void dispatchCancelPendingInputEvents() {
15444        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15445        onCancelPendingInputEvents();
15446        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15447            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15448                    " did not call through to super.onCancelPendingInputEvents()");
15449        }
15450    }
15451
15452    /**
15453     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15454     * a parent view.
15455     *
15456     * <p>This method is responsible for removing any pending high-level input events that were
15457     * posted to the event queue to run later. Custom view classes that post their own deferred
15458     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15459     * {@link android.os.Handler} should override this method, call
15460     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15461     * </p>
15462     */
15463    public void onCancelPendingInputEvents() {
15464        removePerformClickCallback();
15465        cancelLongPress();
15466        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15467    }
15468
15469    /**
15470     * Store this view hierarchy's frozen state into the given container.
15471     *
15472     * @param container The SparseArray in which to save the view's state.
15473     *
15474     * @see #restoreHierarchyState(android.util.SparseArray)
15475     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15476     * @see #onSaveInstanceState()
15477     */
15478    public void saveHierarchyState(SparseArray<Parcelable> container) {
15479        dispatchSaveInstanceState(container);
15480    }
15481
15482    /**
15483     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15484     * this view and its children. May be overridden to modify how freezing happens to a
15485     * view's children; for example, some views may want to not store state for their children.
15486     *
15487     * @param container The SparseArray in which to save the view's state.
15488     *
15489     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15490     * @see #saveHierarchyState(android.util.SparseArray)
15491     * @see #onSaveInstanceState()
15492     */
15493    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15494        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15495            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15496            Parcelable state = onSaveInstanceState();
15497            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15498                throw new IllegalStateException(
15499                        "Derived class did not call super.onSaveInstanceState()");
15500            }
15501            if (state != null) {
15502                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15503                // + ": " + state);
15504                container.put(mID, state);
15505            }
15506        }
15507    }
15508
15509    /**
15510     * Hook allowing a view to generate a representation of its internal state
15511     * that can later be used to create a new instance with that same state.
15512     * This state should only contain information that is not persistent or can
15513     * not be reconstructed later. For example, you will never store your
15514     * current position on screen because that will be computed again when a
15515     * new instance of the view is placed in its view hierarchy.
15516     * <p>
15517     * Some examples of things you may store here: the current cursor position
15518     * in a text view (but usually not the text itself since that is stored in a
15519     * content provider or other persistent storage), the currently selected
15520     * item in a list view.
15521     *
15522     * @return Returns a Parcelable object containing the view's current dynamic
15523     *         state, or null if there is nothing interesting to save. The
15524     *         default implementation returns null.
15525     * @see #onRestoreInstanceState(android.os.Parcelable)
15526     * @see #saveHierarchyState(android.util.SparseArray)
15527     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15528     * @see #setSaveEnabled(boolean)
15529     */
15530    @CallSuper
15531    protected Parcelable onSaveInstanceState() {
15532        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15533        if (mStartActivityRequestWho != null) {
15534            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15535            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15536            return state;
15537        }
15538        return BaseSavedState.EMPTY_STATE;
15539    }
15540
15541    /**
15542     * Restore this view hierarchy's frozen state from the given container.
15543     *
15544     * @param container The SparseArray which holds previously frozen states.
15545     *
15546     * @see #saveHierarchyState(android.util.SparseArray)
15547     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15548     * @see #onRestoreInstanceState(android.os.Parcelable)
15549     */
15550    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15551        dispatchRestoreInstanceState(container);
15552    }
15553
15554    /**
15555     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15556     * state for this view and its children. May be overridden to modify how restoring
15557     * happens to a view's children; for example, some views may want to not store state
15558     * for their children.
15559     *
15560     * @param container The SparseArray which holds previously saved state.
15561     *
15562     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15563     * @see #restoreHierarchyState(android.util.SparseArray)
15564     * @see #onRestoreInstanceState(android.os.Parcelable)
15565     */
15566    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15567        if (mID != NO_ID) {
15568            Parcelable state = container.get(mID);
15569            if (state != null) {
15570                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15571                // + ": " + state);
15572                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15573                onRestoreInstanceState(state);
15574                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15575                    throw new IllegalStateException(
15576                            "Derived class did not call super.onRestoreInstanceState()");
15577                }
15578            }
15579        }
15580    }
15581
15582    /**
15583     * Hook allowing a view to re-apply a representation of its internal state that had previously
15584     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15585     * null state.
15586     *
15587     * @param state The frozen state that had previously been returned by
15588     *        {@link #onSaveInstanceState}.
15589     *
15590     * @see #onSaveInstanceState()
15591     * @see #restoreHierarchyState(android.util.SparseArray)
15592     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15593     */
15594    @CallSuper
15595    protected void onRestoreInstanceState(Parcelable state) {
15596        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15597        if (state != null && !(state instanceof AbsSavedState)) {
15598            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15599                    + "received " + state.getClass().toString() + " instead. This usually happens "
15600                    + "when two views of different type have the same id in the same hierarchy. "
15601                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15602                    + "other views do not use the same id.");
15603        }
15604        if (state != null && state instanceof BaseSavedState) {
15605            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15606        }
15607    }
15608
15609    /**
15610     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15611     *
15612     * @return the drawing start time in milliseconds
15613     */
15614    public long getDrawingTime() {
15615        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15616    }
15617
15618    /**
15619     * <p>Enables or disables the duplication of the parent's state into this view. When
15620     * duplication is enabled, this view gets its drawable state from its parent rather
15621     * than from its own internal properties.</p>
15622     *
15623     * <p>Note: in the current implementation, setting this property to true after the
15624     * view was added to a ViewGroup might have no effect at all. This property should
15625     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15626     *
15627     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15628     * property is enabled, an exception will be thrown.</p>
15629     *
15630     * <p>Note: if the child view uses and updates additional states which are unknown to the
15631     * parent, these states should not be affected by this method.</p>
15632     *
15633     * @param enabled True to enable duplication of the parent's drawable state, false
15634     *                to disable it.
15635     *
15636     * @see #getDrawableState()
15637     * @see #isDuplicateParentStateEnabled()
15638     */
15639    public void setDuplicateParentStateEnabled(boolean enabled) {
15640        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15641    }
15642
15643    /**
15644     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15645     *
15646     * @return True if this view's drawable state is duplicated from the parent,
15647     *         false otherwise
15648     *
15649     * @see #getDrawableState()
15650     * @see #setDuplicateParentStateEnabled(boolean)
15651     */
15652    public boolean isDuplicateParentStateEnabled() {
15653        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15654    }
15655
15656    /**
15657     * <p>Specifies the type of layer backing this view. The layer can be
15658     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15659     * {@link #LAYER_TYPE_HARDWARE}.</p>
15660     *
15661     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15662     * instance that controls how the layer is composed on screen. The following
15663     * properties of the paint are taken into account when composing the layer:</p>
15664     * <ul>
15665     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15666     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15667     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15668     * </ul>
15669     *
15670     * <p>If this view has an alpha value set to < 1.0 by calling
15671     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15672     * by this view's alpha value.</p>
15673     *
15674     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15675     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15676     * for more information on when and how to use layers.</p>
15677     *
15678     * @param layerType The type of layer to use with this view, must be one of
15679     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15680     *        {@link #LAYER_TYPE_HARDWARE}
15681     * @param paint The paint used to compose the layer. This argument is optional
15682     *        and can be null. It is ignored when the layer type is
15683     *        {@link #LAYER_TYPE_NONE}
15684     *
15685     * @see #getLayerType()
15686     * @see #LAYER_TYPE_NONE
15687     * @see #LAYER_TYPE_SOFTWARE
15688     * @see #LAYER_TYPE_HARDWARE
15689     * @see #setAlpha(float)
15690     *
15691     * @attr ref android.R.styleable#View_layerType
15692     */
15693    public void setLayerType(int layerType, @Nullable Paint paint) {
15694        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15695            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15696                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15697        }
15698
15699        boolean typeChanged = mRenderNode.setLayerType(layerType);
15700
15701        if (!typeChanged) {
15702            setLayerPaint(paint);
15703            return;
15704        }
15705
15706        // Destroy any previous software drawing cache if needed
15707        if (mLayerType == LAYER_TYPE_SOFTWARE) {
15708            destroyDrawingCache();
15709        }
15710
15711        mLayerType = layerType;
15712        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15713        mRenderNode.setLayerPaint(mLayerPaint);
15714
15715        // draw() behaves differently if we are on a layer, so we need to
15716        // invalidate() here
15717        invalidateParentCaches();
15718        invalidate(true);
15719    }
15720
15721    /**
15722     * Updates the {@link Paint} object used with the current layer (used only if the current
15723     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15724     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15725     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15726     * ensure that the view gets redrawn immediately.
15727     *
15728     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15729     * instance that controls how the layer is composed on screen. The following
15730     * properties of the paint are taken into account when composing the layer:</p>
15731     * <ul>
15732     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15733     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15734     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15735     * </ul>
15736     *
15737     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15738     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15739     *
15740     * @param paint The paint used to compose the layer. This argument is optional
15741     *        and can be null. It is ignored when the layer type is
15742     *        {@link #LAYER_TYPE_NONE}
15743     *
15744     * @see #setLayerType(int, android.graphics.Paint)
15745     */
15746    public void setLayerPaint(@Nullable Paint paint) {
15747        int layerType = getLayerType();
15748        if (layerType != LAYER_TYPE_NONE) {
15749            mLayerPaint = paint;
15750            if (layerType == LAYER_TYPE_HARDWARE) {
15751                if (mRenderNode.setLayerPaint(paint)) {
15752                    invalidateViewProperty(false, false);
15753                }
15754            } else {
15755                invalidate();
15756            }
15757        }
15758    }
15759
15760    /**
15761     * Indicates what type of layer is currently associated with this view. By default
15762     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15763     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15764     * for more information on the different types of layers.
15765     *
15766     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15767     *         {@link #LAYER_TYPE_HARDWARE}
15768     *
15769     * @see #setLayerType(int, android.graphics.Paint)
15770     * @see #buildLayer()
15771     * @see #LAYER_TYPE_NONE
15772     * @see #LAYER_TYPE_SOFTWARE
15773     * @see #LAYER_TYPE_HARDWARE
15774     */
15775    public int getLayerType() {
15776        return mLayerType;
15777    }
15778
15779    /**
15780     * Forces this view's layer to be created and this view to be rendered
15781     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15782     * invoking this method will have no effect.
15783     *
15784     * This method can for instance be used to render a view into its layer before
15785     * starting an animation. If this view is complex, rendering into the layer
15786     * before starting the animation will avoid skipping frames.
15787     *
15788     * @throws IllegalStateException If this view is not attached to a window
15789     *
15790     * @see #setLayerType(int, android.graphics.Paint)
15791     */
15792    public void buildLayer() {
15793        if (mLayerType == LAYER_TYPE_NONE) return;
15794
15795        final AttachInfo attachInfo = mAttachInfo;
15796        if (attachInfo == null) {
15797            throw new IllegalStateException("This view must be attached to a window first");
15798        }
15799
15800        if (getWidth() == 0 || getHeight() == 0) {
15801            return;
15802        }
15803
15804        switch (mLayerType) {
15805            case LAYER_TYPE_HARDWARE:
15806                updateDisplayListIfDirty();
15807                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
15808                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
15809                }
15810                break;
15811            case LAYER_TYPE_SOFTWARE:
15812                buildDrawingCache(true);
15813                break;
15814        }
15815    }
15816
15817    /**
15818     * Destroys all hardware rendering resources. This method is invoked
15819     * when the system needs to reclaim resources. Upon execution of this
15820     * method, you should free any OpenGL resources created by the view.
15821     *
15822     * Note: you <strong>must</strong> call
15823     * <code>super.destroyHardwareResources()</code> when overriding
15824     * this method.
15825     *
15826     * @hide
15827     */
15828    @CallSuper
15829    protected void destroyHardwareResources() {
15830        // Although the Layer will be destroyed by RenderNode, we want to release
15831        // the staging display list, which is also a signal to RenderNode that it's
15832        // safe to free its copy of the display list as it knows that we will
15833        // push an updated DisplayList if we try to draw again
15834        resetDisplayList();
15835    }
15836
15837    /**
15838     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15839     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15840     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15841     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15842     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15843     * null.</p>
15844     *
15845     * <p>Enabling the drawing cache is similar to
15846     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15847     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15848     * drawing cache has no effect on rendering because the system uses a different mechanism
15849     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15850     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15851     * for information on how to enable software and hardware layers.</p>
15852     *
15853     * <p>This API can be used to manually generate
15854     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15855     * {@link #getDrawingCache()}.</p>
15856     *
15857     * @param enabled true to enable the drawing cache, false otherwise
15858     *
15859     * @see #isDrawingCacheEnabled()
15860     * @see #getDrawingCache()
15861     * @see #buildDrawingCache()
15862     * @see #setLayerType(int, android.graphics.Paint)
15863     */
15864    public void setDrawingCacheEnabled(boolean enabled) {
15865        mCachingFailed = false;
15866        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15867    }
15868
15869    /**
15870     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15871     *
15872     * @return true if the drawing cache is enabled
15873     *
15874     * @see #setDrawingCacheEnabled(boolean)
15875     * @see #getDrawingCache()
15876     */
15877    @ViewDebug.ExportedProperty(category = "drawing")
15878    public boolean isDrawingCacheEnabled() {
15879        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15880    }
15881
15882    /**
15883     * Debugging utility which recursively outputs the dirty state of a view and its
15884     * descendants.
15885     *
15886     * @hide
15887     */
15888    @SuppressWarnings({"UnusedDeclaration"})
15889    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15890        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15891                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15892                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15893                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15894        if (clear) {
15895            mPrivateFlags &= clearMask;
15896        }
15897        if (this instanceof ViewGroup) {
15898            ViewGroup parent = (ViewGroup) this;
15899            final int count = parent.getChildCount();
15900            for (int i = 0; i < count; i++) {
15901                final View child = parent.getChildAt(i);
15902                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15903            }
15904        }
15905    }
15906
15907    /**
15908     * This method is used by ViewGroup to cause its children to restore or recreate their
15909     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15910     * to recreate its own display list, which would happen if it went through the normal
15911     * draw/dispatchDraw mechanisms.
15912     *
15913     * @hide
15914     */
15915    protected void dispatchGetDisplayList() {}
15916
15917    /**
15918     * A view that is not attached or hardware accelerated cannot create a display list.
15919     * This method checks these conditions and returns the appropriate result.
15920     *
15921     * @return true if view has the ability to create a display list, false otherwise.
15922     *
15923     * @hide
15924     */
15925    public boolean canHaveDisplayList() {
15926        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
15927    }
15928
15929    /**
15930     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15931     * @hide
15932     */
15933    @NonNull
15934    public RenderNode updateDisplayListIfDirty() {
15935        final RenderNode renderNode = mRenderNode;
15936        if (!canHaveDisplayList()) {
15937            // can't populate RenderNode, don't try
15938            return renderNode;
15939        }
15940
15941        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
15942                || !renderNode.isValid()
15943                || (mRecreateDisplayList)) {
15944            // Don't need to recreate the display list, just need to tell our
15945            // children to restore/recreate theirs
15946            if (renderNode.isValid()
15947                    && !mRecreateDisplayList) {
15948                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15949                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15950                dispatchGetDisplayList();
15951
15952                return renderNode; // no work needed
15953            }
15954
15955            // If we got here, we're recreating it. Mark it as such to ensure that
15956            // we copy in child display lists into ours in drawChild()
15957            mRecreateDisplayList = true;
15958
15959            int width = mRight - mLeft;
15960            int height = mBottom - mTop;
15961            int layerType = getLayerType();
15962
15963            final DisplayListCanvas canvas = renderNode.start(width, height);
15964            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
15965
15966            try {
15967                if (layerType == LAYER_TYPE_SOFTWARE) {
15968                    buildDrawingCache(true);
15969                    Bitmap cache = getDrawingCache(true);
15970                    if (cache != null) {
15971                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
15972                    }
15973                } else {
15974                    computeScroll();
15975
15976                    canvas.translate(-mScrollX, -mScrollY);
15977                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15978                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15979
15980                    // Fast path for layouts with no backgrounds
15981                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15982                        dispatchDraw(canvas);
15983                        if (mOverlay != null && !mOverlay.isEmpty()) {
15984                            mOverlay.getOverlayView().draw(canvas);
15985                        }
15986                    } else {
15987                        draw(canvas);
15988                    }
15989                }
15990            } finally {
15991                renderNode.end(canvas);
15992                setDisplayListProperties(renderNode);
15993            }
15994        } else {
15995            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15996            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15997        }
15998        return renderNode;
15999    }
16000
16001    private void resetDisplayList() {
16002        if (mRenderNode.isValid()) {
16003            mRenderNode.discardDisplayList();
16004        }
16005
16006        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16007            mBackgroundRenderNode.discardDisplayList();
16008        }
16009    }
16010
16011    /**
16012     * Called when the passed RenderNode is removed from the draw tree
16013     * @hide
16014     */
16015    public void onRenderNodeDetached(RenderNode renderNode) {
16016    }
16017
16018    /**
16019     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16020     *
16021     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16022     *
16023     * @see #getDrawingCache(boolean)
16024     */
16025    public Bitmap getDrawingCache() {
16026        return getDrawingCache(false);
16027    }
16028
16029    /**
16030     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16031     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16032     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16033     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16034     * request the drawing cache by calling this method and draw it on screen if the
16035     * returned bitmap is not null.</p>
16036     *
16037     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16038     * this method will create a bitmap of the same size as this view. Because this bitmap
16039     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16040     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16041     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16042     * size than the view. This implies that your application must be able to handle this
16043     * size.</p>
16044     *
16045     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16046     *        the current density of the screen when the application is in compatibility
16047     *        mode.
16048     *
16049     * @return A bitmap representing this view or null if cache is disabled.
16050     *
16051     * @see #setDrawingCacheEnabled(boolean)
16052     * @see #isDrawingCacheEnabled()
16053     * @see #buildDrawingCache(boolean)
16054     * @see #destroyDrawingCache()
16055     */
16056    public Bitmap getDrawingCache(boolean autoScale) {
16057        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16058            return null;
16059        }
16060        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16061            buildDrawingCache(autoScale);
16062        }
16063        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16064    }
16065
16066    /**
16067     * <p>Frees the resources used by the drawing cache. If you call
16068     * {@link #buildDrawingCache()} manually without calling
16069     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16070     * should cleanup the cache with this method afterwards.</p>
16071     *
16072     * @see #setDrawingCacheEnabled(boolean)
16073     * @see #buildDrawingCache()
16074     * @see #getDrawingCache()
16075     */
16076    public void destroyDrawingCache() {
16077        if (mDrawingCache != null) {
16078            mDrawingCache.recycle();
16079            mDrawingCache = null;
16080        }
16081        if (mUnscaledDrawingCache != null) {
16082            mUnscaledDrawingCache.recycle();
16083            mUnscaledDrawingCache = null;
16084        }
16085    }
16086
16087    /**
16088     * Setting a solid background color for the drawing cache's bitmaps will improve
16089     * performance and memory usage. Note, though that this should only be used if this
16090     * view will always be drawn on top of a solid color.
16091     *
16092     * @param color The background color to use for the drawing cache's bitmap
16093     *
16094     * @see #setDrawingCacheEnabled(boolean)
16095     * @see #buildDrawingCache()
16096     * @see #getDrawingCache()
16097     */
16098    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16099        if (color != mDrawingCacheBackgroundColor) {
16100            mDrawingCacheBackgroundColor = color;
16101            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16102        }
16103    }
16104
16105    /**
16106     * @see #setDrawingCacheBackgroundColor(int)
16107     *
16108     * @return The background color to used for the drawing cache's bitmap
16109     */
16110    @ColorInt
16111    public int getDrawingCacheBackgroundColor() {
16112        return mDrawingCacheBackgroundColor;
16113    }
16114
16115    /**
16116     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16117     *
16118     * @see #buildDrawingCache(boolean)
16119     */
16120    public void buildDrawingCache() {
16121        buildDrawingCache(false);
16122    }
16123
16124    /**
16125     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16126     *
16127     * <p>If you call {@link #buildDrawingCache()} manually without calling
16128     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16129     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16130     *
16131     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16132     * this method will create a bitmap of the same size as this view. Because this bitmap
16133     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16134     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16135     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16136     * size than the view. This implies that your application must be able to handle this
16137     * size.</p>
16138     *
16139     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16140     * you do not need the drawing cache bitmap, calling this method will increase memory
16141     * usage and cause the view to be rendered in software once, thus negatively impacting
16142     * performance.</p>
16143     *
16144     * @see #getDrawingCache()
16145     * @see #destroyDrawingCache()
16146     */
16147    public void buildDrawingCache(boolean autoScale) {
16148        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16149                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16150            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16151                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16152                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16153            }
16154            try {
16155                buildDrawingCacheImpl(autoScale);
16156            } finally {
16157                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16158            }
16159        }
16160    }
16161
16162    /**
16163     * private, internal implementation of buildDrawingCache, used to enable tracing
16164     */
16165    private void buildDrawingCacheImpl(boolean autoScale) {
16166        mCachingFailed = false;
16167
16168        int width = mRight - mLeft;
16169        int height = mBottom - mTop;
16170
16171        final AttachInfo attachInfo = mAttachInfo;
16172        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16173
16174        if (autoScale && scalingRequired) {
16175            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16176            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16177        }
16178
16179        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16180        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16181        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16182
16183        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16184        final long drawingCacheSize =
16185                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16186        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16187            if (width > 0 && height > 0) {
16188                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16189                        + " too large to fit into a software layer (or drawing cache), needs "
16190                        + projectedBitmapSize + " bytes, only "
16191                        + drawingCacheSize + " available");
16192            }
16193            destroyDrawingCache();
16194            mCachingFailed = true;
16195            return;
16196        }
16197
16198        boolean clear = true;
16199        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16200
16201        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16202            Bitmap.Config quality;
16203            if (!opaque) {
16204                // Never pick ARGB_4444 because it looks awful
16205                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16206                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16207                    case DRAWING_CACHE_QUALITY_AUTO:
16208                    case DRAWING_CACHE_QUALITY_LOW:
16209                    case DRAWING_CACHE_QUALITY_HIGH:
16210                    default:
16211                        quality = Bitmap.Config.ARGB_8888;
16212                        break;
16213                }
16214            } else {
16215                // Optimization for translucent windows
16216                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16217                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16218            }
16219
16220            // Try to cleanup memory
16221            if (bitmap != null) bitmap.recycle();
16222
16223            try {
16224                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16225                        width, height, quality);
16226                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16227                if (autoScale) {
16228                    mDrawingCache = bitmap;
16229                } else {
16230                    mUnscaledDrawingCache = bitmap;
16231                }
16232                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16233            } catch (OutOfMemoryError e) {
16234                // If there is not enough memory to create the bitmap cache, just
16235                // ignore the issue as bitmap caches are not required to draw the
16236                // view hierarchy
16237                if (autoScale) {
16238                    mDrawingCache = null;
16239                } else {
16240                    mUnscaledDrawingCache = null;
16241                }
16242                mCachingFailed = true;
16243                return;
16244            }
16245
16246            clear = drawingCacheBackgroundColor != 0;
16247        }
16248
16249        Canvas canvas;
16250        if (attachInfo != null) {
16251            canvas = attachInfo.mCanvas;
16252            if (canvas == null) {
16253                canvas = new Canvas();
16254            }
16255            canvas.setBitmap(bitmap);
16256            // Temporarily clobber the cached Canvas in case one of our children
16257            // is also using a drawing cache. Without this, the children would
16258            // steal the canvas by attaching their own bitmap to it and bad, bad
16259            // thing would happen (invisible views, corrupted drawings, etc.)
16260            attachInfo.mCanvas = null;
16261        } else {
16262            // This case should hopefully never or seldom happen
16263            canvas = new Canvas(bitmap);
16264        }
16265
16266        if (clear) {
16267            bitmap.eraseColor(drawingCacheBackgroundColor);
16268        }
16269
16270        computeScroll();
16271        final int restoreCount = canvas.save();
16272
16273        if (autoScale && scalingRequired) {
16274            final float scale = attachInfo.mApplicationScale;
16275            canvas.scale(scale, scale);
16276        }
16277
16278        canvas.translate(-mScrollX, -mScrollY);
16279
16280        mPrivateFlags |= PFLAG_DRAWN;
16281        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16282                mLayerType != LAYER_TYPE_NONE) {
16283            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16284        }
16285
16286        // Fast path for layouts with no backgrounds
16287        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16288            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16289            dispatchDraw(canvas);
16290            if (mOverlay != null && !mOverlay.isEmpty()) {
16291                mOverlay.getOverlayView().draw(canvas);
16292            }
16293        } else {
16294            draw(canvas);
16295        }
16296
16297        canvas.restoreToCount(restoreCount);
16298        canvas.setBitmap(null);
16299
16300        if (attachInfo != null) {
16301            // Restore the cached Canvas for our siblings
16302            attachInfo.mCanvas = canvas;
16303        }
16304    }
16305
16306    /**
16307     * Create a snapshot of the view into a bitmap.  We should probably make
16308     * some form of this public, but should think about the API.
16309     *
16310     * @hide
16311     */
16312    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16313        int width = mRight - mLeft;
16314        int height = mBottom - mTop;
16315
16316        final AttachInfo attachInfo = mAttachInfo;
16317        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16318        width = (int) ((width * scale) + 0.5f);
16319        height = (int) ((height * scale) + 0.5f);
16320
16321        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16322                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16323        if (bitmap == null) {
16324            throw new OutOfMemoryError();
16325        }
16326
16327        Resources resources = getResources();
16328        if (resources != null) {
16329            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16330        }
16331
16332        Canvas canvas;
16333        if (attachInfo != null) {
16334            canvas = attachInfo.mCanvas;
16335            if (canvas == null) {
16336                canvas = new Canvas();
16337            }
16338            canvas.setBitmap(bitmap);
16339            // Temporarily clobber the cached Canvas in case one of our children
16340            // is also using a drawing cache. Without this, the children would
16341            // steal the canvas by attaching their own bitmap to it and bad, bad
16342            // things would happen (invisible views, corrupted drawings, etc.)
16343            attachInfo.mCanvas = null;
16344        } else {
16345            // This case should hopefully never or seldom happen
16346            canvas = new Canvas(bitmap);
16347        }
16348
16349        if ((backgroundColor & 0xff000000) != 0) {
16350            bitmap.eraseColor(backgroundColor);
16351        }
16352
16353        computeScroll();
16354        final int restoreCount = canvas.save();
16355        canvas.scale(scale, scale);
16356        canvas.translate(-mScrollX, -mScrollY);
16357
16358        // Temporarily remove the dirty mask
16359        int flags = mPrivateFlags;
16360        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16361
16362        // Fast path for layouts with no backgrounds
16363        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16364            dispatchDraw(canvas);
16365            if (mOverlay != null && !mOverlay.isEmpty()) {
16366                mOverlay.getOverlayView().draw(canvas);
16367            }
16368        } else {
16369            draw(canvas);
16370        }
16371
16372        mPrivateFlags = flags;
16373
16374        canvas.restoreToCount(restoreCount);
16375        canvas.setBitmap(null);
16376
16377        if (attachInfo != null) {
16378            // Restore the cached Canvas for our siblings
16379            attachInfo.mCanvas = canvas;
16380        }
16381
16382        return bitmap;
16383    }
16384
16385    /**
16386     * Indicates whether this View is currently in edit mode. A View is usually
16387     * in edit mode when displayed within a developer tool. For instance, if
16388     * this View is being drawn by a visual user interface builder, this method
16389     * should return true.
16390     *
16391     * Subclasses should check the return value of this method to provide
16392     * different behaviors if their normal behavior might interfere with the
16393     * host environment. For instance: the class spawns a thread in its
16394     * constructor, the drawing code relies on device-specific features, etc.
16395     *
16396     * This method is usually checked in the drawing code of custom widgets.
16397     *
16398     * @return True if this View is in edit mode, false otherwise.
16399     */
16400    public boolean isInEditMode() {
16401        return false;
16402    }
16403
16404    /**
16405     * If the View draws content inside its padding and enables fading edges,
16406     * it needs to support padding offsets. Padding offsets are added to the
16407     * fading edges to extend the length of the fade so that it covers pixels
16408     * drawn inside the padding.
16409     *
16410     * Subclasses of this class should override this method if they need
16411     * to draw content inside the padding.
16412     *
16413     * @return True if padding offset must be applied, false otherwise.
16414     *
16415     * @see #getLeftPaddingOffset()
16416     * @see #getRightPaddingOffset()
16417     * @see #getTopPaddingOffset()
16418     * @see #getBottomPaddingOffset()
16419     *
16420     * @since CURRENT
16421     */
16422    protected boolean isPaddingOffsetRequired() {
16423        return false;
16424    }
16425
16426    /**
16427     * Amount by which to extend the left fading region. Called only when
16428     * {@link #isPaddingOffsetRequired()} returns true.
16429     *
16430     * @return The left padding offset in pixels.
16431     *
16432     * @see #isPaddingOffsetRequired()
16433     *
16434     * @since CURRENT
16435     */
16436    protected int getLeftPaddingOffset() {
16437        return 0;
16438    }
16439
16440    /**
16441     * Amount by which to extend the right fading region. Called only when
16442     * {@link #isPaddingOffsetRequired()} returns true.
16443     *
16444     * @return The right padding offset in pixels.
16445     *
16446     * @see #isPaddingOffsetRequired()
16447     *
16448     * @since CURRENT
16449     */
16450    protected int getRightPaddingOffset() {
16451        return 0;
16452    }
16453
16454    /**
16455     * Amount by which to extend the top fading region. Called only when
16456     * {@link #isPaddingOffsetRequired()} returns true.
16457     *
16458     * @return The top padding offset in pixels.
16459     *
16460     * @see #isPaddingOffsetRequired()
16461     *
16462     * @since CURRENT
16463     */
16464    protected int getTopPaddingOffset() {
16465        return 0;
16466    }
16467
16468    /**
16469     * Amount by which to extend the bottom fading region. Called only when
16470     * {@link #isPaddingOffsetRequired()} returns true.
16471     *
16472     * @return The bottom padding offset in pixels.
16473     *
16474     * @see #isPaddingOffsetRequired()
16475     *
16476     * @since CURRENT
16477     */
16478    protected int getBottomPaddingOffset() {
16479        return 0;
16480    }
16481
16482    /**
16483     * @hide
16484     * @param offsetRequired
16485     */
16486    protected int getFadeTop(boolean offsetRequired) {
16487        int top = mPaddingTop;
16488        if (offsetRequired) top += getTopPaddingOffset();
16489        return top;
16490    }
16491
16492    /**
16493     * @hide
16494     * @param offsetRequired
16495     */
16496    protected int getFadeHeight(boolean offsetRequired) {
16497        int padding = mPaddingTop;
16498        if (offsetRequired) padding += getTopPaddingOffset();
16499        return mBottom - mTop - mPaddingBottom - padding;
16500    }
16501
16502    /**
16503     * <p>Indicates whether this view is attached to a hardware accelerated
16504     * window or not.</p>
16505     *
16506     * <p>Even if this method returns true, it does not mean that every call
16507     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16508     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16509     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16510     * window is hardware accelerated,
16511     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16512     * return false, and this method will return true.</p>
16513     *
16514     * @return True if the view is attached to a window and the window is
16515     *         hardware accelerated; false in any other case.
16516     */
16517    @ViewDebug.ExportedProperty(category = "drawing")
16518    public boolean isHardwareAccelerated() {
16519        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16520    }
16521
16522    /**
16523     * Sets a rectangular area on this view to which the view will be clipped
16524     * when it is drawn. Setting the value to null will remove the clip bounds
16525     * and the view will draw normally, using its full bounds.
16526     *
16527     * @param clipBounds The rectangular area, in the local coordinates of
16528     * this view, to which future drawing operations will be clipped.
16529     */
16530    public void setClipBounds(Rect clipBounds) {
16531        if (clipBounds == mClipBounds
16532                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16533            return;
16534        }
16535        if (clipBounds != null) {
16536            if (mClipBounds == null) {
16537                mClipBounds = new Rect(clipBounds);
16538            } else {
16539                mClipBounds.set(clipBounds);
16540            }
16541        } else {
16542            mClipBounds = null;
16543        }
16544        mRenderNode.setClipBounds(mClipBounds);
16545        invalidateViewProperty(false, false);
16546    }
16547
16548    /**
16549     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16550     *
16551     * @return A copy of the current clip bounds if clip bounds are set,
16552     * otherwise null.
16553     */
16554    public Rect getClipBounds() {
16555        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16556    }
16557
16558
16559    /**
16560     * Populates an output rectangle with the clip bounds of the view,
16561     * returning {@code true} if successful or {@code false} if the view's
16562     * clip bounds are {@code null}.
16563     *
16564     * @param outRect rectangle in which to place the clip bounds of the view
16565     * @return {@code true} if successful or {@code false} if the view's
16566     *         clip bounds are {@code null}
16567     */
16568    public boolean getClipBounds(Rect outRect) {
16569        if (mClipBounds != null) {
16570            outRect.set(mClipBounds);
16571            return true;
16572        }
16573        return false;
16574    }
16575
16576    /**
16577     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16578     * case of an active Animation being run on the view.
16579     */
16580    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16581            Animation a, boolean scalingRequired) {
16582        Transformation invalidationTransform;
16583        final int flags = parent.mGroupFlags;
16584        final boolean initialized = a.isInitialized();
16585        if (!initialized) {
16586            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16587            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16588            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16589            onAnimationStart();
16590        }
16591
16592        final Transformation t = parent.getChildTransformation();
16593        boolean more = a.getTransformation(drawingTime, t, 1f);
16594        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16595            if (parent.mInvalidationTransformation == null) {
16596                parent.mInvalidationTransformation = new Transformation();
16597            }
16598            invalidationTransform = parent.mInvalidationTransformation;
16599            a.getTransformation(drawingTime, invalidationTransform, 1f);
16600        } else {
16601            invalidationTransform = t;
16602        }
16603
16604        if (more) {
16605            if (!a.willChangeBounds()) {
16606                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16607                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16608                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16609                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16610                    // The child need to draw an animation, potentially offscreen, so
16611                    // make sure we do not cancel invalidate requests
16612                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16613                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16614                }
16615            } else {
16616                if (parent.mInvalidateRegion == null) {
16617                    parent.mInvalidateRegion = new RectF();
16618                }
16619                final RectF region = parent.mInvalidateRegion;
16620                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16621                        invalidationTransform);
16622
16623                // The child need to draw an animation, potentially offscreen, so
16624                // make sure we do not cancel invalidate requests
16625                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16626
16627                final int left = mLeft + (int) region.left;
16628                final int top = mTop + (int) region.top;
16629                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16630                        top + (int) (region.height() + .5f));
16631            }
16632        }
16633        return more;
16634    }
16635
16636    /**
16637     * This method is called by getDisplayList() when a display list is recorded for a View.
16638     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16639     */
16640    void setDisplayListProperties(RenderNode renderNode) {
16641        if (renderNode != null) {
16642            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16643            renderNode.setClipToBounds(mParent instanceof ViewGroup
16644                    && ((ViewGroup) mParent).getClipChildren());
16645
16646            float alpha = 1;
16647            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16648                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16649                ViewGroup parentVG = (ViewGroup) mParent;
16650                final Transformation t = parentVG.getChildTransformation();
16651                if (parentVG.getChildStaticTransformation(this, t)) {
16652                    final int transformType = t.getTransformationType();
16653                    if (transformType != Transformation.TYPE_IDENTITY) {
16654                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16655                            alpha = t.getAlpha();
16656                        }
16657                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16658                            renderNode.setStaticMatrix(t.getMatrix());
16659                        }
16660                    }
16661                }
16662            }
16663            if (mTransformationInfo != null) {
16664                alpha *= getFinalAlpha();
16665                if (alpha < 1) {
16666                    final int multipliedAlpha = (int) (255 * alpha);
16667                    if (onSetAlpha(multipliedAlpha)) {
16668                        alpha = 1;
16669                    }
16670                }
16671                renderNode.setAlpha(alpha);
16672            } else if (alpha < 1) {
16673                renderNode.setAlpha(alpha);
16674            }
16675        }
16676    }
16677
16678    /**
16679     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16680     *
16681     * This is where the View specializes rendering behavior based on layer type,
16682     * and hardware acceleration.
16683     */
16684    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16685        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16686        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16687         *
16688         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16689         * HW accelerated, it can't handle drawing RenderNodes.
16690         */
16691        boolean drawingWithRenderNode = mAttachInfo != null
16692                && mAttachInfo.mHardwareAccelerated
16693                && hardwareAcceleratedCanvas;
16694
16695        boolean more = false;
16696        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16697        final int parentFlags = parent.mGroupFlags;
16698
16699        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16700            parent.getChildTransformation().clear();
16701            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16702        }
16703
16704        Transformation transformToApply = null;
16705        boolean concatMatrix = false;
16706        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16707        final Animation a = getAnimation();
16708        if (a != null) {
16709            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16710            concatMatrix = a.willChangeTransformationMatrix();
16711            if (concatMatrix) {
16712                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16713            }
16714            transformToApply = parent.getChildTransformation();
16715        } else {
16716            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16717                // No longer animating: clear out old animation matrix
16718                mRenderNode.setAnimationMatrix(null);
16719                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16720            }
16721            if (!drawingWithRenderNode
16722                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16723                final Transformation t = parent.getChildTransformation();
16724                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16725                if (hasTransform) {
16726                    final int transformType = t.getTransformationType();
16727                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16728                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16729                }
16730            }
16731        }
16732
16733        concatMatrix |= !childHasIdentityMatrix;
16734
16735        // Sets the flag as early as possible to allow draw() implementations
16736        // to call invalidate() successfully when doing animations
16737        mPrivateFlags |= PFLAG_DRAWN;
16738
16739        if (!concatMatrix &&
16740                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16741                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16742                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16743                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16744            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16745            return more;
16746        }
16747        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16748
16749        if (hardwareAcceleratedCanvas) {
16750            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16751            // retain the flag's value temporarily in the mRecreateDisplayList flag
16752            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16753            mPrivateFlags &= ~PFLAG_INVALIDATED;
16754        }
16755
16756        RenderNode renderNode = null;
16757        Bitmap cache = null;
16758        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16759        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16760             if (layerType != LAYER_TYPE_NONE) {
16761                 // If not drawing with RenderNode, treat HW layers as SW
16762                 layerType = LAYER_TYPE_SOFTWARE;
16763                 buildDrawingCache(true);
16764            }
16765            cache = getDrawingCache(true);
16766        }
16767
16768        if (drawingWithRenderNode) {
16769            // Delay getting the display list until animation-driven alpha values are
16770            // set up and possibly passed on to the view
16771            renderNode = updateDisplayListIfDirty();
16772            if (!renderNode.isValid()) {
16773                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16774                // to getDisplayList(), the display list will be marked invalid and we should not
16775                // try to use it again.
16776                renderNode = null;
16777                drawingWithRenderNode = false;
16778            }
16779        }
16780
16781        int sx = 0;
16782        int sy = 0;
16783        if (!drawingWithRenderNode) {
16784            computeScroll();
16785            sx = mScrollX;
16786            sy = mScrollY;
16787        }
16788
16789        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16790        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16791
16792        int restoreTo = -1;
16793        if (!drawingWithRenderNode || transformToApply != null) {
16794            restoreTo = canvas.save();
16795        }
16796        if (offsetForScroll) {
16797            canvas.translate(mLeft - sx, mTop - sy);
16798        } else {
16799            if (!drawingWithRenderNode) {
16800                canvas.translate(mLeft, mTop);
16801            }
16802            if (scalingRequired) {
16803                if (drawingWithRenderNode) {
16804                    // TODO: Might not need this if we put everything inside the DL
16805                    restoreTo = canvas.save();
16806                }
16807                // mAttachInfo cannot be null, otherwise scalingRequired == false
16808                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16809                canvas.scale(scale, scale);
16810            }
16811        }
16812
16813        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16814        if (transformToApply != null
16815                || alpha < 1
16816                || !hasIdentityMatrix()
16817                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16818            if (transformToApply != null || !childHasIdentityMatrix) {
16819                int transX = 0;
16820                int transY = 0;
16821
16822                if (offsetForScroll) {
16823                    transX = -sx;
16824                    transY = -sy;
16825                }
16826
16827                if (transformToApply != null) {
16828                    if (concatMatrix) {
16829                        if (drawingWithRenderNode) {
16830                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16831                        } else {
16832                            // Undo the scroll translation, apply the transformation matrix,
16833                            // then redo the scroll translate to get the correct result.
16834                            canvas.translate(-transX, -transY);
16835                            canvas.concat(transformToApply.getMatrix());
16836                            canvas.translate(transX, transY);
16837                        }
16838                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16839                    }
16840
16841                    float transformAlpha = transformToApply.getAlpha();
16842                    if (transformAlpha < 1) {
16843                        alpha *= transformAlpha;
16844                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16845                    }
16846                }
16847
16848                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16849                    canvas.translate(-transX, -transY);
16850                    canvas.concat(getMatrix());
16851                    canvas.translate(transX, transY);
16852                }
16853            }
16854
16855            // Deal with alpha if it is or used to be <1
16856            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16857                if (alpha < 1) {
16858                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16859                } else {
16860                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16861                }
16862                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16863                if (!drawingWithDrawingCache) {
16864                    final int multipliedAlpha = (int) (255 * alpha);
16865                    if (!onSetAlpha(multipliedAlpha)) {
16866                        if (drawingWithRenderNode) {
16867                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16868                        } else if (layerType == LAYER_TYPE_NONE) {
16869                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16870                                    multipliedAlpha);
16871                        }
16872                    } else {
16873                        // Alpha is handled by the child directly, clobber the layer's alpha
16874                        mPrivateFlags |= PFLAG_ALPHA_SET;
16875                    }
16876                }
16877            }
16878        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16879            onSetAlpha(255);
16880            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16881        }
16882
16883        if (!drawingWithRenderNode) {
16884            // apply clips directly, since RenderNode won't do it for this draw
16885            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16886                if (offsetForScroll) {
16887                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16888                } else {
16889                    if (!scalingRequired || cache == null) {
16890                        canvas.clipRect(0, 0, getWidth(), getHeight());
16891                    } else {
16892                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16893                    }
16894                }
16895            }
16896
16897            if (mClipBounds != null) {
16898                // clip bounds ignore scroll
16899                canvas.clipRect(mClipBounds);
16900            }
16901        }
16902
16903        if (!drawingWithDrawingCache) {
16904            if (drawingWithRenderNode) {
16905                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16906                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16907            } else {
16908                // Fast path for layouts with no backgrounds
16909                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16910                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16911                    dispatchDraw(canvas);
16912                } else {
16913                    draw(canvas);
16914                }
16915            }
16916        } else if (cache != null) {
16917            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16918            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
16919                // no layer paint, use temporary paint to draw bitmap
16920                Paint cachePaint = parent.mCachePaint;
16921                if (cachePaint == null) {
16922                    cachePaint = new Paint();
16923                    cachePaint.setDither(false);
16924                    parent.mCachePaint = cachePaint;
16925                }
16926                cachePaint.setAlpha((int) (alpha * 255));
16927                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16928            } else {
16929                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16930                int layerPaintAlpha = mLayerPaint.getAlpha();
16931                if (alpha < 1) {
16932                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16933                }
16934                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
16935                if (alpha < 1) {
16936                    mLayerPaint.setAlpha(layerPaintAlpha);
16937                }
16938            }
16939        }
16940
16941        if (restoreTo >= 0) {
16942            canvas.restoreToCount(restoreTo);
16943        }
16944
16945        if (a != null && !more) {
16946            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
16947                onSetAlpha(255);
16948            }
16949            parent.finishAnimatingView(this, a);
16950        }
16951
16952        if (more && hardwareAcceleratedCanvas) {
16953            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16954                // alpha animations should cause the child to recreate its display list
16955                invalidate(true);
16956            }
16957        }
16958
16959        mRecreateDisplayList = false;
16960
16961        return more;
16962    }
16963
16964    /**
16965     * Manually render this view (and all of its children) to the given Canvas.
16966     * The view must have already done a full layout before this function is
16967     * called.  When implementing a view, implement
16968     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
16969     * If you do need to override this method, call the superclass version.
16970     *
16971     * @param canvas The Canvas to which the View is rendered.
16972     */
16973    @CallSuper
16974    public void draw(Canvas canvas) {
16975        final int privateFlags = mPrivateFlags;
16976        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
16977                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
16978        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
16979
16980        /*
16981         * Draw traversal performs several drawing steps which must be executed
16982         * in the appropriate order:
16983         *
16984         *      1. Draw the background
16985         *      2. If necessary, save the canvas' layers to prepare for fading
16986         *      3. Draw view's content
16987         *      4. Draw children
16988         *      5. If necessary, draw the fading edges and restore layers
16989         *      6. Draw decorations (scrollbars for instance)
16990         */
16991
16992        // Step 1, draw the background, if needed
16993        int saveCount;
16994
16995        if (!dirtyOpaque) {
16996            drawBackground(canvas);
16997        }
16998
16999        // skip step 2 & 5 if possible (common case)
17000        final int viewFlags = mViewFlags;
17001        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17002        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17003        if (!verticalEdges && !horizontalEdges) {
17004            // Step 3, draw the content
17005            if (!dirtyOpaque) onDraw(canvas);
17006
17007            // Step 4, draw the children
17008            dispatchDraw(canvas);
17009
17010            // Overlay is part of the content and draws beneath Foreground
17011            if (mOverlay != null && !mOverlay.isEmpty()) {
17012                mOverlay.getOverlayView().dispatchDraw(canvas);
17013            }
17014
17015            // Step 6, draw decorations (foreground, scrollbars)
17016            onDrawForeground(canvas);
17017
17018            // we're done...
17019            return;
17020        }
17021
17022        /*
17023         * Here we do the full fledged routine...
17024         * (this is an uncommon case where speed matters less,
17025         * this is why we repeat some of the tests that have been
17026         * done above)
17027         */
17028
17029        boolean drawTop = false;
17030        boolean drawBottom = false;
17031        boolean drawLeft = false;
17032        boolean drawRight = false;
17033
17034        float topFadeStrength = 0.0f;
17035        float bottomFadeStrength = 0.0f;
17036        float leftFadeStrength = 0.0f;
17037        float rightFadeStrength = 0.0f;
17038
17039        // Step 2, save the canvas' layers
17040        int paddingLeft = mPaddingLeft;
17041
17042        final boolean offsetRequired = isPaddingOffsetRequired();
17043        if (offsetRequired) {
17044            paddingLeft += getLeftPaddingOffset();
17045        }
17046
17047        int left = mScrollX + paddingLeft;
17048        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17049        int top = mScrollY + getFadeTop(offsetRequired);
17050        int bottom = top + getFadeHeight(offsetRequired);
17051
17052        if (offsetRequired) {
17053            right += getRightPaddingOffset();
17054            bottom += getBottomPaddingOffset();
17055        }
17056
17057        final ScrollabilityCache scrollabilityCache = mScrollCache;
17058        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17059        int length = (int) fadeHeight;
17060
17061        // clip the fade length if top and bottom fades overlap
17062        // overlapping fades produce odd-looking artifacts
17063        if (verticalEdges && (top + length > bottom - length)) {
17064            length = (bottom - top) / 2;
17065        }
17066
17067        // also clip horizontal fades if necessary
17068        if (horizontalEdges && (left + length > right - length)) {
17069            length = (right - left) / 2;
17070        }
17071
17072        if (verticalEdges) {
17073            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17074            drawTop = topFadeStrength * fadeHeight > 1.0f;
17075            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17076            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17077        }
17078
17079        if (horizontalEdges) {
17080            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17081            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17082            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17083            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17084        }
17085
17086        saveCount = canvas.getSaveCount();
17087
17088        int solidColor = getSolidColor();
17089        if (solidColor == 0) {
17090            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17091
17092            if (drawTop) {
17093                canvas.saveLayer(left, top, right, top + length, null, flags);
17094            }
17095
17096            if (drawBottom) {
17097                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17098            }
17099
17100            if (drawLeft) {
17101                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17102            }
17103
17104            if (drawRight) {
17105                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17106            }
17107        } else {
17108            scrollabilityCache.setFadeColor(solidColor);
17109        }
17110
17111        // Step 3, draw the content
17112        if (!dirtyOpaque) onDraw(canvas);
17113
17114        // Step 4, draw the children
17115        dispatchDraw(canvas);
17116
17117        // Step 5, draw the fade effect and restore layers
17118        final Paint p = scrollabilityCache.paint;
17119        final Matrix matrix = scrollabilityCache.matrix;
17120        final Shader fade = scrollabilityCache.shader;
17121
17122        if (drawTop) {
17123            matrix.setScale(1, fadeHeight * topFadeStrength);
17124            matrix.postTranslate(left, top);
17125            fade.setLocalMatrix(matrix);
17126            p.setShader(fade);
17127            canvas.drawRect(left, top, right, top + length, p);
17128        }
17129
17130        if (drawBottom) {
17131            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17132            matrix.postRotate(180);
17133            matrix.postTranslate(left, bottom);
17134            fade.setLocalMatrix(matrix);
17135            p.setShader(fade);
17136            canvas.drawRect(left, bottom - length, right, bottom, p);
17137        }
17138
17139        if (drawLeft) {
17140            matrix.setScale(1, fadeHeight * leftFadeStrength);
17141            matrix.postRotate(-90);
17142            matrix.postTranslate(left, top);
17143            fade.setLocalMatrix(matrix);
17144            p.setShader(fade);
17145            canvas.drawRect(left, top, left + length, bottom, p);
17146        }
17147
17148        if (drawRight) {
17149            matrix.setScale(1, fadeHeight * rightFadeStrength);
17150            matrix.postRotate(90);
17151            matrix.postTranslate(right, top);
17152            fade.setLocalMatrix(matrix);
17153            p.setShader(fade);
17154            canvas.drawRect(right - length, top, right, bottom, p);
17155        }
17156
17157        canvas.restoreToCount(saveCount);
17158
17159        // Overlay is part of the content and draws beneath Foreground
17160        if (mOverlay != null && !mOverlay.isEmpty()) {
17161            mOverlay.getOverlayView().dispatchDraw(canvas);
17162        }
17163
17164        // Step 6, draw decorations (foreground, scrollbars)
17165        onDrawForeground(canvas);
17166    }
17167
17168    /**
17169     * Draws the background onto the specified canvas.
17170     *
17171     * @param canvas Canvas on which to draw the background
17172     */
17173    private void drawBackground(Canvas canvas) {
17174        final Drawable background = mBackground;
17175        if (background == null) {
17176            return;
17177        }
17178
17179        setBackgroundBounds();
17180
17181        // Attempt to use a display list if requested.
17182        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17183                && mAttachInfo.mHardwareRenderer != null) {
17184            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17185
17186            final RenderNode renderNode = mBackgroundRenderNode;
17187            if (renderNode != null && renderNode.isValid()) {
17188                setBackgroundRenderNodeProperties(renderNode);
17189                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17190                return;
17191            }
17192        }
17193
17194        final int scrollX = mScrollX;
17195        final int scrollY = mScrollY;
17196        if ((scrollX | scrollY) == 0) {
17197            background.draw(canvas);
17198        } else {
17199            canvas.translate(scrollX, scrollY);
17200            background.draw(canvas);
17201            canvas.translate(-scrollX, -scrollY);
17202        }
17203    }
17204
17205    /**
17206     * Sets the correct background bounds and rebuilds the outline, if needed.
17207     * <p/>
17208     * This is called by LayoutLib.
17209     */
17210    void setBackgroundBounds() {
17211        if (mBackgroundSizeChanged && mBackground != null) {
17212            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17213            mBackgroundSizeChanged = false;
17214            rebuildOutline();
17215        }
17216    }
17217
17218    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17219        renderNode.setTranslationX(mScrollX);
17220        renderNode.setTranslationY(mScrollY);
17221    }
17222
17223    /**
17224     * Creates a new display list or updates the existing display list for the
17225     * specified Drawable.
17226     *
17227     * @param drawable Drawable for which to create a display list
17228     * @param renderNode Existing RenderNode, or {@code null}
17229     * @return A valid display list for the specified drawable
17230     */
17231    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17232        if (renderNode == null) {
17233            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17234        }
17235
17236        final Rect bounds = drawable.getBounds();
17237        final int width = bounds.width();
17238        final int height = bounds.height();
17239        final DisplayListCanvas canvas = renderNode.start(width, height);
17240
17241        // Reverse left/top translation done by drawable canvas, which will
17242        // instead be applied by rendernode's LTRB bounds below. This way, the
17243        // drawable's bounds match with its rendernode bounds and its content
17244        // will lie within those bounds in the rendernode tree.
17245        canvas.translate(-bounds.left, -bounds.top);
17246
17247        try {
17248            drawable.draw(canvas);
17249        } finally {
17250            renderNode.end(canvas);
17251        }
17252
17253        // Set up drawable properties that are view-independent.
17254        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17255        renderNode.setProjectBackwards(drawable.isProjected());
17256        renderNode.setProjectionReceiver(true);
17257        renderNode.setClipToBounds(false);
17258        return renderNode;
17259    }
17260
17261    /**
17262     * Returns the overlay for this view, creating it if it does not yet exist.
17263     * Adding drawables to the overlay will cause them to be displayed whenever
17264     * the view itself is redrawn. Objects in the overlay should be actively
17265     * managed: remove them when they should not be displayed anymore. The
17266     * overlay will always have the same size as its host view.
17267     *
17268     * <p>Note: Overlays do not currently work correctly with {@link
17269     * SurfaceView} or {@link TextureView}; contents in overlays for these
17270     * types of views may not display correctly.</p>
17271     *
17272     * @return The ViewOverlay object for this view.
17273     * @see ViewOverlay
17274     */
17275    public ViewOverlay getOverlay() {
17276        if (mOverlay == null) {
17277            mOverlay = new ViewOverlay(mContext, this);
17278        }
17279        return mOverlay;
17280    }
17281
17282    /**
17283     * Override this if your view is known to always be drawn on top of a solid color background,
17284     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17285     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17286     * should be set to 0xFF.
17287     *
17288     * @see #setVerticalFadingEdgeEnabled(boolean)
17289     * @see #setHorizontalFadingEdgeEnabled(boolean)
17290     *
17291     * @return The known solid color background for this view, or 0 if the color may vary
17292     */
17293    @ViewDebug.ExportedProperty(category = "drawing")
17294    @ColorInt
17295    public int getSolidColor() {
17296        return 0;
17297    }
17298
17299    /**
17300     * Build a human readable string representation of the specified view flags.
17301     *
17302     * @param flags the view flags to convert to a string
17303     * @return a String representing the supplied flags
17304     */
17305    private static String printFlags(int flags) {
17306        String output = "";
17307        int numFlags = 0;
17308        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17309            output += "TAKES_FOCUS";
17310            numFlags++;
17311        }
17312
17313        switch (flags & VISIBILITY_MASK) {
17314        case INVISIBLE:
17315            if (numFlags > 0) {
17316                output += " ";
17317            }
17318            output += "INVISIBLE";
17319            // USELESS HERE numFlags++;
17320            break;
17321        case GONE:
17322            if (numFlags > 0) {
17323                output += " ";
17324            }
17325            output += "GONE";
17326            // USELESS HERE numFlags++;
17327            break;
17328        default:
17329            break;
17330        }
17331        return output;
17332    }
17333
17334    /**
17335     * Build a human readable string representation of the specified private
17336     * view flags.
17337     *
17338     * @param privateFlags the private view flags to convert to a string
17339     * @return a String representing the supplied flags
17340     */
17341    private static String printPrivateFlags(int privateFlags) {
17342        String output = "";
17343        int numFlags = 0;
17344
17345        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17346            output += "WANTS_FOCUS";
17347            numFlags++;
17348        }
17349
17350        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17351            if (numFlags > 0) {
17352                output += " ";
17353            }
17354            output += "FOCUSED";
17355            numFlags++;
17356        }
17357
17358        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17359            if (numFlags > 0) {
17360                output += " ";
17361            }
17362            output += "SELECTED";
17363            numFlags++;
17364        }
17365
17366        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17367            if (numFlags > 0) {
17368                output += " ";
17369            }
17370            output += "IS_ROOT_NAMESPACE";
17371            numFlags++;
17372        }
17373
17374        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17375            if (numFlags > 0) {
17376                output += " ";
17377            }
17378            output += "HAS_BOUNDS";
17379            numFlags++;
17380        }
17381
17382        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17383            if (numFlags > 0) {
17384                output += " ";
17385            }
17386            output += "DRAWN";
17387            // USELESS HERE numFlags++;
17388        }
17389        return output;
17390    }
17391
17392    /**
17393     * <p>Indicates whether or not this view's layout will be requested during
17394     * the next hierarchy layout pass.</p>
17395     *
17396     * @return true if the layout will be forced during next layout pass
17397     */
17398    public boolean isLayoutRequested() {
17399        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17400    }
17401
17402    /**
17403     * Return true if o is a ViewGroup that is laying out using optical bounds.
17404     * @hide
17405     */
17406    public static boolean isLayoutModeOptical(Object o) {
17407        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17408    }
17409
17410    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17411        Insets parentInsets = mParent instanceof View ?
17412                ((View) mParent).getOpticalInsets() : Insets.NONE;
17413        Insets childInsets = getOpticalInsets();
17414        return setFrame(
17415                left   + parentInsets.left - childInsets.left,
17416                top    + parentInsets.top  - childInsets.top,
17417                right  + parentInsets.left + childInsets.right,
17418                bottom + parentInsets.top  + childInsets.bottom);
17419    }
17420
17421    /**
17422     * Assign a size and position to a view and all of its
17423     * descendants
17424     *
17425     * <p>This is the second phase of the layout mechanism.
17426     * (The first is measuring). In this phase, each parent calls
17427     * layout on all of its children to position them.
17428     * This is typically done using the child measurements
17429     * that were stored in the measure pass().</p>
17430     *
17431     * <p>Derived classes should not override this method.
17432     * Derived classes with children should override
17433     * onLayout. In that method, they should
17434     * call layout on each of their children.</p>
17435     *
17436     * @param l Left position, relative to parent
17437     * @param t Top position, relative to parent
17438     * @param r Right position, relative to parent
17439     * @param b Bottom position, relative to parent
17440     */
17441    @SuppressWarnings({"unchecked"})
17442    public void layout(int l, int t, int r, int b) {
17443        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17444            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17445            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17446        }
17447
17448        int oldL = mLeft;
17449        int oldT = mTop;
17450        int oldB = mBottom;
17451        int oldR = mRight;
17452
17453        boolean changed = isLayoutModeOptical(mParent) ?
17454                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17455
17456        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17457            onLayout(changed, l, t, r, b);
17458            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17459
17460            ListenerInfo li = mListenerInfo;
17461            if (li != null && li.mOnLayoutChangeListeners != null) {
17462                ArrayList<OnLayoutChangeListener> listenersCopy =
17463                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17464                int numListeners = listenersCopy.size();
17465                for (int i = 0; i < numListeners; ++i) {
17466                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17467                }
17468            }
17469        }
17470
17471        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17472        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17473    }
17474
17475    /**
17476     * Called from layout when this view should
17477     * assign a size and position to each of its children.
17478     *
17479     * Derived classes with children should override
17480     * this method and call layout on each of
17481     * their children.
17482     * @param changed This is a new size or position for this view
17483     * @param left Left position, relative to parent
17484     * @param top Top position, relative to parent
17485     * @param right Right position, relative to parent
17486     * @param bottom Bottom position, relative to parent
17487     */
17488    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17489    }
17490
17491    /**
17492     * Assign a size and position to this view.
17493     *
17494     * This is called from layout.
17495     *
17496     * @param left Left position, relative to parent
17497     * @param top Top position, relative to parent
17498     * @param right Right position, relative to parent
17499     * @param bottom Bottom position, relative to parent
17500     * @return true if the new size and position are different than the
17501     *         previous ones
17502     * {@hide}
17503     */
17504    protected boolean setFrame(int left, int top, int right, int bottom) {
17505        boolean changed = false;
17506
17507        if (DBG) {
17508            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17509                    + right + "," + bottom + ")");
17510        }
17511
17512        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17513            changed = true;
17514
17515            // Remember our drawn bit
17516            int drawn = mPrivateFlags & PFLAG_DRAWN;
17517
17518            int oldWidth = mRight - mLeft;
17519            int oldHeight = mBottom - mTop;
17520            int newWidth = right - left;
17521            int newHeight = bottom - top;
17522            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17523
17524            // Invalidate our old position
17525            invalidate(sizeChanged);
17526
17527            mLeft = left;
17528            mTop = top;
17529            mRight = right;
17530            mBottom = bottom;
17531            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17532
17533            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17534
17535
17536            if (sizeChanged) {
17537                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17538            }
17539
17540            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17541                // If we are visible, force the DRAWN bit to on so that
17542                // this invalidate will go through (at least to our parent).
17543                // This is because someone may have invalidated this view
17544                // before this call to setFrame came in, thereby clearing
17545                // the DRAWN bit.
17546                mPrivateFlags |= PFLAG_DRAWN;
17547                invalidate(sizeChanged);
17548                // parent display list may need to be recreated based on a change in the bounds
17549                // of any child
17550                invalidateParentCaches();
17551            }
17552
17553            // Reset drawn bit to original value (invalidate turns it off)
17554            mPrivateFlags |= drawn;
17555
17556            mBackgroundSizeChanged = true;
17557            if (mForegroundInfo != null) {
17558                mForegroundInfo.mBoundsChanged = true;
17559            }
17560
17561            notifySubtreeAccessibilityStateChangedIfNeeded();
17562        }
17563        return changed;
17564    }
17565
17566    /**
17567     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17568     * @hide
17569     */
17570    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17571        setFrame(left, top, right, bottom);
17572    }
17573
17574    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17575        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17576        if (mOverlay != null) {
17577            mOverlay.getOverlayView().setRight(newWidth);
17578            mOverlay.getOverlayView().setBottom(newHeight);
17579        }
17580        rebuildOutline();
17581    }
17582
17583    /**
17584     * Finalize inflating a view from XML.  This is called as the last phase
17585     * of inflation, after all child views have been added.
17586     *
17587     * <p>Even if the subclass overrides onFinishInflate, they should always be
17588     * sure to call the super method, so that we get called.
17589     */
17590    @CallSuper
17591    protected void onFinishInflate() {
17592    }
17593
17594    /**
17595     * Returns the resources associated with this view.
17596     *
17597     * @return Resources object.
17598     */
17599    public Resources getResources() {
17600        return mResources;
17601    }
17602
17603    /**
17604     * Invalidates the specified Drawable.
17605     *
17606     * @param drawable the drawable to invalidate
17607     */
17608    @Override
17609    public void invalidateDrawable(@NonNull Drawable drawable) {
17610        if (verifyDrawable(drawable)) {
17611            final Rect dirty = drawable.getDirtyBounds();
17612            final int scrollX = mScrollX;
17613            final int scrollY = mScrollY;
17614
17615            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17616                    dirty.right + scrollX, dirty.bottom + scrollY);
17617            rebuildOutline();
17618        }
17619    }
17620
17621    /**
17622     * Schedules an action on a drawable to occur at a specified time.
17623     *
17624     * @param who the recipient of the action
17625     * @param what the action to run on the drawable
17626     * @param when the time at which the action must occur. Uses the
17627     *        {@link SystemClock#uptimeMillis} timebase.
17628     */
17629    @Override
17630    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17631        if (verifyDrawable(who) && what != null) {
17632            final long delay = when - SystemClock.uptimeMillis();
17633            if (mAttachInfo != null) {
17634                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17635                        Choreographer.CALLBACK_ANIMATION, what, who,
17636                        Choreographer.subtractFrameDelay(delay));
17637            } else {
17638                // Postpone the runnable until we know
17639                // on which thread it needs to run.
17640                getRunQueue().postDelayed(what, delay);
17641            }
17642        }
17643    }
17644
17645    /**
17646     * Cancels a scheduled action on a drawable.
17647     *
17648     * @param who the recipient of the action
17649     * @param what the action to cancel
17650     */
17651    @Override
17652    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17653        if (verifyDrawable(who) && what != null) {
17654            if (mAttachInfo != null) {
17655                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17656                        Choreographer.CALLBACK_ANIMATION, what, who);
17657            }
17658            getRunQueue().removeCallbacks(what);
17659        }
17660    }
17661
17662    /**
17663     * Unschedule any events associated with the given Drawable.  This can be
17664     * used when selecting a new Drawable into a view, so that the previous
17665     * one is completely unscheduled.
17666     *
17667     * @param who The Drawable to unschedule.
17668     *
17669     * @see #drawableStateChanged
17670     */
17671    public void unscheduleDrawable(Drawable who) {
17672        if (mAttachInfo != null && who != null) {
17673            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17674                    Choreographer.CALLBACK_ANIMATION, null, who);
17675        }
17676    }
17677
17678    /**
17679     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17680     * that the View directionality can and will be resolved before its Drawables.
17681     *
17682     * Will call {@link View#onResolveDrawables} when resolution is done.
17683     *
17684     * @hide
17685     */
17686    protected void resolveDrawables() {
17687        // Drawables resolution may need to happen before resolving the layout direction (which is
17688        // done only during the measure() call).
17689        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17690        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17691        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17692        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17693        // direction to be resolved as its resolved value will be the same as its raw value.
17694        if (!isLayoutDirectionResolved() &&
17695                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17696            return;
17697        }
17698
17699        final int layoutDirection = isLayoutDirectionResolved() ?
17700                getLayoutDirection() : getRawLayoutDirection();
17701
17702        if (mBackground != null) {
17703            mBackground.setLayoutDirection(layoutDirection);
17704        }
17705        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17706            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17707        }
17708        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17709        onResolveDrawables(layoutDirection);
17710    }
17711
17712    boolean areDrawablesResolved() {
17713        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17714    }
17715
17716    /**
17717     * Called when layout direction has been resolved.
17718     *
17719     * The default implementation does nothing.
17720     *
17721     * @param layoutDirection The resolved layout direction.
17722     *
17723     * @see #LAYOUT_DIRECTION_LTR
17724     * @see #LAYOUT_DIRECTION_RTL
17725     *
17726     * @hide
17727     */
17728    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17729    }
17730
17731    /**
17732     * @hide
17733     */
17734    protected void resetResolvedDrawables() {
17735        resetResolvedDrawablesInternal();
17736    }
17737
17738    void resetResolvedDrawablesInternal() {
17739        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17740    }
17741
17742    /**
17743     * If your view subclass is displaying its own Drawable objects, it should
17744     * override this function and return true for any Drawable it is
17745     * displaying.  This allows animations for those drawables to be
17746     * scheduled.
17747     *
17748     * <p>Be sure to call through to the super class when overriding this
17749     * function.
17750     *
17751     * @param who The Drawable to verify.  Return true if it is one you are
17752     *            displaying, else return the result of calling through to the
17753     *            super class.
17754     *
17755     * @return boolean If true than the Drawable is being displayed in the
17756     *         view; else false and it is not allowed to animate.
17757     *
17758     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17759     * @see #drawableStateChanged()
17760     */
17761    @CallSuper
17762    protected boolean verifyDrawable(@NonNull Drawable who) {
17763        // Avoid verifying the scroll bar drawable so that we don't end up in
17764        // an invalidation loop. This effectively prevents the scroll bar
17765        // drawable from triggering invalidations and scheduling runnables.
17766        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17767    }
17768
17769    /**
17770     * This function is called whenever the state of the view changes in such
17771     * a way that it impacts the state of drawables being shown.
17772     * <p>
17773     * If the View has a StateListAnimator, it will also be called to run necessary state
17774     * change animations.
17775     * <p>
17776     * Be sure to call through to the superclass when overriding this function.
17777     *
17778     * @see Drawable#setState(int[])
17779     */
17780    @CallSuper
17781    protected void drawableStateChanged() {
17782        final int[] state = getDrawableState();
17783        boolean changed = false;
17784
17785        final Drawable bg = mBackground;
17786        if (bg != null && bg.isStateful()) {
17787            changed |= bg.setState(state);
17788        }
17789
17790        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17791        if (fg != null && fg.isStateful()) {
17792            changed |= fg.setState(state);
17793        }
17794
17795        if (mScrollCache != null) {
17796            final Drawable scrollBar = mScrollCache.scrollBar;
17797            if (scrollBar != null && scrollBar.isStateful()) {
17798                changed |= scrollBar.setState(state)
17799                        && mScrollCache.state != ScrollabilityCache.OFF;
17800            }
17801        }
17802
17803        if (mStateListAnimator != null) {
17804            mStateListAnimator.setState(state);
17805        }
17806
17807        if (changed) {
17808            invalidate();
17809        }
17810    }
17811
17812    /**
17813     * This function is called whenever the view hotspot changes and needs to
17814     * be propagated to drawables or child views managed by the view.
17815     * <p>
17816     * Dispatching to child views is handled by
17817     * {@link #dispatchDrawableHotspotChanged(float, float)}.
17818     * <p>
17819     * Be sure to call through to the superclass when overriding this function.
17820     *
17821     * @param x hotspot x coordinate
17822     * @param y hotspot y coordinate
17823     */
17824    @CallSuper
17825    public void drawableHotspotChanged(float x, float y) {
17826        if (mBackground != null) {
17827            mBackground.setHotspot(x, y);
17828        }
17829        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17830            mForegroundInfo.mDrawable.setHotspot(x, y);
17831        }
17832
17833        dispatchDrawableHotspotChanged(x, y);
17834    }
17835
17836    /**
17837     * Dispatches drawableHotspotChanged to all of this View's children.
17838     *
17839     * @param x hotspot x coordinate
17840     * @param y hotspot y coordinate
17841     * @see #drawableHotspotChanged(float, float)
17842     */
17843    public void dispatchDrawableHotspotChanged(float x, float y) {
17844    }
17845
17846    /**
17847     * Call this to force a view to update its drawable state. This will cause
17848     * drawableStateChanged to be called on this view. Views that are interested
17849     * in the new state should call getDrawableState.
17850     *
17851     * @see #drawableStateChanged
17852     * @see #getDrawableState
17853     */
17854    public void refreshDrawableState() {
17855        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17856        drawableStateChanged();
17857
17858        ViewParent parent = mParent;
17859        if (parent != null) {
17860            parent.childDrawableStateChanged(this);
17861        }
17862    }
17863
17864    /**
17865     * Return an array of resource IDs of the drawable states representing the
17866     * current state of the view.
17867     *
17868     * @return The current drawable state
17869     *
17870     * @see Drawable#setState(int[])
17871     * @see #drawableStateChanged()
17872     * @see #onCreateDrawableState(int)
17873     */
17874    public final int[] getDrawableState() {
17875        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17876            return mDrawableState;
17877        } else {
17878            mDrawableState = onCreateDrawableState(0);
17879            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17880            return mDrawableState;
17881        }
17882    }
17883
17884    /**
17885     * Generate the new {@link android.graphics.drawable.Drawable} state for
17886     * this view. This is called by the view
17887     * system when the cached Drawable state is determined to be invalid.  To
17888     * retrieve the current state, you should use {@link #getDrawableState}.
17889     *
17890     * @param extraSpace if non-zero, this is the number of extra entries you
17891     * would like in the returned array in which you can place your own
17892     * states.
17893     *
17894     * @return Returns an array holding the current {@link Drawable} state of
17895     * the view.
17896     *
17897     * @see #mergeDrawableStates(int[], int[])
17898     */
17899    protected int[] onCreateDrawableState(int extraSpace) {
17900        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17901                mParent instanceof View) {
17902            return ((View) mParent).onCreateDrawableState(extraSpace);
17903        }
17904
17905        int[] drawableState;
17906
17907        int privateFlags = mPrivateFlags;
17908
17909        int viewStateIndex = 0;
17910        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17911        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17912        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17913        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17914        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17915        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17916        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17917                ThreadedRenderer.isAvailable()) {
17918            // This is set if HW acceleration is requested, even if the current
17919            // process doesn't allow it.  This is just to allow app preview
17920            // windows to better match their app.
17921            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17922        }
17923        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17924
17925        final int privateFlags2 = mPrivateFlags2;
17926        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17927            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17928        }
17929        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17930            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17931        }
17932
17933        drawableState = StateSet.get(viewStateIndex);
17934
17935        //noinspection ConstantIfStatement
17936        if (false) {
17937            Log.i("View", "drawableStateIndex=" + viewStateIndex);
17938            Log.i("View", toString()
17939                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
17940                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
17941                    + " fo=" + hasFocus()
17942                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
17943                    + " wf=" + hasWindowFocus()
17944                    + ": " + Arrays.toString(drawableState));
17945        }
17946
17947        if (extraSpace == 0) {
17948            return drawableState;
17949        }
17950
17951        final int[] fullState;
17952        if (drawableState != null) {
17953            fullState = new int[drawableState.length + extraSpace];
17954            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
17955        } else {
17956            fullState = new int[extraSpace];
17957        }
17958
17959        return fullState;
17960    }
17961
17962    /**
17963     * Merge your own state values in <var>additionalState</var> into the base
17964     * state values <var>baseState</var> that were returned by
17965     * {@link #onCreateDrawableState(int)}.
17966     *
17967     * @param baseState The base state values returned by
17968     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
17969     * own additional state values.
17970     *
17971     * @param additionalState The additional state values you would like
17972     * added to <var>baseState</var>; this array is not modified.
17973     *
17974     * @return As a convenience, the <var>baseState</var> array you originally
17975     * passed into the function is returned.
17976     *
17977     * @see #onCreateDrawableState(int)
17978     */
17979    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
17980        final int N = baseState.length;
17981        int i = N - 1;
17982        while (i >= 0 && baseState[i] == 0) {
17983            i--;
17984        }
17985        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
17986        return baseState;
17987    }
17988
17989    /**
17990     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
17991     * on all Drawable objects associated with this view.
17992     * <p>
17993     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
17994     * attached to this view.
17995     */
17996    @CallSuper
17997    public void jumpDrawablesToCurrentState() {
17998        if (mBackground != null) {
17999            mBackground.jumpToCurrentState();
18000        }
18001        if (mStateListAnimator != null) {
18002            mStateListAnimator.jumpToCurrentState();
18003        }
18004        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18005            mForegroundInfo.mDrawable.jumpToCurrentState();
18006        }
18007    }
18008
18009    /**
18010     * Sets the background color for this view.
18011     * @param color the color of the background
18012     */
18013    @RemotableViewMethod
18014    public void setBackgroundColor(@ColorInt int color) {
18015        if (mBackground instanceof ColorDrawable) {
18016            ((ColorDrawable) mBackground.mutate()).setColor(color);
18017            computeOpaqueFlags();
18018            mBackgroundResource = 0;
18019        } else {
18020            setBackground(new ColorDrawable(color));
18021        }
18022    }
18023
18024    /**
18025     * Set the background to a given resource. The resource should refer to
18026     * a Drawable object or 0 to remove the background.
18027     * @param resid The identifier of the resource.
18028     *
18029     * @attr ref android.R.styleable#View_background
18030     */
18031    @RemotableViewMethod
18032    public void setBackgroundResource(@DrawableRes int resid) {
18033        if (resid != 0 && resid == mBackgroundResource) {
18034            return;
18035        }
18036
18037        Drawable d = null;
18038        if (resid != 0) {
18039            d = mContext.getDrawable(resid);
18040        }
18041        setBackground(d);
18042
18043        mBackgroundResource = resid;
18044    }
18045
18046    /**
18047     * Set the background to a given Drawable, or remove the background. If the
18048     * background has padding, this View's padding is set to the background's
18049     * padding. However, when a background is removed, this View's padding isn't
18050     * touched. If setting the padding is desired, please use
18051     * {@link #setPadding(int, int, int, int)}.
18052     *
18053     * @param background The Drawable to use as the background, or null to remove the
18054     *        background
18055     */
18056    public void setBackground(Drawable background) {
18057        //noinspection deprecation
18058        setBackgroundDrawable(background);
18059    }
18060
18061    /**
18062     * @deprecated use {@link #setBackground(Drawable)} instead
18063     */
18064    @Deprecated
18065    public void setBackgroundDrawable(Drawable background) {
18066        computeOpaqueFlags();
18067
18068        if (background == mBackground) {
18069            return;
18070        }
18071
18072        boolean requestLayout = false;
18073
18074        mBackgroundResource = 0;
18075
18076        /*
18077         * Regardless of whether we're setting a new background or not, we want
18078         * to clear the previous drawable. setVisible first while we still have the callback set.
18079         */
18080        if (mBackground != null) {
18081            if (isAttachedToWindow()) {
18082                mBackground.setVisible(false, false);
18083            }
18084            mBackground.setCallback(null);
18085            unscheduleDrawable(mBackground);
18086        }
18087
18088        if (background != null) {
18089            Rect padding = sThreadLocal.get();
18090            if (padding == null) {
18091                padding = new Rect();
18092                sThreadLocal.set(padding);
18093            }
18094            resetResolvedDrawablesInternal();
18095            background.setLayoutDirection(getLayoutDirection());
18096            if (background.getPadding(padding)) {
18097                resetResolvedPaddingInternal();
18098                switch (background.getLayoutDirection()) {
18099                    case LAYOUT_DIRECTION_RTL:
18100                        mUserPaddingLeftInitial = padding.right;
18101                        mUserPaddingRightInitial = padding.left;
18102                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18103                        break;
18104                    case LAYOUT_DIRECTION_LTR:
18105                    default:
18106                        mUserPaddingLeftInitial = padding.left;
18107                        mUserPaddingRightInitial = padding.right;
18108                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18109                }
18110                mLeftPaddingDefined = false;
18111                mRightPaddingDefined = false;
18112            }
18113
18114            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18115            // if it has a different minimum size, we should layout again
18116            if (mBackground == null
18117                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18118                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18119                requestLayout = true;
18120            }
18121
18122            // Set mBackground before we set this as the callback and start making other
18123            // background drawable state change calls. In particular, the setVisible call below
18124            // can result in drawables attempting to start animations or otherwise invalidate,
18125            // which requires the view set as the callback (us) to recognize the drawable as
18126            // belonging to it as per verifyDrawable.
18127            mBackground = background;
18128            if (background.isStateful()) {
18129                background.setState(getDrawableState());
18130            }
18131            if (isAttachedToWindow()) {
18132                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18133            }
18134
18135            applyBackgroundTint();
18136
18137            // Set callback last, since the view may still be initializing.
18138            background.setCallback(this);
18139
18140            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18141                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18142                requestLayout = true;
18143            }
18144        } else {
18145            /* Remove the background */
18146            mBackground = null;
18147            if ((mViewFlags & WILL_NOT_DRAW) != 0
18148                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18149                mPrivateFlags |= PFLAG_SKIP_DRAW;
18150            }
18151
18152            /*
18153             * When the background is set, we try to apply its padding to this
18154             * View. When the background is removed, we don't touch this View's
18155             * padding. This is noted in the Javadocs. Hence, we don't need to
18156             * requestLayout(), the invalidate() below is sufficient.
18157             */
18158
18159            // The old background's minimum size could have affected this
18160            // View's layout, so let's requestLayout
18161            requestLayout = true;
18162        }
18163
18164        computeOpaqueFlags();
18165
18166        if (requestLayout) {
18167            requestLayout();
18168        }
18169
18170        mBackgroundSizeChanged = true;
18171        invalidate(true);
18172        invalidateOutline();
18173    }
18174
18175    /**
18176     * Gets the background drawable
18177     *
18178     * @return The drawable used as the background for this view, if any.
18179     *
18180     * @see #setBackground(Drawable)
18181     *
18182     * @attr ref android.R.styleable#View_background
18183     */
18184    public Drawable getBackground() {
18185        return mBackground;
18186    }
18187
18188    /**
18189     * Applies a tint to the background drawable. Does not modify the current tint
18190     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18191     * <p>
18192     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18193     * mutate the drawable and apply the specified tint and tint mode using
18194     * {@link Drawable#setTintList(ColorStateList)}.
18195     *
18196     * @param tint the tint to apply, may be {@code null} to clear tint
18197     *
18198     * @attr ref android.R.styleable#View_backgroundTint
18199     * @see #getBackgroundTintList()
18200     * @see Drawable#setTintList(ColorStateList)
18201     */
18202    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18203        if (mBackgroundTint == null) {
18204            mBackgroundTint = new TintInfo();
18205        }
18206        mBackgroundTint.mTintList = tint;
18207        mBackgroundTint.mHasTintList = true;
18208
18209        applyBackgroundTint();
18210    }
18211
18212    /**
18213     * Return the tint applied to the background drawable, if specified.
18214     *
18215     * @return the tint applied to the background drawable
18216     * @attr ref android.R.styleable#View_backgroundTint
18217     * @see #setBackgroundTintList(ColorStateList)
18218     */
18219    @Nullable
18220    public ColorStateList getBackgroundTintList() {
18221        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18222    }
18223
18224    /**
18225     * Specifies the blending mode used to apply the tint specified by
18226     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18227     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18228     *
18229     * @param tintMode the blending mode used to apply the tint, may be
18230     *                 {@code null} to clear tint
18231     * @attr ref android.R.styleable#View_backgroundTintMode
18232     * @see #getBackgroundTintMode()
18233     * @see Drawable#setTintMode(PorterDuff.Mode)
18234     */
18235    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18236        if (mBackgroundTint == null) {
18237            mBackgroundTint = new TintInfo();
18238        }
18239        mBackgroundTint.mTintMode = tintMode;
18240        mBackgroundTint.mHasTintMode = true;
18241
18242        applyBackgroundTint();
18243    }
18244
18245    /**
18246     * Return the blending mode used to apply the tint to the background
18247     * drawable, if specified.
18248     *
18249     * @return the blending mode used to apply the tint to the background
18250     *         drawable
18251     * @attr ref android.R.styleable#View_backgroundTintMode
18252     * @see #setBackgroundTintMode(PorterDuff.Mode)
18253     */
18254    @Nullable
18255    public PorterDuff.Mode getBackgroundTintMode() {
18256        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18257    }
18258
18259    private void applyBackgroundTint() {
18260        if (mBackground != null && mBackgroundTint != null) {
18261            final TintInfo tintInfo = mBackgroundTint;
18262            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18263                mBackground = mBackground.mutate();
18264
18265                if (tintInfo.mHasTintList) {
18266                    mBackground.setTintList(tintInfo.mTintList);
18267                }
18268
18269                if (tintInfo.mHasTintMode) {
18270                    mBackground.setTintMode(tintInfo.mTintMode);
18271                }
18272
18273                // The drawable (or one of its children) may not have been
18274                // stateful before applying the tint, so let's try again.
18275                if (mBackground.isStateful()) {
18276                    mBackground.setState(getDrawableState());
18277                }
18278            }
18279        }
18280    }
18281
18282    /**
18283     * Returns the drawable used as the foreground of this View. The
18284     * foreground drawable, if non-null, is always drawn on top of the view's content.
18285     *
18286     * @return a Drawable or null if no foreground was set
18287     *
18288     * @see #onDrawForeground(Canvas)
18289     */
18290    public Drawable getForeground() {
18291        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18292    }
18293
18294    /**
18295     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18296     *
18297     * @param foreground the Drawable to be drawn on top of the children
18298     *
18299     * @attr ref android.R.styleable#View_foreground
18300     */
18301    public void setForeground(Drawable foreground) {
18302        if (mForegroundInfo == null) {
18303            if (foreground == null) {
18304                // Nothing to do.
18305                return;
18306            }
18307            mForegroundInfo = new ForegroundInfo();
18308        }
18309
18310        if (foreground == mForegroundInfo.mDrawable) {
18311            // Nothing to do
18312            return;
18313        }
18314
18315        if (mForegroundInfo.mDrawable != null) {
18316            if (isAttachedToWindow()) {
18317                mForegroundInfo.mDrawable.setVisible(false, false);
18318            }
18319            mForegroundInfo.mDrawable.setCallback(null);
18320            unscheduleDrawable(mForegroundInfo.mDrawable);
18321        }
18322
18323        mForegroundInfo.mDrawable = foreground;
18324        mForegroundInfo.mBoundsChanged = true;
18325        if (foreground != null) {
18326            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18327                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18328            }
18329            foreground.setLayoutDirection(getLayoutDirection());
18330            if (foreground.isStateful()) {
18331                foreground.setState(getDrawableState());
18332            }
18333            applyForegroundTint();
18334            if (isAttachedToWindow()) {
18335                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18336            }
18337            // Set callback last, since the view may still be initializing.
18338            foreground.setCallback(this);
18339        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18340            mPrivateFlags |= PFLAG_SKIP_DRAW;
18341        }
18342        requestLayout();
18343        invalidate();
18344    }
18345
18346    /**
18347     * Magic bit used to support features of framework-internal window decor implementation details.
18348     * This used to live exclusively in FrameLayout.
18349     *
18350     * @return true if the foreground should draw inside the padding region or false
18351     *         if it should draw inset by the view's padding
18352     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18353     */
18354    public boolean isForegroundInsidePadding() {
18355        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18356    }
18357
18358    /**
18359     * Describes how the foreground is positioned.
18360     *
18361     * @return foreground gravity.
18362     *
18363     * @see #setForegroundGravity(int)
18364     *
18365     * @attr ref android.R.styleable#View_foregroundGravity
18366     */
18367    public int getForegroundGravity() {
18368        return mForegroundInfo != null ? mForegroundInfo.mGravity
18369                : Gravity.START | Gravity.TOP;
18370    }
18371
18372    /**
18373     * Describes how the foreground is positioned. Defaults to START and TOP.
18374     *
18375     * @param gravity see {@link android.view.Gravity}
18376     *
18377     * @see #getForegroundGravity()
18378     *
18379     * @attr ref android.R.styleable#View_foregroundGravity
18380     */
18381    public void setForegroundGravity(int gravity) {
18382        if (mForegroundInfo == null) {
18383            mForegroundInfo = new ForegroundInfo();
18384        }
18385
18386        if (mForegroundInfo.mGravity != gravity) {
18387            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18388                gravity |= Gravity.START;
18389            }
18390
18391            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18392                gravity |= Gravity.TOP;
18393            }
18394
18395            mForegroundInfo.mGravity = gravity;
18396            requestLayout();
18397        }
18398    }
18399
18400    /**
18401     * Applies a tint to the foreground drawable. Does not modify the current tint
18402     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18403     * <p>
18404     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18405     * mutate the drawable and apply the specified tint and tint mode using
18406     * {@link Drawable#setTintList(ColorStateList)}.
18407     *
18408     * @param tint the tint to apply, may be {@code null} to clear tint
18409     *
18410     * @attr ref android.R.styleable#View_foregroundTint
18411     * @see #getForegroundTintList()
18412     * @see Drawable#setTintList(ColorStateList)
18413     */
18414    public void setForegroundTintList(@Nullable ColorStateList tint) {
18415        if (mForegroundInfo == null) {
18416            mForegroundInfo = new ForegroundInfo();
18417        }
18418        if (mForegroundInfo.mTintInfo == null) {
18419            mForegroundInfo.mTintInfo = new TintInfo();
18420        }
18421        mForegroundInfo.mTintInfo.mTintList = tint;
18422        mForegroundInfo.mTintInfo.mHasTintList = true;
18423
18424        applyForegroundTint();
18425    }
18426
18427    /**
18428     * Return the tint applied to the foreground drawable, if specified.
18429     *
18430     * @return the tint applied to the foreground drawable
18431     * @attr ref android.R.styleable#View_foregroundTint
18432     * @see #setForegroundTintList(ColorStateList)
18433     */
18434    @Nullable
18435    public ColorStateList getForegroundTintList() {
18436        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18437                ? mForegroundInfo.mTintInfo.mTintList : null;
18438    }
18439
18440    /**
18441     * Specifies the blending mode used to apply the tint specified by
18442     * {@link #setForegroundTintList(ColorStateList)}} to the background
18443     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18444     *
18445     * @param tintMode the blending mode used to apply the tint, may be
18446     *                 {@code null} to clear tint
18447     * @attr ref android.R.styleable#View_foregroundTintMode
18448     * @see #getForegroundTintMode()
18449     * @see Drawable#setTintMode(PorterDuff.Mode)
18450     */
18451    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18452        if (mForegroundInfo == null) {
18453            mForegroundInfo = new ForegroundInfo();
18454        }
18455        if (mForegroundInfo.mTintInfo == null) {
18456            mForegroundInfo.mTintInfo = new TintInfo();
18457        }
18458        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18459        mForegroundInfo.mTintInfo.mHasTintMode = true;
18460
18461        applyForegroundTint();
18462    }
18463
18464    /**
18465     * Return the blending mode used to apply the tint to the foreground
18466     * drawable, if specified.
18467     *
18468     * @return the blending mode used to apply the tint to the foreground
18469     *         drawable
18470     * @attr ref android.R.styleable#View_foregroundTintMode
18471     * @see #setForegroundTintMode(PorterDuff.Mode)
18472     */
18473    @Nullable
18474    public PorterDuff.Mode getForegroundTintMode() {
18475        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18476                ? mForegroundInfo.mTintInfo.mTintMode : null;
18477    }
18478
18479    private void applyForegroundTint() {
18480        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18481                && mForegroundInfo.mTintInfo != null) {
18482            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18483            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18484                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18485
18486                if (tintInfo.mHasTintList) {
18487                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18488                }
18489
18490                if (tintInfo.mHasTintMode) {
18491                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18492                }
18493
18494                // The drawable (or one of its children) may not have been
18495                // stateful before applying the tint, so let's try again.
18496                if (mForegroundInfo.mDrawable.isStateful()) {
18497                    mForegroundInfo.mDrawable.setState(getDrawableState());
18498                }
18499            }
18500        }
18501    }
18502
18503    /**
18504     * Draw any foreground content for this view.
18505     *
18506     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18507     * drawable or other view-specific decorations. The foreground is drawn on top of the
18508     * primary view content.</p>
18509     *
18510     * @param canvas canvas to draw into
18511     */
18512    public void onDrawForeground(Canvas canvas) {
18513        onDrawScrollIndicators(canvas);
18514        onDrawScrollBars(canvas);
18515
18516        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18517        if (foreground != null) {
18518            if (mForegroundInfo.mBoundsChanged) {
18519                mForegroundInfo.mBoundsChanged = false;
18520                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18521                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18522
18523                if (mForegroundInfo.mInsidePadding) {
18524                    selfBounds.set(0, 0, getWidth(), getHeight());
18525                } else {
18526                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18527                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18528                }
18529
18530                final int ld = getLayoutDirection();
18531                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18532                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18533                foreground.setBounds(overlayBounds);
18534            }
18535
18536            foreground.draw(canvas);
18537        }
18538    }
18539
18540    /**
18541     * Sets the padding. The view may add on the space required to display
18542     * the scrollbars, depending on the style and visibility of the scrollbars.
18543     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18544     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18545     * from the values set in this call.
18546     *
18547     * @attr ref android.R.styleable#View_padding
18548     * @attr ref android.R.styleable#View_paddingBottom
18549     * @attr ref android.R.styleable#View_paddingLeft
18550     * @attr ref android.R.styleable#View_paddingRight
18551     * @attr ref android.R.styleable#View_paddingTop
18552     * @param left the left padding in pixels
18553     * @param top the top padding in pixels
18554     * @param right the right padding in pixels
18555     * @param bottom the bottom padding in pixels
18556     */
18557    public void setPadding(int left, int top, int right, int bottom) {
18558        resetResolvedPaddingInternal();
18559
18560        mUserPaddingStart = UNDEFINED_PADDING;
18561        mUserPaddingEnd = UNDEFINED_PADDING;
18562
18563        mUserPaddingLeftInitial = left;
18564        mUserPaddingRightInitial = right;
18565
18566        mLeftPaddingDefined = true;
18567        mRightPaddingDefined = true;
18568
18569        internalSetPadding(left, top, right, bottom);
18570    }
18571
18572    /**
18573     * @hide
18574     */
18575    protected void internalSetPadding(int left, int top, int right, int bottom) {
18576        mUserPaddingLeft = left;
18577        mUserPaddingRight = right;
18578        mUserPaddingBottom = bottom;
18579
18580        final int viewFlags = mViewFlags;
18581        boolean changed = false;
18582
18583        // Common case is there are no scroll bars.
18584        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18585            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18586                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18587                        ? 0 : getVerticalScrollbarWidth();
18588                switch (mVerticalScrollbarPosition) {
18589                    case SCROLLBAR_POSITION_DEFAULT:
18590                        if (isLayoutRtl()) {
18591                            left += offset;
18592                        } else {
18593                            right += offset;
18594                        }
18595                        break;
18596                    case SCROLLBAR_POSITION_RIGHT:
18597                        right += offset;
18598                        break;
18599                    case SCROLLBAR_POSITION_LEFT:
18600                        left += offset;
18601                        break;
18602                }
18603            }
18604            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18605                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18606                        ? 0 : getHorizontalScrollbarHeight();
18607            }
18608        }
18609
18610        if (mPaddingLeft != left) {
18611            changed = true;
18612            mPaddingLeft = left;
18613        }
18614        if (mPaddingTop != top) {
18615            changed = true;
18616            mPaddingTop = top;
18617        }
18618        if (mPaddingRight != right) {
18619            changed = true;
18620            mPaddingRight = right;
18621        }
18622        if (mPaddingBottom != bottom) {
18623            changed = true;
18624            mPaddingBottom = bottom;
18625        }
18626
18627        if (changed) {
18628            requestLayout();
18629            invalidateOutline();
18630        }
18631    }
18632
18633    /**
18634     * Sets the relative padding. The view may add on the space required to display
18635     * the scrollbars, depending on the style and visibility of the scrollbars.
18636     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18637     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18638     * from the values set in this call.
18639     *
18640     * @attr ref android.R.styleable#View_padding
18641     * @attr ref android.R.styleable#View_paddingBottom
18642     * @attr ref android.R.styleable#View_paddingStart
18643     * @attr ref android.R.styleable#View_paddingEnd
18644     * @attr ref android.R.styleable#View_paddingTop
18645     * @param start the start padding in pixels
18646     * @param top the top padding in pixels
18647     * @param end the end padding in pixels
18648     * @param bottom the bottom padding in pixels
18649     */
18650    public void setPaddingRelative(int start, int top, int end, int bottom) {
18651        resetResolvedPaddingInternal();
18652
18653        mUserPaddingStart = start;
18654        mUserPaddingEnd = end;
18655        mLeftPaddingDefined = true;
18656        mRightPaddingDefined = true;
18657
18658        switch(getLayoutDirection()) {
18659            case LAYOUT_DIRECTION_RTL:
18660                mUserPaddingLeftInitial = end;
18661                mUserPaddingRightInitial = start;
18662                internalSetPadding(end, top, start, bottom);
18663                break;
18664            case LAYOUT_DIRECTION_LTR:
18665            default:
18666                mUserPaddingLeftInitial = start;
18667                mUserPaddingRightInitial = end;
18668                internalSetPadding(start, top, end, bottom);
18669        }
18670    }
18671
18672    /**
18673     * Returns the top padding of this view.
18674     *
18675     * @return the top padding in pixels
18676     */
18677    public int getPaddingTop() {
18678        return mPaddingTop;
18679    }
18680
18681    /**
18682     * Returns the bottom padding of this view. If there are inset and enabled
18683     * scrollbars, this value may include the space required to display the
18684     * scrollbars as well.
18685     *
18686     * @return the bottom padding in pixels
18687     */
18688    public int getPaddingBottom() {
18689        return mPaddingBottom;
18690    }
18691
18692    /**
18693     * Returns the left padding of this view. If there are inset and enabled
18694     * scrollbars, this value may include the space required to display the
18695     * scrollbars as well.
18696     *
18697     * @return the left padding in pixels
18698     */
18699    public int getPaddingLeft() {
18700        if (!isPaddingResolved()) {
18701            resolvePadding();
18702        }
18703        return mPaddingLeft;
18704    }
18705
18706    /**
18707     * Returns the start padding of this view depending on its resolved layout direction.
18708     * If there are inset and enabled scrollbars, this value may include the space
18709     * required to display the scrollbars as well.
18710     *
18711     * @return the start padding in pixels
18712     */
18713    public int getPaddingStart() {
18714        if (!isPaddingResolved()) {
18715            resolvePadding();
18716        }
18717        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18718                mPaddingRight : mPaddingLeft;
18719    }
18720
18721    /**
18722     * Returns the right padding of this view. If there are inset and enabled
18723     * scrollbars, this value may include the space required to display the
18724     * scrollbars as well.
18725     *
18726     * @return the right padding in pixels
18727     */
18728    public int getPaddingRight() {
18729        if (!isPaddingResolved()) {
18730            resolvePadding();
18731        }
18732        return mPaddingRight;
18733    }
18734
18735    /**
18736     * Returns the end padding of this view depending on its resolved layout direction.
18737     * If there are inset and enabled scrollbars, this value may include the space
18738     * required to display the scrollbars as well.
18739     *
18740     * @return the end padding in pixels
18741     */
18742    public int getPaddingEnd() {
18743        if (!isPaddingResolved()) {
18744            resolvePadding();
18745        }
18746        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18747                mPaddingLeft : mPaddingRight;
18748    }
18749
18750    /**
18751     * Return if the padding has been set through relative values
18752     * {@link #setPaddingRelative(int, int, int, int)} or through
18753     * @attr ref android.R.styleable#View_paddingStart or
18754     * @attr ref android.R.styleable#View_paddingEnd
18755     *
18756     * @return true if the padding is relative or false if it is not.
18757     */
18758    public boolean isPaddingRelative() {
18759        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18760    }
18761
18762    Insets computeOpticalInsets() {
18763        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18764    }
18765
18766    /**
18767     * @hide
18768     */
18769    public void resetPaddingToInitialValues() {
18770        if (isRtlCompatibilityMode()) {
18771            mPaddingLeft = mUserPaddingLeftInitial;
18772            mPaddingRight = mUserPaddingRightInitial;
18773            return;
18774        }
18775        if (isLayoutRtl()) {
18776            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18777            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18778        } else {
18779            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18780            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18781        }
18782    }
18783
18784    /**
18785     * @hide
18786     */
18787    public Insets getOpticalInsets() {
18788        if (mLayoutInsets == null) {
18789            mLayoutInsets = computeOpticalInsets();
18790        }
18791        return mLayoutInsets;
18792    }
18793
18794    /**
18795     * Set this view's optical insets.
18796     *
18797     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18798     * property. Views that compute their own optical insets should call it as part of measurement.
18799     * This method does not request layout. If you are setting optical insets outside of
18800     * measure/layout itself you will want to call requestLayout() yourself.
18801     * </p>
18802     * @hide
18803     */
18804    public void setOpticalInsets(Insets insets) {
18805        mLayoutInsets = insets;
18806    }
18807
18808    /**
18809     * Changes the selection state of this view. A view can be selected or not.
18810     * Note that selection is not the same as focus. Views are typically
18811     * selected in the context of an AdapterView like ListView or GridView;
18812     * the selected view is the view that is highlighted.
18813     *
18814     * @param selected true if the view must be selected, false otherwise
18815     */
18816    public void setSelected(boolean selected) {
18817        //noinspection DoubleNegation
18818        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
18819            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
18820            if (!selected) resetPressedState();
18821            invalidate(true);
18822            refreshDrawableState();
18823            dispatchSetSelected(selected);
18824            if (selected) {
18825                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
18826            } else {
18827                notifyViewAccessibilityStateChangedIfNeeded(
18828                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
18829            }
18830        }
18831    }
18832
18833    /**
18834     * Dispatch setSelected to all of this View's children.
18835     *
18836     * @see #setSelected(boolean)
18837     *
18838     * @param selected The new selected state
18839     */
18840    protected void dispatchSetSelected(boolean selected) {
18841    }
18842
18843    /**
18844     * Indicates the selection state of this view.
18845     *
18846     * @return true if the view is selected, false otherwise
18847     */
18848    @ViewDebug.ExportedProperty
18849    public boolean isSelected() {
18850        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18851    }
18852
18853    /**
18854     * Changes the activated state of this view. A view can be activated or not.
18855     * Note that activation is not the same as selection.  Selection is
18856     * a transient property, representing the view (hierarchy) the user is
18857     * currently interacting with.  Activation is a longer-term state that the
18858     * user can move views in and out of.  For example, in a list view with
18859     * single or multiple selection enabled, the views in the current selection
18860     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18861     * here.)  The activated state is propagated down to children of the view it
18862     * is set on.
18863     *
18864     * @param activated true if the view must be activated, false otherwise
18865     */
18866    public void setActivated(boolean activated) {
18867        //noinspection DoubleNegation
18868        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18869            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18870            invalidate(true);
18871            refreshDrawableState();
18872            dispatchSetActivated(activated);
18873        }
18874    }
18875
18876    /**
18877     * Dispatch setActivated to all of this View's children.
18878     *
18879     * @see #setActivated(boolean)
18880     *
18881     * @param activated The new activated state
18882     */
18883    protected void dispatchSetActivated(boolean activated) {
18884    }
18885
18886    /**
18887     * Indicates the activation state of this view.
18888     *
18889     * @return true if the view is activated, false otherwise
18890     */
18891    @ViewDebug.ExportedProperty
18892    public boolean isActivated() {
18893        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18894    }
18895
18896    /**
18897     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18898     * observer can be used to get notifications when global events, like
18899     * layout, happen.
18900     *
18901     * The returned ViewTreeObserver observer is not guaranteed to remain
18902     * valid for the lifetime of this View. If the caller of this method keeps
18903     * a long-lived reference to ViewTreeObserver, it should always check for
18904     * the return value of {@link ViewTreeObserver#isAlive()}.
18905     *
18906     * @return The ViewTreeObserver for this view's hierarchy.
18907     */
18908    public ViewTreeObserver getViewTreeObserver() {
18909        if (mAttachInfo != null) {
18910            return mAttachInfo.mTreeObserver;
18911        }
18912        if (mFloatingTreeObserver == null) {
18913            mFloatingTreeObserver = new ViewTreeObserver();
18914        }
18915        return mFloatingTreeObserver;
18916    }
18917
18918    /**
18919     * <p>Finds the topmost view in the current view hierarchy.</p>
18920     *
18921     * @return the topmost view containing this view
18922     */
18923    public View getRootView() {
18924        if (mAttachInfo != null) {
18925            final View v = mAttachInfo.mRootView;
18926            if (v != null) {
18927                return v;
18928            }
18929        }
18930
18931        View parent = this;
18932
18933        while (parent.mParent != null && parent.mParent instanceof View) {
18934            parent = (View) parent.mParent;
18935        }
18936
18937        return parent;
18938    }
18939
18940    /**
18941     * Transforms a motion event from view-local coordinates to on-screen
18942     * coordinates.
18943     *
18944     * @param ev the view-local motion event
18945     * @return false if the transformation could not be applied
18946     * @hide
18947     */
18948    public boolean toGlobalMotionEvent(MotionEvent ev) {
18949        final AttachInfo info = mAttachInfo;
18950        if (info == null) {
18951            return false;
18952        }
18953
18954        final Matrix m = info.mTmpMatrix;
18955        m.set(Matrix.IDENTITY_MATRIX);
18956        transformMatrixToGlobal(m);
18957        ev.transform(m);
18958        return true;
18959    }
18960
18961    /**
18962     * Transforms a motion event from on-screen coordinates to view-local
18963     * coordinates.
18964     *
18965     * @param ev the on-screen motion event
18966     * @return false if the transformation could not be applied
18967     * @hide
18968     */
18969    public boolean toLocalMotionEvent(MotionEvent ev) {
18970        final AttachInfo info = mAttachInfo;
18971        if (info == null) {
18972            return false;
18973        }
18974
18975        final Matrix m = info.mTmpMatrix;
18976        m.set(Matrix.IDENTITY_MATRIX);
18977        transformMatrixToLocal(m);
18978        ev.transform(m);
18979        return true;
18980    }
18981
18982    /**
18983     * Modifies the input matrix such that it maps view-local coordinates to
18984     * on-screen coordinates.
18985     *
18986     * @param m input matrix to modify
18987     * @hide
18988     */
18989    public void transformMatrixToGlobal(Matrix m) {
18990        final ViewParent parent = mParent;
18991        if (parent instanceof View) {
18992            final View vp = (View) parent;
18993            vp.transformMatrixToGlobal(m);
18994            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
18995        } else if (parent instanceof ViewRootImpl) {
18996            final ViewRootImpl vr = (ViewRootImpl) parent;
18997            vr.transformMatrixToGlobal(m);
18998            m.preTranslate(0, -vr.mCurScrollY);
18999        }
19000
19001        m.preTranslate(mLeft, mTop);
19002
19003        if (!hasIdentityMatrix()) {
19004            m.preConcat(getMatrix());
19005        }
19006    }
19007
19008    /**
19009     * Modifies the input matrix such that it maps on-screen coordinates to
19010     * view-local coordinates.
19011     *
19012     * @param m input matrix to modify
19013     * @hide
19014     */
19015    public void transformMatrixToLocal(Matrix m) {
19016        final ViewParent parent = mParent;
19017        if (parent instanceof View) {
19018            final View vp = (View) parent;
19019            vp.transformMatrixToLocal(m);
19020            m.postTranslate(vp.mScrollX, vp.mScrollY);
19021        } else if (parent instanceof ViewRootImpl) {
19022            final ViewRootImpl vr = (ViewRootImpl) parent;
19023            vr.transformMatrixToLocal(m);
19024            m.postTranslate(0, vr.mCurScrollY);
19025        }
19026
19027        m.postTranslate(-mLeft, -mTop);
19028
19029        if (!hasIdentityMatrix()) {
19030            m.postConcat(getInverseMatrix());
19031        }
19032    }
19033
19034    /**
19035     * @hide
19036     */
19037    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19038            @ViewDebug.IntToString(from = 0, to = "x"),
19039            @ViewDebug.IntToString(from = 1, to = "y")
19040    })
19041    public int[] getLocationOnScreen() {
19042        int[] location = new int[2];
19043        getLocationOnScreen(location);
19044        return location;
19045    }
19046
19047    /**
19048     * <p>Computes the coordinates of this view on the screen. The argument
19049     * must be an array of two integers. After the method returns, the array
19050     * contains the x and y location in that order.</p>
19051     *
19052     * @param outLocation an array of two integers in which to hold the coordinates
19053     */
19054    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19055        getLocationInWindow(outLocation);
19056
19057        final AttachInfo info = mAttachInfo;
19058        if (info != null) {
19059            outLocation[0] += info.mWindowLeft;
19060            outLocation[1] += info.mWindowTop;
19061        }
19062    }
19063
19064    /**
19065     * <p>Computes the coordinates of this view in its window. The argument
19066     * must be an array of two integers. After the method returns, the array
19067     * contains the x and y location in that order.</p>
19068     *
19069     * @param outLocation an array of two integers in which to hold the coordinates
19070     */
19071    public void getLocationInWindow(@Size(2) int[] outLocation) {
19072        if (outLocation == null || outLocation.length < 2) {
19073            throw new IllegalArgumentException("outLocation must be an array of two integers");
19074        }
19075
19076        outLocation[0] = 0;
19077        outLocation[1] = 0;
19078
19079        transformFromViewToWindowSpace(outLocation);
19080    }
19081
19082    /** @hide */
19083    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19084        if (inOutLocation == null || inOutLocation.length < 2) {
19085            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19086        }
19087
19088        if (mAttachInfo == null) {
19089            // When the view is not attached to a window, this method does not make sense
19090            inOutLocation[0] = inOutLocation[1] = 0;
19091            return;
19092        }
19093
19094        float position[] = mAttachInfo.mTmpTransformLocation;
19095        position[0] = inOutLocation[0];
19096        position[1] = inOutLocation[1];
19097
19098        if (!hasIdentityMatrix()) {
19099            getMatrix().mapPoints(position);
19100        }
19101
19102        position[0] += mLeft;
19103        position[1] += mTop;
19104
19105        ViewParent viewParent = mParent;
19106        while (viewParent instanceof View) {
19107            final View view = (View) viewParent;
19108
19109            position[0] -= view.mScrollX;
19110            position[1] -= view.mScrollY;
19111
19112            if (!view.hasIdentityMatrix()) {
19113                view.getMatrix().mapPoints(position);
19114            }
19115
19116            position[0] += view.mLeft;
19117            position[1] += view.mTop;
19118
19119            viewParent = view.mParent;
19120         }
19121
19122        if (viewParent instanceof ViewRootImpl) {
19123            // *cough*
19124            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19125            position[1] -= vr.mCurScrollY;
19126        }
19127
19128        inOutLocation[0] = Math.round(position[0]);
19129        inOutLocation[1] = Math.round(position[1]);
19130    }
19131
19132    /**
19133     * {@hide}
19134     * @param id the id of the view to be found
19135     * @return the view of the specified id, null if cannot be found
19136     */
19137    protected View findViewTraversal(@IdRes int id) {
19138        if (id == mID) {
19139            return this;
19140        }
19141        return null;
19142    }
19143
19144    /**
19145     * {@hide}
19146     * @param tag the tag of the view to be found
19147     * @return the view of specified tag, null if cannot be found
19148     */
19149    protected View findViewWithTagTraversal(Object tag) {
19150        if (tag != null && tag.equals(mTag)) {
19151            return this;
19152        }
19153        return null;
19154    }
19155
19156    /**
19157     * {@hide}
19158     * @param predicate The predicate to evaluate.
19159     * @param childToSkip If not null, ignores this child during the recursive traversal.
19160     * @return The first view that matches the predicate or null.
19161     */
19162    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19163        if (predicate.apply(this)) {
19164            return this;
19165        }
19166        return null;
19167    }
19168
19169    /**
19170     * Look for a child view with the given id.  If this view has the given
19171     * id, return this view.
19172     *
19173     * @param id The id to search for.
19174     * @return The view that has the given id in the hierarchy or null
19175     */
19176    @Nullable
19177    public final View findViewById(@IdRes int id) {
19178        if (id < 0) {
19179            return null;
19180        }
19181        return findViewTraversal(id);
19182    }
19183
19184    /**
19185     * Finds a view by its unuque and stable accessibility id.
19186     *
19187     * @param accessibilityId The searched accessibility id.
19188     * @return The found view.
19189     */
19190    final View findViewByAccessibilityId(int accessibilityId) {
19191        if (accessibilityId < 0) {
19192            return null;
19193        }
19194        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19195        if (view != null) {
19196            return view.includeForAccessibility() ? view : null;
19197        }
19198        return null;
19199    }
19200
19201    /**
19202     * Performs the traversal to find a view by its unuque and stable accessibility id.
19203     *
19204     * <strong>Note:</strong>This method does not stop at the root namespace
19205     * boundary since the user can touch the screen at an arbitrary location
19206     * potentially crossing the root namespace bounday which will send an
19207     * accessibility event to accessibility services and they should be able
19208     * to obtain the event source. Also accessibility ids are guaranteed to be
19209     * unique in the window.
19210     *
19211     * @param accessibilityId The accessibility id.
19212     * @return The found view.
19213     *
19214     * @hide
19215     */
19216    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19217        if (getAccessibilityViewId() == accessibilityId) {
19218            return this;
19219        }
19220        return null;
19221    }
19222
19223    /**
19224     * Look for a child view with the given tag.  If this view has the given
19225     * tag, return this view.
19226     *
19227     * @param tag The tag to search for, using "tag.equals(getTag())".
19228     * @return The View that has the given tag in the hierarchy or null
19229     */
19230    public final View findViewWithTag(Object tag) {
19231        if (tag == null) {
19232            return null;
19233        }
19234        return findViewWithTagTraversal(tag);
19235    }
19236
19237    /**
19238     * {@hide}
19239     * Look for a child view that matches the specified predicate.
19240     * If this view matches the predicate, return this view.
19241     *
19242     * @param predicate The predicate to evaluate.
19243     * @return The first view that matches the predicate or null.
19244     */
19245    public final View findViewByPredicate(Predicate<View> predicate) {
19246        return findViewByPredicateTraversal(predicate, null);
19247    }
19248
19249    /**
19250     * {@hide}
19251     * Look for a child view that matches the specified predicate,
19252     * starting with the specified view and its descendents and then
19253     * recusively searching the ancestors and siblings of that view
19254     * until this view is reached.
19255     *
19256     * This method is useful in cases where the predicate does not match
19257     * a single unique view (perhaps multiple views use the same id)
19258     * and we are trying to find the view that is "closest" in scope to the
19259     * starting view.
19260     *
19261     * @param start The view to start from.
19262     * @param predicate The predicate to evaluate.
19263     * @return The first view that matches the predicate or null.
19264     */
19265    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19266        View childToSkip = null;
19267        for (;;) {
19268            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19269            if (view != null || start == this) {
19270                return view;
19271            }
19272
19273            ViewParent parent = start.getParent();
19274            if (parent == null || !(parent instanceof View)) {
19275                return null;
19276            }
19277
19278            childToSkip = start;
19279            start = (View) parent;
19280        }
19281    }
19282
19283    /**
19284     * Sets the identifier for this view. The identifier does not have to be
19285     * unique in this view's hierarchy. The identifier should be a positive
19286     * number.
19287     *
19288     * @see #NO_ID
19289     * @see #getId()
19290     * @see #findViewById(int)
19291     *
19292     * @param id a number used to identify the view
19293     *
19294     * @attr ref android.R.styleable#View_id
19295     */
19296    public void setId(@IdRes int id) {
19297        mID = id;
19298        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19299            mID = generateViewId();
19300        }
19301    }
19302
19303    /**
19304     * {@hide}
19305     *
19306     * @param isRoot true if the view belongs to the root namespace, false
19307     *        otherwise
19308     */
19309    public void setIsRootNamespace(boolean isRoot) {
19310        if (isRoot) {
19311            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19312        } else {
19313            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19314        }
19315    }
19316
19317    /**
19318     * {@hide}
19319     *
19320     * @return true if the view belongs to the root namespace, false otherwise
19321     */
19322    public boolean isRootNamespace() {
19323        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19324    }
19325
19326    /**
19327     * Returns this view's identifier.
19328     *
19329     * @return a positive integer used to identify the view or {@link #NO_ID}
19330     *         if the view has no ID
19331     *
19332     * @see #setId(int)
19333     * @see #findViewById(int)
19334     * @attr ref android.R.styleable#View_id
19335     */
19336    @IdRes
19337    @ViewDebug.CapturedViewProperty
19338    public int getId() {
19339        return mID;
19340    }
19341
19342    /**
19343     * Returns this view's tag.
19344     *
19345     * @return the Object stored in this view as a tag, or {@code null} if not
19346     *         set
19347     *
19348     * @see #setTag(Object)
19349     * @see #getTag(int)
19350     */
19351    @ViewDebug.ExportedProperty
19352    public Object getTag() {
19353        return mTag;
19354    }
19355
19356    /**
19357     * Sets the tag associated with this view. A tag can be used to mark
19358     * a view in its hierarchy and does not have to be unique within the
19359     * hierarchy. Tags can also be used to store data within a view without
19360     * resorting to another data structure.
19361     *
19362     * @param tag an Object to tag the view with
19363     *
19364     * @see #getTag()
19365     * @see #setTag(int, Object)
19366     */
19367    public void setTag(final Object tag) {
19368        mTag = tag;
19369    }
19370
19371    /**
19372     * Returns the tag associated with this view and the specified key.
19373     *
19374     * @param key The key identifying the tag
19375     *
19376     * @return the Object stored in this view as a tag, or {@code null} if not
19377     *         set
19378     *
19379     * @see #setTag(int, Object)
19380     * @see #getTag()
19381     */
19382    public Object getTag(int key) {
19383        if (mKeyedTags != null) return mKeyedTags.get(key);
19384        return null;
19385    }
19386
19387    /**
19388     * Sets a tag associated with this view and a key. A tag can be used
19389     * to mark a view in its hierarchy and does not have to be unique within
19390     * the hierarchy. Tags can also be used to store data within a view
19391     * without resorting to another data structure.
19392     *
19393     * The specified key should be an id declared in the resources of the
19394     * application to ensure it is unique (see the <a
19395     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19396     * Keys identified as belonging to
19397     * the Android framework or not associated with any package will cause
19398     * an {@link IllegalArgumentException} to be thrown.
19399     *
19400     * @param key The key identifying the tag
19401     * @param tag An Object to tag the view with
19402     *
19403     * @throws IllegalArgumentException If they specified key is not valid
19404     *
19405     * @see #setTag(Object)
19406     * @see #getTag(int)
19407     */
19408    public void setTag(int key, final Object tag) {
19409        // If the package id is 0x00 or 0x01, it's either an undefined package
19410        // or a framework id
19411        if ((key >>> 24) < 2) {
19412            throw new IllegalArgumentException("The key must be an application-specific "
19413                    + "resource id.");
19414        }
19415
19416        setKeyedTag(key, tag);
19417    }
19418
19419    /**
19420     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19421     * framework id.
19422     *
19423     * @hide
19424     */
19425    public void setTagInternal(int key, Object tag) {
19426        if ((key >>> 24) != 0x1) {
19427            throw new IllegalArgumentException("The key must be a framework-specific "
19428                    + "resource id.");
19429        }
19430
19431        setKeyedTag(key, tag);
19432    }
19433
19434    private void setKeyedTag(int key, Object tag) {
19435        if (mKeyedTags == null) {
19436            mKeyedTags = new SparseArray<Object>(2);
19437        }
19438
19439        mKeyedTags.put(key, tag);
19440    }
19441
19442    /**
19443     * Prints information about this view in the log output, with the tag
19444     * {@link #VIEW_LOG_TAG}.
19445     *
19446     * @hide
19447     */
19448    public void debug() {
19449        debug(0);
19450    }
19451
19452    /**
19453     * Prints information about this view in the log output, with the tag
19454     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19455     * indentation defined by the <code>depth</code>.
19456     *
19457     * @param depth the indentation level
19458     *
19459     * @hide
19460     */
19461    protected void debug(int depth) {
19462        String output = debugIndent(depth - 1);
19463
19464        output += "+ " + this;
19465        int id = getId();
19466        if (id != -1) {
19467            output += " (id=" + id + ")";
19468        }
19469        Object tag = getTag();
19470        if (tag != null) {
19471            output += " (tag=" + tag + ")";
19472        }
19473        Log.d(VIEW_LOG_TAG, output);
19474
19475        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19476            output = debugIndent(depth) + " FOCUSED";
19477            Log.d(VIEW_LOG_TAG, output);
19478        }
19479
19480        output = debugIndent(depth);
19481        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19482                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19483                + "} ";
19484        Log.d(VIEW_LOG_TAG, output);
19485
19486        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19487                || mPaddingBottom != 0) {
19488            output = debugIndent(depth);
19489            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19490                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19491            Log.d(VIEW_LOG_TAG, output);
19492        }
19493
19494        output = debugIndent(depth);
19495        output += "mMeasureWidth=" + mMeasuredWidth +
19496                " mMeasureHeight=" + mMeasuredHeight;
19497        Log.d(VIEW_LOG_TAG, output);
19498
19499        output = debugIndent(depth);
19500        if (mLayoutParams == null) {
19501            output += "BAD! no layout params";
19502        } else {
19503            output = mLayoutParams.debug(output);
19504        }
19505        Log.d(VIEW_LOG_TAG, output);
19506
19507        output = debugIndent(depth);
19508        output += "flags={";
19509        output += View.printFlags(mViewFlags);
19510        output += "}";
19511        Log.d(VIEW_LOG_TAG, output);
19512
19513        output = debugIndent(depth);
19514        output += "privateFlags={";
19515        output += View.printPrivateFlags(mPrivateFlags);
19516        output += "}";
19517        Log.d(VIEW_LOG_TAG, output);
19518    }
19519
19520    /**
19521     * Creates a string of whitespaces used for indentation.
19522     *
19523     * @param depth the indentation level
19524     * @return a String containing (depth * 2 + 3) * 2 white spaces
19525     *
19526     * @hide
19527     */
19528    protected static String debugIndent(int depth) {
19529        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19530        for (int i = 0; i < (depth * 2) + 3; i++) {
19531            spaces.append(' ').append(' ');
19532        }
19533        return spaces.toString();
19534    }
19535
19536    /**
19537     * <p>Return the offset of the widget's text baseline from the widget's top
19538     * boundary. If this widget does not support baseline alignment, this
19539     * method returns -1. </p>
19540     *
19541     * @return the offset of the baseline within the widget's bounds or -1
19542     *         if baseline alignment is not supported
19543     */
19544    @ViewDebug.ExportedProperty(category = "layout")
19545    public int getBaseline() {
19546        return -1;
19547    }
19548
19549    /**
19550     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19551     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19552     * a layout pass.
19553     *
19554     * @return whether the view hierarchy is currently undergoing a layout pass
19555     */
19556    public boolean isInLayout() {
19557        ViewRootImpl viewRoot = getViewRootImpl();
19558        return (viewRoot != null && viewRoot.isInLayout());
19559    }
19560
19561    /**
19562     * Call this when something has changed which has invalidated the
19563     * layout of this view. This will schedule a layout pass of the view
19564     * tree. This should not be called while the view hierarchy is currently in a layout
19565     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19566     * end of the current layout pass (and then layout will run again) or after the current
19567     * frame is drawn and the next layout occurs.
19568     *
19569     * <p>Subclasses which override this method should call the superclass method to
19570     * handle possible request-during-layout errors correctly.</p>
19571     */
19572    @CallSuper
19573    public void requestLayout() {
19574        if (mMeasureCache != null) mMeasureCache.clear();
19575
19576        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19577            // Only trigger request-during-layout logic if this is the view requesting it,
19578            // not the views in its parent hierarchy
19579            ViewRootImpl viewRoot = getViewRootImpl();
19580            if (viewRoot != null && viewRoot.isInLayout()) {
19581                if (!viewRoot.requestLayoutDuringLayout(this)) {
19582                    return;
19583                }
19584            }
19585            mAttachInfo.mViewRequestingLayout = this;
19586        }
19587
19588        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19589        mPrivateFlags |= PFLAG_INVALIDATED;
19590
19591        if (mParent != null && !mParent.isLayoutRequested()) {
19592            mParent.requestLayout();
19593        }
19594        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19595            mAttachInfo.mViewRequestingLayout = null;
19596        }
19597    }
19598
19599    /**
19600     * Forces this view to be laid out during the next layout pass.
19601     * This method does not call requestLayout() or forceLayout()
19602     * on the parent.
19603     */
19604    public void forceLayout() {
19605        if (mMeasureCache != null) mMeasureCache.clear();
19606
19607        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19608        mPrivateFlags |= PFLAG_INVALIDATED;
19609    }
19610
19611    /**
19612     * <p>
19613     * This is called to find out how big a view should be. The parent
19614     * supplies constraint information in the width and height parameters.
19615     * </p>
19616     *
19617     * <p>
19618     * The actual measurement work of a view is performed in
19619     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19620     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19621     * </p>
19622     *
19623     *
19624     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19625     *        parent
19626     * @param heightMeasureSpec Vertical space requirements as imposed by the
19627     *        parent
19628     *
19629     * @see #onMeasure(int, int)
19630     */
19631    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19632        boolean optical = isLayoutModeOptical(this);
19633        if (optical != isLayoutModeOptical(mParent)) {
19634            Insets insets = getOpticalInsets();
19635            int oWidth  = insets.left + insets.right;
19636            int oHeight = insets.top  + insets.bottom;
19637            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19638            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19639        }
19640
19641        // Suppress sign extension for the low bytes
19642        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19643        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19644
19645        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19646
19647        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19648        // already measured as the correct size. In API 23 and below, this
19649        // extra pass is required to make LinearLayout re-distribute weight.
19650        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19651                || heightMeasureSpec != mOldHeightMeasureSpec;
19652        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19653                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19654        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19655                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19656        final boolean needsLayout = specChanged
19657                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19658
19659        if (forceLayout || needsLayout) {
19660            // first clears the measured dimension flag
19661            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19662
19663            resolveRtlPropertiesIfNeeded();
19664
19665            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19666            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19667                // measure ourselves, this should set the measured dimension flag back
19668                onMeasure(widthMeasureSpec, heightMeasureSpec);
19669                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19670            } else {
19671                long value = mMeasureCache.valueAt(cacheIndex);
19672                // Casting a long to int drops the high 32 bits, no mask needed
19673                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19674                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19675            }
19676
19677            // flag not set, setMeasuredDimension() was not invoked, we raise
19678            // an exception to warn the developer
19679            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19680                throw new IllegalStateException("View with id " + getId() + ": "
19681                        + getClass().getName() + "#onMeasure() did not set the"
19682                        + " measured dimension by calling"
19683                        + " setMeasuredDimension()");
19684            }
19685
19686            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19687        }
19688
19689        mOldWidthMeasureSpec = widthMeasureSpec;
19690        mOldHeightMeasureSpec = heightMeasureSpec;
19691
19692        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19693                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19694    }
19695
19696    /**
19697     * <p>
19698     * Measure the view and its content to determine the measured width and the
19699     * measured height. This method is invoked by {@link #measure(int, int)} and
19700     * should be overridden by subclasses to provide accurate and efficient
19701     * measurement of their contents.
19702     * </p>
19703     *
19704     * <p>
19705     * <strong>CONTRACT:</strong> When overriding this method, you
19706     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19707     * measured width and height of this view. Failure to do so will trigger an
19708     * <code>IllegalStateException</code>, thrown by
19709     * {@link #measure(int, int)}. Calling the superclass'
19710     * {@link #onMeasure(int, int)} is a valid use.
19711     * </p>
19712     *
19713     * <p>
19714     * The base class implementation of measure defaults to the background size,
19715     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19716     * override {@link #onMeasure(int, int)} to provide better measurements of
19717     * their content.
19718     * </p>
19719     *
19720     * <p>
19721     * If this method is overridden, it is the subclass's responsibility to make
19722     * sure the measured height and width are at least the view's minimum height
19723     * and width ({@link #getSuggestedMinimumHeight()} and
19724     * {@link #getSuggestedMinimumWidth()}).
19725     * </p>
19726     *
19727     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19728     *                         The requirements are encoded with
19729     *                         {@link android.view.View.MeasureSpec}.
19730     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19731     *                         The requirements are encoded with
19732     *                         {@link android.view.View.MeasureSpec}.
19733     *
19734     * @see #getMeasuredWidth()
19735     * @see #getMeasuredHeight()
19736     * @see #setMeasuredDimension(int, int)
19737     * @see #getSuggestedMinimumHeight()
19738     * @see #getSuggestedMinimumWidth()
19739     * @see android.view.View.MeasureSpec#getMode(int)
19740     * @see android.view.View.MeasureSpec#getSize(int)
19741     */
19742    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19743        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19744                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19745    }
19746
19747    /**
19748     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19749     * measured width and measured height. Failing to do so will trigger an
19750     * exception at measurement time.</p>
19751     *
19752     * @param measuredWidth The measured width of this view.  May be a complex
19753     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19754     * {@link #MEASURED_STATE_TOO_SMALL}.
19755     * @param measuredHeight The measured height of this view.  May be a complex
19756     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19757     * {@link #MEASURED_STATE_TOO_SMALL}.
19758     */
19759    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19760        boolean optical = isLayoutModeOptical(this);
19761        if (optical != isLayoutModeOptical(mParent)) {
19762            Insets insets = getOpticalInsets();
19763            int opticalWidth  = insets.left + insets.right;
19764            int opticalHeight = insets.top  + insets.bottom;
19765
19766            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19767            measuredHeight += optical ? opticalHeight : -opticalHeight;
19768        }
19769        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19770    }
19771
19772    /**
19773     * Sets the measured dimension without extra processing for things like optical bounds.
19774     * Useful for reapplying consistent values that have already been cooked with adjustments
19775     * for optical bounds, etc. such as those from the measurement cache.
19776     *
19777     * @param measuredWidth The measured width of this view.  May be a complex
19778     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19779     * {@link #MEASURED_STATE_TOO_SMALL}.
19780     * @param measuredHeight The measured height of this view.  May be a complex
19781     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19782     * {@link #MEASURED_STATE_TOO_SMALL}.
19783     */
19784    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19785        mMeasuredWidth = measuredWidth;
19786        mMeasuredHeight = measuredHeight;
19787
19788        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19789    }
19790
19791    /**
19792     * Merge two states as returned by {@link #getMeasuredState()}.
19793     * @param curState The current state as returned from a view or the result
19794     * of combining multiple views.
19795     * @param newState The new view state to combine.
19796     * @return Returns a new integer reflecting the combination of the two
19797     * states.
19798     */
19799    public static int combineMeasuredStates(int curState, int newState) {
19800        return curState | newState;
19801    }
19802
19803    /**
19804     * Version of {@link #resolveSizeAndState(int, int, int)}
19805     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19806     */
19807    public static int resolveSize(int size, int measureSpec) {
19808        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19809    }
19810
19811    /**
19812     * Utility to reconcile a desired size and state, with constraints imposed
19813     * by a MeasureSpec. Will take the desired size, unless a different size
19814     * is imposed by the constraints. The returned value is a compound integer,
19815     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
19816     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
19817     * resulting size is smaller than the size the view wants to be.
19818     *
19819     * @param size How big the view wants to be.
19820     * @param measureSpec Constraints imposed by the parent.
19821     * @param childMeasuredState Size information bit mask for the view's
19822     *                           children.
19823     * @return Size information bit mask as defined by
19824     *         {@link #MEASURED_SIZE_MASK} and
19825     *         {@link #MEASURED_STATE_TOO_SMALL}.
19826     */
19827    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
19828        final int specMode = MeasureSpec.getMode(measureSpec);
19829        final int specSize = MeasureSpec.getSize(measureSpec);
19830        final int result;
19831        switch (specMode) {
19832            case MeasureSpec.AT_MOST:
19833                if (specSize < size) {
19834                    result = specSize | MEASURED_STATE_TOO_SMALL;
19835                } else {
19836                    result = size;
19837                }
19838                break;
19839            case MeasureSpec.EXACTLY:
19840                result = specSize;
19841                break;
19842            case MeasureSpec.UNSPECIFIED:
19843            default:
19844                result = size;
19845        }
19846        return result | (childMeasuredState & MEASURED_STATE_MASK);
19847    }
19848
19849    /**
19850     * Utility to return a default size. Uses the supplied size if the
19851     * MeasureSpec imposed no constraints. Will get larger if allowed
19852     * by the MeasureSpec.
19853     *
19854     * @param size Default size for this view
19855     * @param measureSpec Constraints imposed by the parent
19856     * @return The size this view should be.
19857     */
19858    public static int getDefaultSize(int size, int measureSpec) {
19859        int result = size;
19860        int specMode = MeasureSpec.getMode(measureSpec);
19861        int specSize = MeasureSpec.getSize(measureSpec);
19862
19863        switch (specMode) {
19864        case MeasureSpec.UNSPECIFIED:
19865            result = size;
19866            break;
19867        case MeasureSpec.AT_MOST:
19868        case MeasureSpec.EXACTLY:
19869            result = specSize;
19870            break;
19871        }
19872        return result;
19873    }
19874
19875    /**
19876     * Returns the suggested minimum height that the view should use. This
19877     * returns the maximum of the view's minimum height
19878     * and the background's minimum height
19879     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19880     * <p>
19881     * When being used in {@link #onMeasure(int, int)}, the caller should still
19882     * ensure the returned height is within the requirements of the parent.
19883     *
19884     * @return The suggested minimum height of the view.
19885     */
19886    protected int getSuggestedMinimumHeight() {
19887        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19888
19889    }
19890
19891    /**
19892     * Returns the suggested minimum width that the view should use. This
19893     * returns the maximum of the view's minimum width
19894     * and the background's minimum width
19895     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19896     * <p>
19897     * When being used in {@link #onMeasure(int, int)}, the caller should still
19898     * ensure the returned width is within the requirements of the parent.
19899     *
19900     * @return The suggested minimum width of the view.
19901     */
19902    protected int getSuggestedMinimumWidth() {
19903        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19904    }
19905
19906    /**
19907     * Returns the minimum height of the view.
19908     *
19909     * @return the minimum height the view will try to be.
19910     *
19911     * @see #setMinimumHeight(int)
19912     *
19913     * @attr ref android.R.styleable#View_minHeight
19914     */
19915    public int getMinimumHeight() {
19916        return mMinHeight;
19917    }
19918
19919    /**
19920     * Sets the minimum height of the view. It is not guaranteed the view will
19921     * be able to achieve this minimum height (for example, if its parent layout
19922     * constrains it with less available height).
19923     *
19924     * @param minHeight The minimum height the view will try to be.
19925     *
19926     * @see #getMinimumHeight()
19927     *
19928     * @attr ref android.R.styleable#View_minHeight
19929     */
19930    @RemotableViewMethod
19931    public void setMinimumHeight(int minHeight) {
19932        mMinHeight = minHeight;
19933        requestLayout();
19934    }
19935
19936    /**
19937     * Returns the minimum width of the view.
19938     *
19939     * @return the minimum width the view will try to be.
19940     *
19941     * @see #setMinimumWidth(int)
19942     *
19943     * @attr ref android.R.styleable#View_minWidth
19944     */
19945    public int getMinimumWidth() {
19946        return mMinWidth;
19947    }
19948
19949    /**
19950     * Sets the minimum width of the view. It is not guaranteed the view will
19951     * be able to achieve this minimum width (for example, if its parent layout
19952     * constrains it with less available width).
19953     *
19954     * @param minWidth The minimum width the view will try to be.
19955     *
19956     * @see #getMinimumWidth()
19957     *
19958     * @attr ref android.R.styleable#View_minWidth
19959     */
19960    public void setMinimumWidth(int minWidth) {
19961        mMinWidth = minWidth;
19962        requestLayout();
19963
19964    }
19965
19966    /**
19967     * Get the animation currently associated with this view.
19968     *
19969     * @return The animation that is currently playing or
19970     *         scheduled to play for this view.
19971     */
19972    public Animation getAnimation() {
19973        return mCurrentAnimation;
19974    }
19975
19976    /**
19977     * Start the specified animation now.
19978     *
19979     * @param animation the animation to start now
19980     */
19981    public void startAnimation(Animation animation) {
19982        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
19983        setAnimation(animation);
19984        invalidateParentCaches();
19985        invalidate(true);
19986    }
19987
19988    /**
19989     * Cancels any animations for this view.
19990     */
19991    public void clearAnimation() {
19992        if (mCurrentAnimation != null) {
19993            mCurrentAnimation.detach();
19994        }
19995        mCurrentAnimation = null;
19996        invalidateParentIfNeeded();
19997    }
19998
19999    /**
20000     * Sets the next animation to play for this view.
20001     * If you want the animation to play immediately, use
20002     * {@link #startAnimation(android.view.animation.Animation)} instead.
20003     * This method provides allows fine-grained
20004     * control over the start time and invalidation, but you
20005     * must make sure that 1) the animation has a start time set, and
20006     * 2) the view's parent (which controls animations on its children)
20007     * will be invalidated when the animation is supposed to
20008     * start.
20009     *
20010     * @param animation The next animation, or null.
20011     */
20012    public void setAnimation(Animation animation) {
20013        mCurrentAnimation = animation;
20014
20015        if (animation != null) {
20016            // If the screen is off assume the animation start time is now instead of
20017            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20018            // would cause the animation to start when the screen turns back on
20019            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20020                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20021                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20022            }
20023            animation.reset();
20024        }
20025    }
20026
20027    /**
20028     * Invoked by a parent ViewGroup to notify the start of the animation
20029     * currently associated with this view. If you override this method,
20030     * always call super.onAnimationStart();
20031     *
20032     * @see #setAnimation(android.view.animation.Animation)
20033     * @see #getAnimation()
20034     */
20035    @CallSuper
20036    protected void onAnimationStart() {
20037        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20038    }
20039
20040    /**
20041     * Invoked by a parent ViewGroup to notify the end of the animation
20042     * currently associated with this view. If you override this method,
20043     * always call super.onAnimationEnd();
20044     *
20045     * @see #setAnimation(android.view.animation.Animation)
20046     * @see #getAnimation()
20047     */
20048    @CallSuper
20049    protected void onAnimationEnd() {
20050        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20051    }
20052
20053    /**
20054     * Invoked if there is a Transform that involves alpha. Subclass that can
20055     * draw themselves with the specified alpha should return true, and then
20056     * respect that alpha when their onDraw() is called. If this returns false
20057     * then the view may be redirected to draw into an offscreen buffer to
20058     * fulfill the request, which will look fine, but may be slower than if the
20059     * subclass handles it internally. The default implementation returns false.
20060     *
20061     * @param alpha The alpha (0..255) to apply to the view's drawing
20062     * @return true if the view can draw with the specified alpha.
20063     */
20064    protected boolean onSetAlpha(int alpha) {
20065        return false;
20066    }
20067
20068    /**
20069     * This is used by the RootView to perform an optimization when
20070     * the view hierarchy contains one or several SurfaceView.
20071     * SurfaceView is always considered transparent, but its children are not,
20072     * therefore all View objects remove themselves from the global transparent
20073     * region (passed as a parameter to this function).
20074     *
20075     * @param region The transparent region for this ViewAncestor (window).
20076     *
20077     * @return Returns true if the effective visibility of the view at this
20078     * point is opaque, regardless of the transparent region; returns false
20079     * if it is possible for underlying windows to be seen behind the view.
20080     *
20081     * {@hide}
20082     */
20083    public boolean gatherTransparentRegion(Region region) {
20084        final AttachInfo attachInfo = mAttachInfo;
20085        if (region != null && attachInfo != null) {
20086            final int pflags = mPrivateFlags;
20087            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20088                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20089                // remove it from the transparent region.
20090                final int[] location = attachInfo.mTransparentLocation;
20091                getLocationInWindow(location);
20092                region.op(location[0], location[1], location[0] + mRight - mLeft,
20093                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20094            } else {
20095                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20096                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20097                    // the background drawable's non-transparent parts from this transparent region.
20098                    applyDrawableToTransparentRegion(mBackground, region);
20099                }
20100                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20101                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20102                    // Similarly, we remove the foreground drawable's non-transparent parts.
20103                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20104                }
20105            }
20106        }
20107        return true;
20108    }
20109
20110    /**
20111     * Play a sound effect for this view.
20112     *
20113     * <p>The framework will play sound effects for some built in actions, such as
20114     * clicking, but you may wish to play these effects in your widget,
20115     * for instance, for internal navigation.
20116     *
20117     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20118     * {@link #isSoundEffectsEnabled()} is true.
20119     *
20120     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20121     */
20122    public void playSoundEffect(int soundConstant) {
20123        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20124            return;
20125        }
20126        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20127    }
20128
20129    /**
20130     * BZZZTT!!1!
20131     *
20132     * <p>Provide haptic feedback to the user for this view.
20133     *
20134     * <p>The framework will provide haptic feedback for some built in actions,
20135     * such as long presses, but you may wish to provide feedback for your
20136     * own widget.
20137     *
20138     * <p>The feedback will only be performed if
20139     * {@link #isHapticFeedbackEnabled()} is true.
20140     *
20141     * @param feedbackConstant One of the constants defined in
20142     * {@link HapticFeedbackConstants}
20143     */
20144    public boolean performHapticFeedback(int feedbackConstant) {
20145        return performHapticFeedback(feedbackConstant, 0);
20146    }
20147
20148    /**
20149     * BZZZTT!!1!
20150     *
20151     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20152     *
20153     * @param feedbackConstant One of the constants defined in
20154     * {@link HapticFeedbackConstants}
20155     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20156     */
20157    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20158        if (mAttachInfo == null) {
20159            return false;
20160        }
20161        //noinspection SimplifiableIfStatement
20162        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20163                && !isHapticFeedbackEnabled()) {
20164            return false;
20165        }
20166        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20167                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20168    }
20169
20170    /**
20171     * Request that the visibility of the status bar or other screen/window
20172     * decorations be changed.
20173     *
20174     * <p>This method is used to put the over device UI into temporary modes
20175     * where the user's attention is focused more on the application content,
20176     * by dimming or hiding surrounding system affordances.  This is typically
20177     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20178     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20179     * to be placed behind the action bar (and with these flags other system
20180     * affordances) so that smooth transitions between hiding and showing them
20181     * can be done.
20182     *
20183     * <p>Two representative examples of the use of system UI visibility is
20184     * implementing a content browsing application (like a magazine reader)
20185     * and a video playing application.
20186     *
20187     * <p>The first code shows a typical implementation of a View in a content
20188     * browsing application.  In this implementation, the application goes
20189     * into a content-oriented mode by hiding the status bar and action bar,
20190     * and putting the navigation elements into lights out mode.  The user can
20191     * then interact with content while in this mode.  Such an application should
20192     * provide an easy way for the user to toggle out of the mode (such as to
20193     * check information in the status bar or access notifications).  In the
20194     * implementation here, this is done simply by tapping on the content.
20195     *
20196     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20197     *      content}
20198     *
20199     * <p>This second code sample shows a typical implementation of a View
20200     * in a video playing application.  In this situation, while the video is
20201     * playing the application would like to go into a complete full-screen mode,
20202     * to use as much of the display as possible for the video.  When in this state
20203     * the user can not interact with the application; the system intercepts
20204     * touching on the screen to pop the UI out of full screen mode.  See
20205     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20206     *
20207     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20208     *      content}
20209     *
20210     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20211     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20212     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20213     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20214     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20215     */
20216    public void setSystemUiVisibility(int visibility) {
20217        if (visibility != mSystemUiVisibility) {
20218            mSystemUiVisibility = visibility;
20219            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20220                mParent.recomputeViewAttributes(this);
20221            }
20222        }
20223    }
20224
20225    /**
20226     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20227     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20228     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20229     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20230     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20231     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20232     */
20233    public int getSystemUiVisibility() {
20234        return mSystemUiVisibility;
20235    }
20236
20237    /**
20238     * Returns the current system UI visibility that is currently set for
20239     * the entire window.  This is the combination of the
20240     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20241     * views in the window.
20242     */
20243    public int getWindowSystemUiVisibility() {
20244        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20245    }
20246
20247    /**
20248     * Override to find out when the window's requested system UI visibility
20249     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20250     * This is different from the callbacks received through
20251     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20252     * in that this is only telling you about the local request of the window,
20253     * not the actual values applied by the system.
20254     */
20255    public void onWindowSystemUiVisibilityChanged(int visible) {
20256    }
20257
20258    /**
20259     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20260     * the view hierarchy.
20261     */
20262    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20263        onWindowSystemUiVisibilityChanged(visible);
20264    }
20265
20266    /**
20267     * Set a listener to receive callbacks when the visibility of the system bar changes.
20268     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20269     */
20270    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20271        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20272        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20273            mParent.recomputeViewAttributes(this);
20274        }
20275    }
20276
20277    /**
20278     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20279     * the view hierarchy.
20280     */
20281    public void dispatchSystemUiVisibilityChanged(int visibility) {
20282        ListenerInfo li = mListenerInfo;
20283        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20284            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20285                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20286        }
20287    }
20288
20289    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20290        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20291        if (val != mSystemUiVisibility) {
20292            setSystemUiVisibility(val);
20293            return true;
20294        }
20295        return false;
20296    }
20297
20298    /** @hide */
20299    public void setDisabledSystemUiVisibility(int flags) {
20300        if (mAttachInfo != null) {
20301            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20302                mAttachInfo.mDisabledSystemUiVisibility = flags;
20303                if (mParent != null) {
20304                    mParent.recomputeViewAttributes(this);
20305                }
20306            }
20307        }
20308    }
20309
20310    /**
20311     * Creates an image that the system displays during the drag and drop
20312     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20313     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20314     * appearance as the given View. The default also positions the center of the drag shadow
20315     * directly under the touch point. If no View is provided (the constructor with no parameters
20316     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20317     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20318     * default is an invisible drag shadow.
20319     * <p>
20320     * You are not required to use the View you provide to the constructor as the basis of the
20321     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20322     * anything you want as the drag shadow.
20323     * </p>
20324     * <p>
20325     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20326     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20327     *  size and position of the drag shadow. It uses this data to construct a
20328     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20329     *  so that your application can draw the shadow image in the Canvas.
20330     * </p>
20331     *
20332     * <div class="special reference">
20333     * <h3>Developer Guides</h3>
20334     * <p>For a guide to implementing drag and drop features, read the
20335     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20336     * </div>
20337     */
20338    public static class DragShadowBuilder {
20339        private final WeakReference<View> mView;
20340
20341        /**
20342         * Constructs a shadow image builder based on a View. By default, the resulting drag
20343         * shadow will have the same appearance and dimensions as the View, with the touch point
20344         * over the center of the View.
20345         * @param view A View. Any View in scope can be used.
20346         */
20347        public DragShadowBuilder(View view) {
20348            mView = new WeakReference<View>(view);
20349        }
20350
20351        /**
20352         * Construct a shadow builder object with no associated View.  This
20353         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20354         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20355         * to supply the drag shadow's dimensions and appearance without
20356         * reference to any View object. If they are not overridden, then the result is an
20357         * invisible drag shadow.
20358         */
20359        public DragShadowBuilder() {
20360            mView = new WeakReference<View>(null);
20361        }
20362
20363        /**
20364         * Returns the View object that had been passed to the
20365         * {@link #View.DragShadowBuilder(View)}
20366         * constructor.  If that View parameter was {@code null} or if the
20367         * {@link #View.DragShadowBuilder()}
20368         * constructor was used to instantiate the builder object, this method will return
20369         * null.
20370         *
20371         * @return The View object associate with this builder object.
20372         */
20373        @SuppressWarnings({"JavadocReference"})
20374        final public View getView() {
20375            return mView.get();
20376        }
20377
20378        /**
20379         * Provides the metrics for the shadow image. These include the dimensions of
20380         * the shadow image, and the point within that shadow that should
20381         * be centered under the touch location while dragging.
20382         * <p>
20383         * The default implementation sets the dimensions of the shadow to be the
20384         * same as the dimensions of the View itself and centers the shadow under
20385         * the touch point.
20386         * </p>
20387         *
20388         * @param shadowSize A {@link android.graphics.Point} containing the width and height
20389         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20390         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20391         * image.
20392         *
20393         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
20394         * shadow image that should be underneath the touch point during the drag and drop
20395         * operation. Your application must set {@link android.graphics.Point#x} to the
20396         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20397         */
20398        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
20399            final View view = mView.get();
20400            if (view != null) {
20401                shadowSize.set(view.getWidth(), view.getHeight());
20402                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
20403            } else {
20404                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20405            }
20406        }
20407
20408        /**
20409         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20410         * based on the dimensions it received from the
20411         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20412         *
20413         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20414         */
20415        public void onDrawShadow(Canvas canvas) {
20416            final View view = mView.get();
20417            if (view != null) {
20418                view.draw(canvas);
20419            } else {
20420                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20421            }
20422        }
20423    }
20424
20425    /**
20426     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20427     * startDragAndDrop()} for newer platform versions.
20428     */
20429    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20430                                   Object myLocalState, int flags) {
20431        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20432    }
20433
20434    /**
20435     * Starts a drag and drop operation. When your application calls this method, it passes a
20436     * {@link android.view.View.DragShadowBuilder} object to the system. The
20437     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20438     * to get metrics for the drag shadow, and then calls the object's
20439     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20440     * <p>
20441     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20442     *  drag events to all the View objects in your application that are currently visible. It does
20443     *  this either by calling the View object's drag listener (an implementation of
20444     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20445     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20446     *  Both are passed a {@link android.view.DragEvent} object that has a
20447     *  {@link android.view.DragEvent#getAction()} value of
20448     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20449     * </p>
20450     * <p>
20451     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20452     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20453     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20454     * to the View the user selected for dragging.
20455     * </p>
20456     * @param data A {@link android.content.ClipData} object pointing to the data to be
20457     * transferred by the drag and drop operation.
20458     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20459     * drag shadow.
20460     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20461     * drop operation. This Object is put into every DragEvent object sent by the system during the
20462     * current drag.
20463     * <p>
20464     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20465     * to the target Views. For example, it can contain flags that differentiate between a
20466     * a copy operation and a move operation.
20467     * </p>
20468     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
20469     * so the parameter should be set to 0.
20470     * @return {@code true} if the method completes successfully, or
20471     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20472     * do a drag, and so no drag operation is in progress.
20473     */
20474    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20475            Object myLocalState, int flags) {
20476        if (ViewDebug.DEBUG_DRAG) {
20477            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20478        }
20479        boolean okay = false;
20480
20481        Point shadowSize = new Point();
20482        Point shadowTouchPoint = new Point();
20483        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20484
20485        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20486                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20487            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20488        }
20489
20490        if (ViewDebug.DEBUG_DRAG) {
20491            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20492                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20493        }
20494        if (mAttachInfo.mDragSurface != null) {
20495            mAttachInfo.mDragSurface.release();
20496        }
20497        mAttachInfo.mDragSurface = new Surface();
20498        try {
20499            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20500                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20501            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20502                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20503            if (mAttachInfo.mDragToken != null) {
20504                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20505                try {
20506                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20507                    shadowBuilder.onDrawShadow(canvas);
20508                } finally {
20509                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20510                }
20511
20512                final ViewRootImpl root = getViewRootImpl();
20513
20514                // Cache the local state object for delivery with DragEvents
20515                root.setLocalDragState(myLocalState);
20516
20517                // repurpose 'shadowSize' for the last touch point
20518                root.getLastTouchPoint(shadowSize);
20519
20520                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20521                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20522                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20523                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20524            }
20525        } catch (Exception e) {
20526            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20527            mAttachInfo.mDragSurface.destroy();
20528            mAttachInfo.mDragSurface = null;
20529        }
20530
20531        return okay;
20532    }
20533
20534    /**
20535     * Cancels an ongoing drag and drop operation.
20536     * <p>
20537     * A {@link android.view.DragEvent} object with
20538     * {@link android.view.DragEvent#getAction()} value of
20539     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20540     * {@link android.view.DragEvent#getResult()} value of {@code false}
20541     * will be sent to every
20542     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20543     * even if they are not currently visible.
20544     * </p>
20545     * <p>
20546     * This method can be called on any View in the same window as the View on which
20547     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20548     * was called.
20549     * </p>
20550     */
20551    public final void cancelDragAndDrop() {
20552        if (ViewDebug.DEBUG_DRAG) {
20553            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20554        }
20555        if (mAttachInfo.mDragToken != null) {
20556            try {
20557                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20558            } catch (Exception e) {
20559                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20560            }
20561            mAttachInfo.mDragToken = null;
20562        } else {
20563            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20564        }
20565    }
20566
20567    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20568        if (ViewDebug.DEBUG_DRAG) {
20569            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20570        }
20571        if (mAttachInfo.mDragToken != null) {
20572            try {
20573                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20574                try {
20575                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20576                    shadowBuilder.onDrawShadow(canvas);
20577                } finally {
20578                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20579                }
20580            } catch (Exception e) {
20581                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20582            }
20583        } else {
20584            Log.e(VIEW_LOG_TAG, "No active drag");
20585        }
20586    }
20587
20588    /**
20589     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20590     * between {startX, startY} and the new cursor positon.
20591     * @param startX horizontal coordinate where the move started.
20592     * @param startY vertical coordinate where the move started.
20593     * @return whether moving was started successfully.
20594     * @hide
20595     */
20596    public final boolean startMovingTask(float startX, float startY) {
20597        if (ViewDebug.DEBUG_POSITIONING) {
20598            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20599        }
20600        try {
20601            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20602        } catch (RemoteException e) {
20603            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20604        }
20605        return false;
20606    }
20607
20608    /**
20609     * Handles drag events sent by the system following a call to
20610     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20611     * startDragAndDrop()}.
20612     *<p>
20613     * When the system calls this method, it passes a
20614     * {@link android.view.DragEvent} object. A call to
20615     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20616     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20617     * operation.
20618     * @param event The {@link android.view.DragEvent} sent by the system.
20619     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20620     * in DragEvent, indicating the type of drag event represented by this object.
20621     * @return {@code true} if the method was successful, otherwise {@code false}.
20622     * <p>
20623     *  The method should return {@code true} in response to an action type of
20624     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20625     *  operation.
20626     * </p>
20627     * <p>
20628     *  The method should also return {@code true} in response to an action type of
20629     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20630     *  {@code false} if it didn't.
20631     * </p>
20632     */
20633    public boolean onDragEvent(DragEvent event) {
20634        return false;
20635    }
20636
20637    /**
20638     * Detects if this View is enabled and has a drag event listener.
20639     * If both are true, then it calls the drag event listener with the
20640     * {@link android.view.DragEvent} it received. If the drag event listener returns
20641     * {@code true}, then dispatchDragEvent() returns {@code true}.
20642     * <p>
20643     * For all other cases, the method calls the
20644     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20645     * method and returns its result.
20646     * </p>
20647     * <p>
20648     * This ensures that a drag event is always consumed, even if the View does not have a drag
20649     * event listener. However, if the View has a listener and the listener returns true, then
20650     * onDragEvent() is not called.
20651     * </p>
20652     */
20653    public boolean dispatchDragEvent(DragEvent event) {
20654        ListenerInfo li = mListenerInfo;
20655        //noinspection SimplifiableIfStatement
20656        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20657                && li.mOnDragListener.onDrag(this, event)) {
20658            return true;
20659        }
20660        return onDragEvent(event);
20661    }
20662
20663    boolean canAcceptDrag() {
20664        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20665    }
20666
20667    /**
20668     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20669     * it is ever exposed at all.
20670     * @hide
20671     */
20672    public void onCloseSystemDialogs(String reason) {
20673    }
20674
20675    /**
20676     * Given a Drawable whose bounds have been set to draw into this view,
20677     * update a Region being computed for
20678     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20679     * that any non-transparent parts of the Drawable are removed from the
20680     * given transparent region.
20681     *
20682     * @param dr The Drawable whose transparency is to be applied to the region.
20683     * @param region A Region holding the current transparency information,
20684     * where any parts of the region that are set are considered to be
20685     * transparent.  On return, this region will be modified to have the
20686     * transparency information reduced by the corresponding parts of the
20687     * Drawable that are not transparent.
20688     * {@hide}
20689     */
20690    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20691        if (DBG) {
20692            Log.i("View", "Getting transparent region for: " + this);
20693        }
20694        final Region r = dr.getTransparentRegion();
20695        final Rect db = dr.getBounds();
20696        final AttachInfo attachInfo = mAttachInfo;
20697        if (r != null && attachInfo != null) {
20698            final int w = getRight()-getLeft();
20699            final int h = getBottom()-getTop();
20700            if (db.left > 0) {
20701                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20702                r.op(0, 0, db.left, h, Region.Op.UNION);
20703            }
20704            if (db.right < w) {
20705                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20706                r.op(db.right, 0, w, h, Region.Op.UNION);
20707            }
20708            if (db.top > 0) {
20709                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20710                r.op(0, 0, w, db.top, Region.Op.UNION);
20711            }
20712            if (db.bottom < h) {
20713                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20714                r.op(0, db.bottom, w, h, Region.Op.UNION);
20715            }
20716            final int[] location = attachInfo.mTransparentLocation;
20717            getLocationInWindow(location);
20718            r.translate(location[0], location[1]);
20719            region.op(r, Region.Op.INTERSECT);
20720        } else {
20721            region.op(db, Region.Op.DIFFERENCE);
20722        }
20723    }
20724
20725    private void checkForLongClick(int delayOffset, float x, float y) {
20726        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20727            mHasPerformedLongPress = false;
20728
20729            if (mPendingCheckForLongPress == null) {
20730                mPendingCheckForLongPress = new CheckForLongPress();
20731            }
20732            mPendingCheckForLongPress.setAnchor(x, y);
20733            mPendingCheckForLongPress.rememberWindowAttachCount();
20734            postDelayed(mPendingCheckForLongPress,
20735                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20736        }
20737    }
20738
20739    /**
20740     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20741     * LayoutInflater} class, which provides a full range of options for view inflation.
20742     *
20743     * @param context The Context object for your activity or application.
20744     * @param resource The resource ID to inflate
20745     * @param root A view group that will be the parent.  Used to properly inflate the
20746     * layout_* parameters.
20747     * @see LayoutInflater
20748     */
20749    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20750        LayoutInflater factory = LayoutInflater.from(context);
20751        return factory.inflate(resource, root);
20752    }
20753
20754    /**
20755     * Scroll the view with standard behavior for scrolling beyond the normal
20756     * content boundaries. Views that call this method should override
20757     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20758     * results of an over-scroll operation.
20759     *
20760     * Views can use this method to handle any touch or fling-based scrolling.
20761     *
20762     * @param deltaX Change in X in pixels
20763     * @param deltaY Change in Y in pixels
20764     * @param scrollX Current X scroll value in pixels before applying deltaX
20765     * @param scrollY Current Y scroll value in pixels before applying deltaY
20766     * @param scrollRangeX Maximum content scroll range along the X axis
20767     * @param scrollRangeY Maximum content scroll range along the Y axis
20768     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20769     *          along the X axis.
20770     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20771     *          along the Y axis.
20772     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20773     * @return true if scrolling was clamped to an over-scroll boundary along either
20774     *          axis, false otherwise.
20775     */
20776    @SuppressWarnings({"UnusedParameters"})
20777    protected boolean overScrollBy(int deltaX, int deltaY,
20778            int scrollX, int scrollY,
20779            int scrollRangeX, int scrollRangeY,
20780            int maxOverScrollX, int maxOverScrollY,
20781            boolean isTouchEvent) {
20782        final int overScrollMode = mOverScrollMode;
20783        final boolean canScrollHorizontal =
20784                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
20785        final boolean canScrollVertical =
20786                computeVerticalScrollRange() > computeVerticalScrollExtent();
20787        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
20788                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
20789        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
20790                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
20791
20792        int newScrollX = scrollX + deltaX;
20793        if (!overScrollHorizontal) {
20794            maxOverScrollX = 0;
20795        }
20796
20797        int newScrollY = scrollY + deltaY;
20798        if (!overScrollVertical) {
20799            maxOverScrollY = 0;
20800        }
20801
20802        // Clamp values if at the limits and record
20803        final int left = -maxOverScrollX;
20804        final int right = maxOverScrollX + scrollRangeX;
20805        final int top = -maxOverScrollY;
20806        final int bottom = maxOverScrollY + scrollRangeY;
20807
20808        boolean clampedX = false;
20809        if (newScrollX > right) {
20810            newScrollX = right;
20811            clampedX = true;
20812        } else if (newScrollX < left) {
20813            newScrollX = left;
20814            clampedX = true;
20815        }
20816
20817        boolean clampedY = false;
20818        if (newScrollY > bottom) {
20819            newScrollY = bottom;
20820            clampedY = true;
20821        } else if (newScrollY < top) {
20822            newScrollY = top;
20823            clampedY = true;
20824        }
20825
20826        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
20827
20828        return clampedX || clampedY;
20829    }
20830
20831    /**
20832     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
20833     * respond to the results of an over-scroll operation.
20834     *
20835     * @param scrollX New X scroll value in pixels
20836     * @param scrollY New Y scroll value in pixels
20837     * @param clampedX True if scrollX was clamped to an over-scroll boundary
20838     * @param clampedY True if scrollY was clamped to an over-scroll boundary
20839     */
20840    protected void onOverScrolled(int scrollX, int scrollY,
20841            boolean clampedX, boolean clampedY) {
20842        // Intentionally empty.
20843    }
20844
20845    /**
20846     * Returns the over-scroll mode for this view. The result will be
20847     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20848     * (allow over-scrolling only if the view content is larger than the container),
20849     * or {@link #OVER_SCROLL_NEVER}.
20850     *
20851     * @return This view's over-scroll mode.
20852     */
20853    public int getOverScrollMode() {
20854        return mOverScrollMode;
20855    }
20856
20857    /**
20858     * Set the over-scroll mode for this view. Valid over-scroll modes are
20859     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20860     * (allow over-scrolling only if the view content is larger than the container),
20861     * or {@link #OVER_SCROLL_NEVER}.
20862     *
20863     * Setting the over-scroll mode of a view will have an effect only if the
20864     * view is capable of scrolling.
20865     *
20866     * @param overScrollMode The new over-scroll mode for this view.
20867     */
20868    public void setOverScrollMode(int overScrollMode) {
20869        if (overScrollMode != OVER_SCROLL_ALWAYS &&
20870                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
20871                overScrollMode != OVER_SCROLL_NEVER) {
20872            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
20873        }
20874        mOverScrollMode = overScrollMode;
20875    }
20876
20877    /**
20878     * Enable or disable nested scrolling for this view.
20879     *
20880     * <p>If this property is set to true the view will be permitted to initiate nested
20881     * scrolling operations with a compatible parent view in the current hierarchy. If this
20882     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
20883     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
20884     * the nested scroll.</p>
20885     *
20886     * @param enabled true to enable nested scrolling, false to disable
20887     *
20888     * @see #isNestedScrollingEnabled()
20889     */
20890    public void setNestedScrollingEnabled(boolean enabled) {
20891        if (enabled) {
20892            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
20893        } else {
20894            stopNestedScroll();
20895            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
20896        }
20897    }
20898
20899    /**
20900     * Returns true if nested scrolling is enabled for this view.
20901     *
20902     * <p>If nested scrolling is enabled and this View class implementation supports it,
20903     * this view will act as a nested scrolling child view when applicable, forwarding data
20904     * about the scroll operation in progress to a compatible and cooperating nested scrolling
20905     * parent.</p>
20906     *
20907     * @return true if nested scrolling is enabled
20908     *
20909     * @see #setNestedScrollingEnabled(boolean)
20910     */
20911    public boolean isNestedScrollingEnabled() {
20912        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
20913                PFLAG3_NESTED_SCROLLING_ENABLED;
20914    }
20915
20916    /**
20917     * Begin a nestable scroll operation along the given axes.
20918     *
20919     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
20920     *
20921     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
20922     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
20923     * In the case of touch scrolling the nested scroll will be terminated automatically in
20924     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
20925     * In the event of programmatic scrolling the caller must explicitly call
20926     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
20927     *
20928     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
20929     * If it returns false the caller may ignore the rest of this contract until the next scroll.
20930     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
20931     *
20932     * <p>At each incremental step of the scroll the caller should invoke
20933     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
20934     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
20935     * parent at least partially consumed the scroll and the caller should adjust the amount it
20936     * scrolls by.</p>
20937     *
20938     * <p>After applying the remainder of the scroll delta the caller should invoke
20939     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
20940     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
20941     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
20942     * </p>
20943     *
20944     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
20945     *             {@link #SCROLL_AXIS_VERTICAL}.
20946     * @return true if a cooperative parent was found and nested scrolling has been enabled for
20947     *         the current gesture.
20948     *
20949     * @see #stopNestedScroll()
20950     * @see #dispatchNestedPreScroll(int, int, int[], int[])
20951     * @see #dispatchNestedScroll(int, int, int, int, int[])
20952     */
20953    public boolean startNestedScroll(int axes) {
20954        if (hasNestedScrollingParent()) {
20955            // Already in progress
20956            return true;
20957        }
20958        if (isNestedScrollingEnabled()) {
20959            ViewParent p = getParent();
20960            View child = this;
20961            while (p != null) {
20962                try {
20963                    if (p.onStartNestedScroll(child, this, axes)) {
20964                        mNestedScrollingParent = p;
20965                        p.onNestedScrollAccepted(child, this, axes);
20966                        return true;
20967                    }
20968                } catch (AbstractMethodError e) {
20969                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
20970                            "method onStartNestedScroll", e);
20971                    // Allow the search upward to continue
20972                }
20973                if (p instanceof View) {
20974                    child = (View) p;
20975                }
20976                p = p.getParent();
20977            }
20978        }
20979        return false;
20980    }
20981
20982    /**
20983     * Stop a nested scroll in progress.
20984     *
20985     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
20986     *
20987     * @see #startNestedScroll(int)
20988     */
20989    public void stopNestedScroll() {
20990        if (mNestedScrollingParent != null) {
20991            mNestedScrollingParent.onStopNestedScroll(this);
20992            mNestedScrollingParent = null;
20993        }
20994    }
20995
20996    /**
20997     * Returns true if this view has a nested scrolling parent.
20998     *
20999     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21000     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21001     *
21002     * @return whether this view has a nested scrolling parent
21003     */
21004    public boolean hasNestedScrollingParent() {
21005        return mNestedScrollingParent != null;
21006    }
21007
21008    /**
21009     * Dispatch one step of a nested scroll in progress.
21010     *
21011     * <p>Implementations of views that support nested scrolling should call this to report
21012     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21013     * is not currently in progress or nested scrolling is not
21014     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21015     *
21016     * <p>Compatible View implementations should also call
21017     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21018     * consuming a component of the scroll event themselves.</p>
21019     *
21020     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21021     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21022     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21023     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21024     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21025     *                       in local view coordinates of this view from before this operation
21026     *                       to after it completes. View implementations may use this to adjust
21027     *                       expected input coordinate tracking.
21028     * @return true if the event was dispatched, false if it could not be dispatched.
21029     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21030     */
21031    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21032            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21033        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21034            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21035                int startX = 0;
21036                int startY = 0;
21037                if (offsetInWindow != null) {
21038                    getLocationInWindow(offsetInWindow);
21039                    startX = offsetInWindow[0];
21040                    startY = offsetInWindow[1];
21041                }
21042
21043                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21044                        dxUnconsumed, dyUnconsumed);
21045
21046                if (offsetInWindow != null) {
21047                    getLocationInWindow(offsetInWindow);
21048                    offsetInWindow[0] -= startX;
21049                    offsetInWindow[1] -= startY;
21050                }
21051                return true;
21052            } else if (offsetInWindow != null) {
21053                // No motion, no dispatch. Keep offsetInWindow up to date.
21054                offsetInWindow[0] = 0;
21055                offsetInWindow[1] = 0;
21056            }
21057        }
21058        return false;
21059    }
21060
21061    /**
21062     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21063     *
21064     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21065     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21066     * scrolling operation to consume some or all of the scroll operation before the child view
21067     * consumes it.</p>
21068     *
21069     * @param dx Horizontal scroll distance in pixels
21070     * @param dy Vertical scroll distance in pixels
21071     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21072     *                 and consumed[1] the consumed dy.
21073     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21074     *                       in local view coordinates of this view from before this operation
21075     *                       to after it completes. View implementations may use this to adjust
21076     *                       expected input coordinate tracking.
21077     * @return true if the parent consumed some or all of the scroll delta
21078     * @see #dispatchNestedScroll(int, int, int, int, int[])
21079     */
21080    public boolean dispatchNestedPreScroll(int dx, int dy,
21081            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21082        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21083            if (dx != 0 || dy != 0) {
21084                int startX = 0;
21085                int startY = 0;
21086                if (offsetInWindow != null) {
21087                    getLocationInWindow(offsetInWindow);
21088                    startX = offsetInWindow[0];
21089                    startY = offsetInWindow[1];
21090                }
21091
21092                if (consumed == null) {
21093                    if (mTempNestedScrollConsumed == null) {
21094                        mTempNestedScrollConsumed = new int[2];
21095                    }
21096                    consumed = mTempNestedScrollConsumed;
21097                }
21098                consumed[0] = 0;
21099                consumed[1] = 0;
21100                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21101
21102                if (offsetInWindow != null) {
21103                    getLocationInWindow(offsetInWindow);
21104                    offsetInWindow[0] -= startX;
21105                    offsetInWindow[1] -= startY;
21106                }
21107                return consumed[0] != 0 || consumed[1] != 0;
21108            } else if (offsetInWindow != null) {
21109                offsetInWindow[0] = 0;
21110                offsetInWindow[1] = 0;
21111            }
21112        }
21113        return false;
21114    }
21115
21116    /**
21117     * Dispatch a fling to a nested scrolling parent.
21118     *
21119     * <p>This method should be used to indicate that a nested scrolling child has detected
21120     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21121     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21122     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21123     * along a scrollable axis.</p>
21124     *
21125     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21126     * its own content, it can use this method to delegate the fling to its nested scrolling
21127     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21128     *
21129     * @param velocityX Horizontal fling velocity in pixels per second
21130     * @param velocityY Vertical fling velocity in pixels per second
21131     * @param consumed true if the child consumed the fling, false otherwise
21132     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21133     */
21134    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21135        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21136            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21137        }
21138        return false;
21139    }
21140
21141    /**
21142     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21143     *
21144     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21145     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21146     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21147     * before the child view consumes it. If this method returns <code>true</code>, a nested
21148     * parent view consumed the fling and this view should not scroll as a result.</p>
21149     *
21150     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21151     * the fling at a time. If a parent view consumed the fling this method will return false.
21152     * Custom view implementations should account for this in two ways:</p>
21153     *
21154     * <ul>
21155     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21156     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21157     *     position regardless.</li>
21158     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21159     *     even to settle back to a valid idle position.</li>
21160     * </ul>
21161     *
21162     * <p>Views should also not offer fling velocities to nested parent views along an axis
21163     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21164     * should not offer a horizontal fling velocity to its parents since scrolling along that
21165     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21166     *
21167     * @param velocityX Horizontal fling velocity in pixels per second
21168     * @param velocityY Vertical fling velocity in pixels per second
21169     * @return true if a nested scrolling parent consumed the fling
21170     */
21171    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21172        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21173            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21174        }
21175        return false;
21176    }
21177
21178    /**
21179     * Gets a scale factor that determines the distance the view should scroll
21180     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21181     * @return The vertical scroll scale factor.
21182     * @hide
21183     */
21184    protected float getVerticalScrollFactor() {
21185        if (mVerticalScrollFactor == 0) {
21186            TypedValue outValue = new TypedValue();
21187            if (!mContext.getTheme().resolveAttribute(
21188                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21189                throw new IllegalStateException(
21190                        "Expected theme to define listPreferredItemHeight.");
21191            }
21192            mVerticalScrollFactor = outValue.getDimension(
21193                    mContext.getResources().getDisplayMetrics());
21194        }
21195        return mVerticalScrollFactor;
21196    }
21197
21198    /**
21199     * Gets a scale factor that determines the distance the view should scroll
21200     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21201     * @return The horizontal scroll scale factor.
21202     * @hide
21203     */
21204    protected float getHorizontalScrollFactor() {
21205        // TODO: Should use something else.
21206        return getVerticalScrollFactor();
21207    }
21208
21209    /**
21210     * Return the value specifying the text direction or policy that was set with
21211     * {@link #setTextDirection(int)}.
21212     *
21213     * @return the defined text direction. It can be one of:
21214     *
21215     * {@link #TEXT_DIRECTION_INHERIT},
21216     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21217     * {@link #TEXT_DIRECTION_ANY_RTL},
21218     * {@link #TEXT_DIRECTION_LTR},
21219     * {@link #TEXT_DIRECTION_RTL},
21220     * {@link #TEXT_DIRECTION_LOCALE},
21221     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21222     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21223     *
21224     * @attr ref android.R.styleable#View_textDirection
21225     *
21226     * @hide
21227     */
21228    @ViewDebug.ExportedProperty(category = "text", mapping = {
21229            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21230            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21231            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21232            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21233            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21234            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21235            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21236            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21237    })
21238    public int getRawTextDirection() {
21239        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21240    }
21241
21242    /**
21243     * Set the text direction.
21244     *
21245     * @param textDirection the direction to set. Should be one of:
21246     *
21247     * {@link #TEXT_DIRECTION_INHERIT},
21248     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21249     * {@link #TEXT_DIRECTION_ANY_RTL},
21250     * {@link #TEXT_DIRECTION_LTR},
21251     * {@link #TEXT_DIRECTION_RTL},
21252     * {@link #TEXT_DIRECTION_LOCALE}
21253     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21254     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21255     *
21256     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21257     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21258     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21259     *
21260     * @attr ref android.R.styleable#View_textDirection
21261     */
21262    public void setTextDirection(int textDirection) {
21263        if (getRawTextDirection() != textDirection) {
21264            // Reset the current text direction and the resolved one
21265            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21266            resetResolvedTextDirection();
21267            // Set the new text direction
21268            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21269            // Do resolution
21270            resolveTextDirection();
21271            // Notify change
21272            onRtlPropertiesChanged(getLayoutDirection());
21273            // Refresh
21274            requestLayout();
21275            invalidate(true);
21276        }
21277    }
21278
21279    /**
21280     * Return the resolved text direction.
21281     *
21282     * @return the resolved text direction. Returns one of:
21283     *
21284     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21285     * {@link #TEXT_DIRECTION_ANY_RTL},
21286     * {@link #TEXT_DIRECTION_LTR},
21287     * {@link #TEXT_DIRECTION_RTL},
21288     * {@link #TEXT_DIRECTION_LOCALE},
21289     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21290     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21291     *
21292     * @attr ref android.R.styleable#View_textDirection
21293     */
21294    @ViewDebug.ExportedProperty(category = "text", mapping = {
21295            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21296            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21297            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21298            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21299            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21300            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21301            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21302            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21303    })
21304    public int getTextDirection() {
21305        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21306    }
21307
21308    /**
21309     * Resolve the text direction.
21310     *
21311     * @return true if resolution has been done, false otherwise.
21312     *
21313     * @hide
21314     */
21315    public boolean resolveTextDirection() {
21316        // Reset any previous text direction resolution
21317        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21318
21319        if (hasRtlSupport()) {
21320            // Set resolved text direction flag depending on text direction flag
21321            final int textDirection = getRawTextDirection();
21322            switch(textDirection) {
21323                case TEXT_DIRECTION_INHERIT:
21324                    if (!canResolveTextDirection()) {
21325                        // We cannot do the resolution if there is no parent, so use the default one
21326                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21327                        // Resolution will need to happen again later
21328                        return false;
21329                    }
21330
21331                    // Parent has not yet resolved, so we still return the default
21332                    try {
21333                        if (!mParent.isTextDirectionResolved()) {
21334                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21335                            // Resolution will need to happen again later
21336                            return false;
21337                        }
21338                    } catch (AbstractMethodError e) {
21339                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21340                                " does not fully implement ViewParent", e);
21341                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21342                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21343                        return true;
21344                    }
21345
21346                    // Set current resolved direction to the same value as the parent's one
21347                    int parentResolvedDirection;
21348                    try {
21349                        parentResolvedDirection = mParent.getTextDirection();
21350                    } catch (AbstractMethodError e) {
21351                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21352                                " does not fully implement ViewParent", e);
21353                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21354                    }
21355                    switch (parentResolvedDirection) {
21356                        case TEXT_DIRECTION_FIRST_STRONG:
21357                        case TEXT_DIRECTION_ANY_RTL:
21358                        case TEXT_DIRECTION_LTR:
21359                        case TEXT_DIRECTION_RTL:
21360                        case TEXT_DIRECTION_LOCALE:
21361                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21362                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21363                            mPrivateFlags2 |=
21364                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21365                            break;
21366                        default:
21367                            // Default resolved direction is "first strong" heuristic
21368                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21369                    }
21370                    break;
21371                case TEXT_DIRECTION_FIRST_STRONG:
21372                case TEXT_DIRECTION_ANY_RTL:
21373                case TEXT_DIRECTION_LTR:
21374                case TEXT_DIRECTION_RTL:
21375                case TEXT_DIRECTION_LOCALE:
21376                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21377                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21378                    // Resolved direction is the same as text direction
21379                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21380                    break;
21381                default:
21382                    // Default resolved direction is "first strong" heuristic
21383                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21384            }
21385        } else {
21386            // Default resolved direction is "first strong" heuristic
21387            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21388        }
21389
21390        // Set to resolved
21391        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21392        return true;
21393    }
21394
21395    /**
21396     * Check if text direction resolution can be done.
21397     *
21398     * @return true if text direction resolution can be done otherwise return false.
21399     */
21400    public boolean canResolveTextDirection() {
21401        switch (getRawTextDirection()) {
21402            case TEXT_DIRECTION_INHERIT:
21403                if (mParent != null) {
21404                    try {
21405                        return mParent.canResolveTextDirection();
21406                    } catch (AbstractMethodError e) {
21407                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21408                                " does not fully implement ViewParent", e);
21409                    }
21410                }
21411                return false;
21412
21413            default:
21414                return true;
21415        }
21416    }
21417
21418    /**
21419     * Reset resolved text direction. Text direction will be resolved during a call to
21420     * {@link #onMeasure(int, int)}.
21421     *
21422     * @hide
21423     */
21424    public void resetResolvedTextDirection() {
21425        // Reset any previous text direction resolution
21426        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21427        // Set to default value
21428        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21429    }
21430
21431    /**
21432     * @return true if text direction is inherited.
21433     *
21434     * @hide
21435     */
21436    public boolean isTextDirectionInherited() {
21437        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21438    }
21439
21440    /**
21441     * @return true if text direction is resolved.
21442     */
21443    public boolean isTextDirectionResolved() {
21444        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21445    }
21446
21447    /**
21448     * Return the value specifying the text alignment or policy that was set with
21449     * {@link #setTextAlignment(int)}.
21450     *
21451     * @return the defined text alignment. It can be one of:
21452     *
21453     * {@link #TEXT_ALIGNMENT_INHERIT},
21454     * {@link #TEXT_ALIGNMENT_GRAVITY},
21455     * {@link #TEXT_ALIGNMENT_CENTER},
21456     * {@link #TEXT_ALIGNMENT_TEXT_START},
21457     * {@link #TEXT_ALIGNMENT_TEXT_END},
21458     * {@link #TEXT_ALIGNMENT_VIEW_START},
21459     * {@link #TEXT_ALIGNMENT_VIEW_END}
21460     *
21461     * @attr ref android.R.styleable#View_textAlignment
21462     *
21463     * @hide
21464     */
21465    @ViewDebug.ExportedProperty(category = "text", mapping = {
21466            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21467            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21468            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21469            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21470            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21471            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21472            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21473    })
21474    @TextAlignment
21475    public int getRawTextAlignment() {
21476        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21477    }
21478
21479    /**
21480     * Set the text alignment.
21481     *
21482     * @param textAlignment The text alignment to set. Should be one of
21483     *
21484     * {@link #TEXT_ALIGNMENT_INHERIT},
21485     * {@link #TEXT_ALIGNMENT_GRAVITY},
21486     * {@link #TEXT_ALIGNMENT_CENTER},
21487     * {@link #TEXT_ALIGNMENT_TEXT_START},
21488     * {@link #TEXT_ALIGNMENT_TEXT_END},
21489     * {@link #TEXT_ALIGNMENT_VIEW_START},
21490     * {@link #TEXT_ALIGNMENT_VIEW_END}
21491     *
21492     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21493     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21494     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21495     *
21496     * @attr ref android.R.styleable#View_textAlignment
21497     */
21498    public void setTextAlignment(@TextAlignment int textAlignment) {
21499        if (textAlignment != getRawTextAlignment()) {
21500            // Reset the current and resolved text alignment
21501            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21502            resetResolvedTextAlignment();
21503            // Set the new text alignment
21504            mPrivateFlags2 |=
21505                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21506            // Do resolution
21507            resolveTextAlignment();
21508            // Notify change
21509            onRtlPropertiesChanged(getLayoutDirection());
21510            // Refresh
21511            requestLayout();
21512            invalidate(true);
21513        }
21514    }
21515
21516    /**
21517     * Return the resolved text alignment.
21518     *
21519     * @return the resolved text alignment. Returns one of:
21520     *
21521     * {@link #TEXT_ALIGNMENT_GRAVITY},
21522     * {@link #TEXT_ALIGNMENT_CENTER},
21523     * {@link #TEXT_ALIGNMENT_TEXT_START},
21524     * {@link #TEXT_ALIGNMENT_TEXT_END},
21525     * {@link #TEXT_ALIGNMENT_VIEW_START},
21526     * {@link #TEXT_ALIGNMENT_VIEW_END}
21527     *
21528     * @attr ref android.R.styleable#View_textAlignment
21529     */
21530    @ViewDebug.ExportedProperty(category = "text", mapping = {
21531            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21532            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21533            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21534            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21535            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21536            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21537            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21538    })
21539    @TextAlignment
21540    public int getTextAlignment() {
21541        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21542                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21543    }
21544
21545    /**
21546     * Resolve the text alignment.
21547     *
21548     * @return true if resolution has been done, false otherwise.
21549     *
21550     * @hide
21551     */
21552    public boolean resolveTextAlignment() {
21553        // Reset any previous text alignment resolution
21554        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21555
21556        if (hasRtlSupport()) {
21557            // Set resolved text alignment flag depending on text alignment flag
21558            final int textAlignment = getRawTextAlignment();
21559            switch (textAlignment) {
21560                case TEXT_ALIGNMENT_INHERIT:
21561                    // Check if we can resolve the text alignment
21562                    if (!canResolveTextAlignment()) {
21563                        // We cannot do the resolution if there is no parent so use the default
21564                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21565                        // Resolution will need to happen again later
21566                        return false;
21567                    }
21568
21569                    // Parent has not yet resolved, so we still return the default
21570                    try {
21571                        if (!mParent.isTextAlignmentResolved()) {
21572                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21573                            // Resolution will need to happen again later
21574                            return false;
21575                        }
21576                    } catch (AbstractMethodError e) {
21577                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21578                                " does not fully implement ViewParent", e);
21579                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21580                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21581                        return true;
21582                    }
21583
21584                    int parentResolvedTextAlignment;
21585                    try {
21586                        parentResolvedTextAlignment = mParent.getTextAlignment();
21587                    } catch (AbstractMethodError e) {
21588                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21589                                " does not fully implement ViewParent", e);
21590                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21591                    }
21592                    switch (parentResolvedTextAlignment) {
21593                        case TEXT_ALIGNMENT_GRAVITY:
21594                        case TEXT_ALIGNMENT_TEXT_START:
21595                        case TEXT_ALIGNMENT_TEXT_END:
21596                        case TEXT_ALIGNMENT_CENTER:
21597                        case TEXT_ALIGNMENT_VIEW_START:
21598                        case TEXT_ALIGNMENT_VIEW_END:
21599                            // Resolved text alignment is the same as the parent resolved
21600                            // text alignment
21601                            mPrivateFlags2 |=
21602                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21603                            break;
21604                        default:
21605                            // Use default resolved text alignment
21606                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21607                    }
21608                    break;
21609                case TEXT_ALIGNMENT_GRAVITY:
21610                case TEXT_ALIGNMENT_TEXT_START:
21611                case TEXT_ALIGNMENT_TEXT_END:
21612                case TEXT_ALIGNMENT_CENTER:
21613                case TEXT_ALIGNMENT_VIEW_START:
21614                case TEXT_ALIGNMENT_VIEW_END:
21615                    // Resolved text alignment is the same as text alignment
21616                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21617                    break;
21618                default:
21619                    // Use default resolved text alignment
21620                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21621            }
21622        } else {
21623            // Use default resolved text alignment
21624            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21625        }
21626
21627        // Set the resolved
21628        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21629        return true;
21630    }
21631
21632    /**
21633     * Check if text alignment resolution can be done.
21634     *
21635     * @return true if text alignment resolution can be done otherwise return false.
21636     */
21637    public boolean canResolveTextAlignment() {
21638        switch (getRawTextAlignment()) {
21639            case TEXT_DIRECTION_INHERIT:
21640                if (mParent != null) {
21641                    try {
21642                        return mParent.canResolveTextAlignment();
21643                    } catch (AbstractMethodError e) {
21644                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21645                                " does not fully implement ViewParent", e);
21646                    }
21647                }
21648                return false;
21649
21650            default:
21651                return true;
21652        }
21653    }
21654
21655    /**
21656     * Reset resolved text alignment. Text alignment will be resolved during a call to
21657     * {@link #onMeasure(int, int)}.
21658     *
21659     * @hide
21660     */
21661    public void resetResolvedTextAlignment() {
21662        // Reset any previous text alignment resolution
21663        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21664        // Set to default
21665        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21666    }
21667
21668    /**
21669     * @return true if text alignment is inherited.
21670     *
21671     * @hide
21672     */
21673    public boolean isTextAlignmentInherited() {
21674        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21675    }
21676
21677    /**
21678     * @return true if text alignment is resolved.
21679     */
21680    public boolean isTextAlignmentResolved() {
21681        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21682    }
21683
21684    /**
21685     * Generate a value suitable for use in {@link #setId(int)}.
21686     * This value will not collide with ID values generated at build time by aapt for R.id.
21687     *
21688     * @return a generated ID value
21689     */
21690    public static int generateViewId() {
21691        for (;;) {
21692            final int result = sNextGeneratedId.get();
21693            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21694            int newValue = result + 1;
21695            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21696            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21697                return result;
21698            }
21699        }
21700    }
21701
21702    /**
21703     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21704     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21705     *                           a normal View or a ViewGroup with
21706     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21707     * @hide
21708     */
21709    public void captureTransitioningViews(List<View> transitioningViews) {
21710        if (getVisibility() == View.VISIBLE) {
21711            transitioningViews.add(this);
21712        }
21713    }
21714
21715    /**
21716     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21717     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21718     * @hide
21719     */
21720    public void findNamedViews(Map<String, View> namedElements) {
21721        if (getVisibility() == VISIBLE || mGhostView != null) {
21722            String transitionName = getTransitionName();
21723            if (transitionName != null) {
21724                namedElements.put(transitionName, this);
21725            }
21726        }
21727    }
21728
21729    /**
21730     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21731     * The default implementation does not care the location or event types, but some subclasses
21732     * may use it (such as WebViews).
21733     * @param event The MotionEvent from a mouse
21734     * @param x The x position of the event, local to the view
21735     * @param y The y position of the event, local to the view
21736     * @see PointerIcon
21737     */
21738    public PointerIcon getPointerIcon(MotionEvent event, float x, float y) {
21739        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21740            return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW);
21741        }
21742        return mPointerIcon;
21743    }
21744
21745    /**
21746     * Set the pointer icon for the current view.
21747     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21748     */
21749    public void setPointerIcon(PointerIcon pointerIcon) {
21750        mPointerIcon = pointerIcon;
21751        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21752            return;
21753        }
21754        try {
21755            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21756        } catch (RemoteException e) {
21757        }
21758    }
21759
21760    /**
21761     * Request capturing further mouse events.
21762     *
21763     * When the view captures, the mouse pointer icon will disappear and will not change its
21764     * position. Further mouse events will come to the capturing view, and the mouse movements
21765     * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and
21766     * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not
21767     * be affected.
21768     *
21769     * The capture will be released through {@link #releasePointerCapture()}, or will be lost
21770     * automatically when the view or containing window disappear.
21771     *
21772     * @return true when succeeds.
21773     * @see #releasePointerCapture()
21774     * @see #hasPointerCapture()
21775     */
21776    public void setPointerCapture() {
21777        final ViewRootImpl viewRootImpl = getViewRootImpl();
21778        if (viewRootImpl != null) {
21779            viewRootImpl.setPointerCapture(this);
21780        }
21781    }
21782
21783
21784    /**
21785     * Release the current capture of mouse events.
21786     *
21787     * If the view does not have the capture, it will do nothing.
21788     * @see #setPointerCapture()
21789     * @see #hasPointerCapture()
21790     */
21791    public void releasePointerCapture() {
21792        final ViewRootImpl viewRootImpl = getViewRootImpl();
21793        if (viewRootImpl != null) {
21794            viewRootImpl.releasePointerCapture(this);
21795        }
21796    }
21797
21798    /**
21799     * Checks the capture status of mouse events.
21800     *
21801     * @return true if the view has the capture.
21802     * @see #setPointerCapture()
21803     * @see #hasPointerCapture()
21804     */
21805    public boolean hasPointerCapture() {
21806        final ViewRootImpl viewRootImpl = getViewRootImpl();
21807        return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this);
21808    }
21809
21810    //
21811    // Properties
21812    //
21813    /**
21814     * A Property wrapper around the <code>alpha</code> functionality handled by the
21815     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21816     */
21817    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21818        @Override
21819        public void setValue(View object, float value) {
21820            object.setAlpha(value);
21821        }
21822
21823        @Override
21824        public Float get(View object) {
21825            return object.getAlpha();
21826        }
21827    };
21828
21829    /**
21830     * A Property wrapper around the <code>translationX</code> functionality handled by the
21831     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
21832     */
21833    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
21834        @Override
21835        public void setValue(View object, float value) {
21836            object.setTranslationX(value);
21837        }
21838
21839                @Override
21840        public Float get(View object) {
21841            return object.getTranslationX();
21842        }
21843    };
21844
21845    /**
21846     * A Property wrapper around the <code>translationY</code> functionality handled by the
21847     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
21848     */
21849    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
21850        @Override
21851        public void setValue(View object, float value) {
21852            object.setTranslationY(value);
21853        }
21854
21855        @Override
21856        public Float get(View object) {
21857            return object.getTranslationY();
21858        }
21859    };
21860
21861    /**
21862     * A Property wrapper around the <code>translationZ</code> functionality handled by the
21863     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
21864     */
21865    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
21866        @Override
21867        public void setValue(View object, float value) {
21868            object.setTranslationZ(value);
21869        }
21870
21871        @Override
21872        public Float get(View object) {
21873            return object.getTranslationZ();
21874        }
21875    };
21876
21877    /**
21878     * A Property wrapper around the <code>x</code> functionality handled by the
21879     * {@link View#setX(float)} and {@link View#getX()} methods.
21880     */
21881    public static final Property<View, Float> X = new FloatProperty<View>("x") {
21882        @Override
21883        public void setValue(View object, float value) {
21884            object.setX(value);
21885        }
21886
21887        @Override
21888        public Float get(View object) {
21889            return object.getX();
21890        }
21891    };
21892
21893    /**
21894     * A Property wrapper around the <code>y</code> functionality handled by the
21895     * {@link View#setY(float)} and {@link View#getY()} methods.
21896     */
21897    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
21898        @Override
21899        public void setValue(View object, float value) {
21900            object.setY(value);
21901        }
21902
21903        @Override
21904        public Float get(View object) {
21905            return object.getY();
21906        }
21907    };
21908
21909    /**
21910     * A Property wrapper around the <code>z</code> functionality handled by the
21911     * {@link View#setZ(float)} and {@link View#getZ()} methods.
21912     */
21913    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
21914        @Override
21915        public void setValue(View object, float value) {
21916            object.setZ(value);
21917        }
21918
21919        @Override
21920        public Float get(View object) {
21921            return object.getZ();
21922        }
21923    };
21924
21925    /**
21926     * A Property wrapper around the <code>rotation</code> functionality handled by the
21927     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
21928     */
21929    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
21930        @Override
21931        public void setValue(View object, float value) {
21932            object.setRotation(value);
21933        }
21934
21935        @Override
21936        public Float get(View object) {
21937            return object.getRotation();
21938        }
21939    };
21940
21941    /**
21942     * A Property wrapper around the <code>rotationX</code> functionality handled by the
21943     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
21944     */
21945    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
21946        @Override
21947        public void setValue(View object, float value) {
21948            object.setRotationX(value);
21949        }
21950
21951        @Override
21952        public Float get(View object) {
21953            return object.getRotationX();
21954        }
21955    };
21956
21957    /**
21958     * A Property wrapper around the <code>rotationY</code> functionality handled by the
21959     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
21960     */
21961    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
21962        @Override
21963        public void setValue(View object, float value) {
21964            object.setRotationY(value);
21965        }
21966
21967        @Override
21968        public Float get(View object) {
21969            return object.getRotationY();
21970        }
21971    };
21972
21973    /**
21974     * A Property wrapper around the <code>scaleX</code> functionality handled by the
21975     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
21976     */
21977    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
21978        @Override
21979        public void setValue(View object, float value) {
21980            object.setScaleX(value);
21981        }
21982
21983        @Override
21984        public Float get(View object) {
21985            return object.getScaleX();
21986        }
21987    };
21988
21989    /**
21990     * A Property wrapper around the <code>scaleY</code> functionality handled by the
21991     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
21992     */
21993    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
21994        @Override
21995        public void setValue(View object, float value) {
21996            object.setScaleY(value);
21997        }
21998
21999        @Override
22000        public Float get(View object) {
22001            return object.getScaleY();
22002        }
22003    };
22004
22005    /**
22006     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22007     * Each MeasureSpec represents a requirement for either the width or the height.
22008     * A MeasureSpec is comprised of a size and a mode. There are three possible
22009     * modes:
22010     * <dl>
22011     * <dt>UNSPECIFIED</dt>
22012     * <dd>
22013     * The parent has not imposed any constraint on the child. It can be whatever size
22014     * it wants.
22015     * </dd>
22016     *
22017     * <dt>EXACTLY</dt>
22018     * <dd>
22019     * The parent has determined an exact size for the child. The child is going to be
22020     * given those bounds regardless of how big it wants to be.
22021     * </dd>
22022     *
22023     * <dt>AT_MOST</dt>
22024     * <dd>
22025     * The child can be as large as it wants up to the specified size.
22026     * </dd>
22027     * </dl>
22028     *
22029     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22030     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22031     */
22032    public static class MeasureSpec {
22033        private static final int MODE_SHIFT = 30;
22034        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22035
22036        /** @hide */
22037        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22038        @Retention(RetentionPolicy.SOURCE)
22039        public @interface MeasureSpecMode {}
22040
22041        /**
22042         * Measure specification mode: The parent has not imposed any constraint
22043         * on the child. It can be whatever size it wants.
22044         */
22045        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22046
22047        /**
22048         * Measure specification mode: The parent has determined an exact size
22049         * for the child. The child is going to be given those bounds regardless
22050         * of how big it wants to be.
22051         */
22052        public static final int EXACTLY     = 1 << MODE_SHIFT;
22053
22054        /**
22055         * Measure specification mode: The child can be as large as it wants up
22056         * to the specified size.
22057         */
22058        public static final int AT_MOST     = 2 << MODE_SHIFT;
22059
22060        /**
22061         * Creates a measure specification based on the supplied size and mode.
22062         *
22063         * The mode must always be one of the following:
22064         * <ul>
22065         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22066         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22067         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22068         * </ul>
22069         *
22070         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22071         * implementation was such that the order of arguments did not matter
22072         * and overflow in either value could impact the resulting MeasureSpec.
22073         * {@link android.widget.RelativeLayout} was affected by this bug.
22074         * Apps targeting API levels greater than 17 will get the fixed, more strict
22075         * behavior.</p>
22076         *
22077         * @param size the size of the measure specification
22078         * @param mode the mode of the measure specification
22079         * @return the measure specification based on size and mode
22080         */
22081        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22082                                          @MeasureSpecMode int mode) {
22083            if (sUseBrokenMakeMeasureSpec) {
22084                return size + mode;
22085            } else {
22086                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22087            }
22088        }
22089
22090        /**
22091         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22092         * will automatically get a size of 0. Older apps expect this.
22093         *
22094         * @hide internal use only for compatibility with system widgets and older apps
22095         */
22096        public static int makeSafeMeasureSpec(int size, int mode) {
22097            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22098                return 0;
22099            }
22100            return makeMeasureSpec(size, mode);
22101        }
22102
22103        /**
22104         * Extracts the mode from the supplied measure specification.
22105         *
22106         * @param measureSpec the measure specification to extract the mode from
22107         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22108         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22109         *         {@link android.view.View.MeasureSpec#EXACTLY}
22110         */
22111        @MeasureSpecMode
22112        public static int getMode(int measureSpec) {
22113            //noinspection ResourceType
22114            return (measureSpec & MODE_MASK);
22115        }
22116
22117        /**
22118         * Extracts the size from the supplied measure specification.
22119         *
22120         * @param measureSpec the measure specification to extract the size from
22121         * @return the size in pixels defined in the supplied measure specification
22122         */
22123        public static int getSize(int measureSpec) {
22124            return (measureSpec & ~MODE_MASK);
22125        }
22126
22127        static int adjust(int measureSpec, int delta) {
22128            final int mode = getMode(measureSpec);
22129            int size = getSize(measureSpec);
22130            if (mode == UNSPECIFIED) {
22131                // No need to adjust size for UNSPECIFIED mode.
22132                return makeMeasureSpec(size, UNSPECIFIED);
22133            }
22134            size += delta;
22135            if (size < 0) {
22136                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22137                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22138                size = 0;
22139            }
22140            return makeMeasureSpec(size, mode);
22141        }
22142
22143        /**
22144         * Returns a String representation of the specified measure
22145         * specification.
22146         *
22147         * @param measureSpec the measure specification to convert to a String
22148         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22149         */
22150        public static String toString(int measureSpec) {
22151            int mode = getMode(measureSpec);
22152            int size = getSize(measureSpec);
22153
22154            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22155
22156            if (mode == UNSPECIFIED)
22157                sb.append("UNSPECIFIED ");
22158            else if (mode == EXACTLY)
22159                sb.append("EXACTLY ");
22160            else if (mode == AT_MOST)
22161                sb.append("AT_MOST ");
22162            else
22163                sb.append(mode).append(" ");
22164
22165            sb.append(size);
22166            return sb.toString();
22167        }
22168    }
22169
22170    private final class CheckForLongPress implements Runnable {
22171        private int mOriginalWindowAttachCount;
22172        private float mX;
22173        private float mY;
22174
22175        @Override
22176        public void run() {
22177            if (isPressed() && (mParent != null)
22178                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22179                if (performLongClick(mX, mY)) {
22180                    mHasPerformedLongPress = true;
22181                }
22182            }
22183        }
22184
22185        public void setAnchor(float x, float y) {
22186            mX = x;
22187            mY = y;
22188        }
22189
22190        public void rememberWindowAttachCount() {
22191            mOriginalWindowAttachCount = mWindowAttachCount;
22192        }
22193    }
22194
22195    private final class CheckForTap implements Runnable {
22196        public float x;
22197        public float y;
22198
22199        @Override
22200        public void run() {
22201            mPrivateFlags &= ~PFLAG_PREPRESSED;
22202            setPressed(true, x, y);
22203            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22204        }
22205    }
22206
22207    private final class PerformClick implements Runnable {
22208        @Override
22209        public void run() {
22210            performClick();
22211        }
22212    }
22213
22214    /**
22215     * This method returns a ViewPropertyAnimator object, which can be used to animate
22216     * specific properties on this View.
22217     *
22218     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22219     */
22220    public ViewPropertyAnimator animate() {
22221        if (mAnimator == null) {
22222            mAnimator = new ViewPropertyAnimator(this);
22223        }
22224        return mAnimator;
22225    }
22226
22227    /**
22228     * Sets the name of the View to be used to identify Views in Transitions.
22229     * Names should be unique in the View hierarchy.
22230     *
22231     * @param transitionName The name of the View to uniquely identify it for Transitions.
22232     */
22233    public final void setTransitionName(String transitionName) {
22234        mTransitionName = transitionName;
22235    }
22236
22237    /**
22238     * Returns the name of the View to be used to identify Views in Transitions.
22239     * Names should be unique in the View hierarchy.
22240     *
22241     * <p>This returns null if the View has not been given a name.</p>
22242     *
22243     * @return The name used of the View to be used to identify Views in Transitions or null
22244     * if no name has been given.
22245     */
22246    @ViewDebug.ExportedProperty
22247    public String getTransitionName() {
22248        return mTransitionName;
22249    }
22250
22251    /**
22252     * @hide
22253     */
22254    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22255        // Do nothing.
22256    }
22257
22258    /**
22259     * Interface definition for a callback to be invoked when a hardware key event is
22260     * dispatched to this view. The callback will be invoked before the key event is
22261     * given to the view. This is only useful for hardware keyboards; a software input
22262     * method has no obligation to trigger this listener.
22263     */
22264    public interface OnKeyListener {
22265        /**
22266         * Called when a hardware key is dispatched to a view. This allows listeners to
22267         * get a chance to respond before the target view.
22268         * <p>Key presses in software keyboards will generally NOT trigger this method,
22269         * although some may elect to do so in some situations. Do not assume a
22270         * software input method has to be key-based; even if it is, it may use key presses
22271         * in a different way than you expect, so there is no way to reliably catch soft
22272         * input key presses.
22273         *
22274         * @param v The view the key has been dispatched to.
22275         * @param keyCode The code for the physical key that was pressed
22276         * @param event The KeyEvent object containing full information about
22277         *        the event.
22278         * @return True if the listener has consumed the event, false otherwise.
22279         */
22280        boolean onKey(View v, int keyCode, KeyEvent event);
22281    }
22282
22283    /**
22284     * Interface definition for a callback to be invoked when a touch event is
22285     * dispatched to this view. The callback will be invoked before the touch
22286     * event is given to the view.
22287     */
22288    public interface OnTouchListener {
22289        /**
22290         * Called when a touch event is dispatched to a view. This allows listeners to
22291         * get a chance to respond before the target view.
22292         *
22293         * @param v The view the touch event has been dispatched to.
22294         * @param event The MotionEvent object containing full information about
22295         *        the event.
22296         * @return True if the listener has consumed the event, false otherwise.
22297         */
22298        boolean onTouch(View v, MotionEvent event);
22299    }
22300
22301    /**
22302     * Interface definition for a callback to be invoked when a hover event is
22303     * dispatched to this view. The callback will be invoked before the hover
22304     * event is given to the view.
22305     */
22306    public interface OnHoverListener {
22307        /**
22308         * Called when a hover event is dispatched to a view. This allows listeners to
22309         * get a chance to respond before the target view.
22310         *
22311         * @param v The view the hover event has been dispatched to.
22312         * @param event The MotionEvent object containing full information about
22313         *        the event.
22314         * @return True if the listener has consumed the event, false otherwise.
22315         */
22316        boolean onHover(View v, MotionEvent event);
22317    }
22318
22319    /**
22320     * Interface definition for a callback to be invoked when a generic motion event is
22321     * dispatched to this view. The callback will be invoked before the generic motion
22322     * event is given to the view.
22323     */
22324    public interface OnGenericMotionListener {
22325        /**
22326         * Called when a generic motion event is dispatched to a view. This allows listeners to
22327         * get a chance to respond before the target view.
22328         *
22329         * @param v The view the generic motion event has been dispatched to.
22330         * @param event The MotionEvent object containing full information about
22331         *        the event.
22332         * @return True if the listener has consumed the event, false otherwise.
22333         */
22334        boolean onGenericMotion(View v, MotionEvent event);
22335    }
22336
22337    /**
22338     * Interface definition for a callback to be invoked when a view has been clicked and held.
22339     */
22340    public interface OnLongClickListener {
22341        /**
22342         * Called when a view has been clicked and held.
22343         *
22344         * @param v The view that was clicked and held.
22345         *
22346         * @return true if the callback consumed the long click, false otherwise.
22347         */
22348        boolean onLongClick(View v);
22349    }
22350
22351    /**
22352     * Interface definition for a callback to be invoked when a drag is being dispatched
22353     * to this view.  The callback will be invoked before the hosting view's own
22354     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22355     * onDrag(event) behavior, it should return 'false' from this callback.
22356     *
22357     * <div class="special reference">
22358     * <h3>Developer Guides</h3>
22359     * <p>For a guide to implementing drag and drop features, read the
22360     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22361     * </div>
22362     */
22363    public interface OnDragListener {
22364        /**
22365         * Called when a drag event is dispatched to a view. This allows listeners
22366         * to get a chance to override base View behavior.
22367         *
22368         * @param v The View that received the drag event.
22369         * @param event The {@link android.view.DragEvent} object for the drag event.
22370         * @return {@code true} if the drag event was handled successfully, or {@code false}
22371         * if the drag event was not handled. Note that {@code false} will trigger the View
22372         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22373         */
22374        boolean onDrag(View v, DragEvent event);
22375    }
22376
22377    /**
22378     * Interface definition for a callback to be invoked when the focus state of
22379     * a view changed.
22380     */
22381    public interface OnFocusChangeListener {
22382        /**
22383         * Called when the focus state of a view has changed.
22384         *
22385         * @param v The view whose state has changed.
22386         * @param hasFocus The new focus state of v.
22387         */
22388        void onFocusChange(View v, boolean hasFocus);
22389    }
22390
22391    /**
22392     * Interface definition for a callback to be invoked when a view is clicked.
22393     */
22394    public interface OnClickListener {
22395        /**
22396         * Called when a view has been clicked.
22397         *
22398         * @param v The view that was clicked.
22399         */
22400        void onClick(View v);
22401    }
22402
22403    /**
22404     * Interface definition for a callback to be invoked when a view is context clicked.
22405     */
22406    public interface OnContextClickListener {
22407        /**
22408         * Called when a view is context clicked.
22409         *
22410         * @param v The view that has been context clicked.
22411         * @return true if the callback consumed the context click, false otherwise.
22412         */
22413        boolean onContextClick(View v);
22414    }
22415
22416    /**
22417     * Interface definition for a callback to be invoked when the context menu
22418     * for this view is being built.
22419     */
22420    public interface OnCreateContextMenuListener {
22421        /**
22422         * Called when the context menu for this view is being built. It is not
22423         * safe to hold onto the menu after this method returns.
22424         *
22425         * @param menu The context menu that is being built
22426         * @param v The view for which the context menu is being built
22427         * @param menuInfo Extra information about the item for which the
22428         *            context menu should be shown. This information will vary
22429         *            depending on the class of v.
22430         */
22431        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22432    }
22433
22434    /**
22435     * Interface definition for a callback to be invoked when the status bar changes
22436     * visibility.  This reports <strong>global</strong> changes to the system UI
22437     * state, not what the application is requesting.
22438     *
22439     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22440     */
22441    public interface OnSystemUiVisibilityChangeListener {
22442        /**
22443         * Called when the status bar changes visibility because of a call to
22444         * {@link View#setSystemUiVisibility(int)}.
22445         *
22446         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22447         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22448         * This tells you the <strong>global</strong> state of these UI visibility
22449         * flags, not what your app is currently applying.
22450         */
22451        public void onSystemUiVisibilityChange(int visibility);
22452    }
22453
22454    /**
22455     * Interface definition for a callback to be invoked when this view is attached
22456     * or detached from its window.
22457     */
22458    public interface OnAttachStateChangeListener {
22459        /**
22460         * Called when the view is attached to a window.
22461         * @param v The view that was attached
22462         */
22463        public void onViewAttachedToWindow(View v);
22464        /**
22465         * Called when the view is detached from a window.
22466         * @param v The view that was detached
22467         */
22468        public void onViewDetachedFromWindow(View v);
22469    }
22470
22471    /**
22472     * Listener for applying window insets on a view in a custom way.
22473     *
22474     * <p>Apps may choose to implement this interface if they want to apply custom policy
22475     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22476     * is set, its
22477     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22478     * method will be called instead of the View's own
22479     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22480     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22481     * the View's normal behavior as part of its own.</p>
22482     */
22483    public interface OnApplyWindowInsetsListener {
22484        /**
22485         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22486         * on a View, this listener method will be called instead of the view's own
22487         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22488         *
22489         * @param v The view applying window insets
22490         * @param insets The insets to apply
22491         * @return The insets supplied, minus any insets that were consumed
22492         */
22493        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22494    }
22495
22496    private final class UnsetPressedState implements Runnable {
22497        @Override
22498        public void run() {
22499            setPressed(false);
22500        }
22501    }
22502
22503    /**
22504     * Base class for derived classes that want to save and restore their own
22505     * state in {@link android.view.View#onSaveInstanceState()}.
22506     */
22507    public static class BaseSavedState extends AbsSavedState {
22508        String mStartActivityRequestWhoSaved;
22509
22510        /**
22511         * Constructor used when reading from a parcel. Reads the state of the superclass.
22512         *
22513         * @param source
22514         */
22515        public BaseSavedState(Parcel source) {
22516            super(source);
22517            mStartActivityRequestWhoSaved = source.readString();
22518        }
22519
22520        /**
22521         * Constructor called by derived classes when creating their SavedState objects
22522         *
22523         * @param superState The state of the superclass of this view
22524         */
22525        public BaseSavedState(Parcelable superState) {
22526            super(superState);
22527        }
22528
22529        @Override
22530        public void writeToParcel(Parcel out, int flags) {
22531            super.writeToParcel(out, flags);
22532            out.writeString(mStartActivityRequestWhoSaved);
22533        }
22534
22535        public static final Parcelable.Creator<BaseSavedState> CREATOR =
22536                new Parcelable.Creator<BaseSavedState>() {
22537            public BaseSavedState createFromParcel(Parcel in) {
22538                return new BaseSavedState(in);
22539            }
22540
22541            public BaseSavedState[] newArray(int size) {
22542                return new BaseSavedState[size];
22543            }
22544        };
22545    }
22546
22547    /**
22548     * A set of information given to a view when it is attached to its parent
22549     * window.
22550     */
22551    final static class AttachInfo {
22552        interface Callbacks {
22553            void playSoundEffect(int effectId);
22554            boolean performHapticFeedback(int effectId, boolean always);
22555        }
22556
22557        /**
22558         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22559         * to a Handler. This class contains the target (View) to invalidate and
22560         * the coordinates of the dirty rectangle.
22561         *
22562         * For performance purposes, this class also implements a pool of up to
22563         * POOL_LIMIT objects that get reused. This reduces memory allocations
22564         * whenever possible.
22565         */
22566        static class InvalidateInfo {
22567            private static final int POOL_LIMIT = 10;
22568
22569            private static final SynchronizedPool<InvalidateInfo> sPool =
22570                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22571
22572            View target;
22573
22574            int left;
22575            int top;
22576            int right;
22577            int bottom;
22578
22579            public static InvalidateInfo obtain() {
22580                InvalidateInfo instance = sPool.acquire();
22581                return (instance != null) ? instance : new InvalidateInfo();
22582            }
22583
22584            public void recycle() {
22585                target = null;
22586                sPool.release(this);
22587            }
22588        }
22589
22590        final IWindowSession mSession;
22591
22592        final IWindow mWindow;
22593
22594        final IBinder mWindowToken;
22595
22596        final Display mDisplay;
22597
22598        final Callbacks mRootCallbacks;
22599
22600        IWindowId mIWindowId;
22601        WindowId mWindowId;
22602
22603        /**
22604         * The top view of the hierarchy.
22605         */
22606        View mRootView;
22607
22608        IBinder mPanelParentWindowToken;
22609
22610        boolean mHardwareAccelerated;
22611        boolean mHardwareAccelerationRequested;
22612        ThreadedRenderer mHardwareRenderer;
22613        List<RenderNode> mPendingAnimatingRenderNodes;
22614
22615        /**
22616         * The state of the display to which the window is attached, as reported
22617         * by {@link Display#getState()}.  Note that the display state constants
22618         * declared by {@link Display} do not exactly line up with the screen state
22619         * constants declared by {@link View} (there are more display states than
22620         * screen states).
22621         */
22622        int mDisplayState = Display.STATE_UNKNOWN;
22623
22624        /**
22625         * Scale factor used by the compatibility mode
22626         */
22627        float mApplicationScale;
22628
22629        /**
22630         * Indicates whether the application is in compatibility mode
22631         */
22632        boolean mScalingRequired;
22633
22634        /**
22635         * Left position of this view's window
22636         */
22637        int mWindowLeft;
22638
22639        /**
22640         * Top position of this view's window
22641         */
22642        int mWindowTop;
22643
22644        /**
22645         * Indicates whether views need to use 32-bit drawing caches
22646         */
22647        boolean mUse32BitDrawingCache;
22648
22649        /**
22650         * For windows that are full-screen but using insets to layout inside
22651         * of the screen areas, these are the current insets to appear inside
22652         * the overscan area of the display.
22653         */
22654        final Rect mOverscanInsets = new Rect();
22655
22656        /**
22657         * For windows that are full-screen but using insets to layout inside
22658         * of the screen decorations, these are the current insets for the
22659         * content of the window.
22660         */
22661        final Rect mContentInsets = new Rect();
22662
22663        /**
22664         * For windows that are full-screen but using insets to layout inside
22665         * of the screen decorations, these are the current insets for the
22666         * actual visible parts of the window.
22667         */
22668        final Rect mVisibleInsets = new Rect();
22669
22670        /**
22671         * For windows that are full-screen but using insets to layout inside
22672         * of the screen decorations, these are the current insets for the
22673         * stable system windows.
22674         */
22675        final Rect mStableInsets = new Rect();
22676
22677        /**
22678         * For windows that include areas that are not covered by real surface these are the outsets
22679         * for real surface.
22680         */
22681        final Rect mOutsets = new Rect();
22682
22683        /**
22684         * In multi-window we force show the navigation bar. Because we don't want that the surface
22685         * size changes in this mode, we instead have a flag whether the navigation bar size should
22686         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22687         */
22688        boolean mAlwaysConsumeNavBar;
22689
22690        /**
22691         * The internal insets given by this window.  This value is
22692         * supplied by the client (through
22693         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22694         * be given to the window manager when changed to be used in laying
22695         * out windows behind it.
22696         */
22697        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22698                = new ViewTreeObserver.InternalInsetsInfo();
22699
22700        /**
22701         * Set to true when mGivenInternalInsets is non-empty.
22702         */
22703        boolean mHasNonEmptyGivenInternalInsets;
22704
22705        /**
22706         * All views in the window's hierarchy that serve as scroll containers,
22707         * used to determine if the window can be resized or must be panned
22708         * to adjust for a soft input area.
22709         */
22710        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22711
22712        final KeyEvent.DispatcherState mKeyDispatchState
22713                = new KeyEvent.DispatcherState();
22714
22715        /**
22716         * Indicates whether the view's window currently has the focus.
22717         */
22718        boolean mHasWindowFocus;
22719
22720        /**
22721         * The current visibility of the window.
22722         */
22723        int mWindowVisibility;
22724
22725        /**
22726         * Indicates the time at which drawing started to occur.
22727         */
22728        long mDrawingTime;
22729
22730        /**
22731         * Indicates whether or not ignoring the DIRTY_MASK flags.
22732         */
22733        boolean mIgnoreDirtyState;
22734
22735        /**
22736         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22737         * to avoid clearing that flag prematurely.
22738         */
22739        boolean mSetIgnoreDirtyState = false;
22740
22741        /**
22742         * Indicates whether the view's window is currently in touch mode.
22743         */
22744        boolean mInTouchMode;
22745
22746        /**
22747         * Indicates whether the view has requested unbuffered input dispatching for the current
22748         * event stream.
22749         */
22750        boolean mUnbufferedDispatchRequested;
22751
22752        /**
22753         * Indicates that ViewAncestor should trigger a global layout change
22754         * the next time it performs a traversal
22755         */
22756        boolean mRecomputeGlobalAttributes;
22757
22758        /**
22759         * Always report new attributes at next traversal.
22760         */
22761        boolean mForceReportNewAttributes;
22762
22763        /**
22764         * Set during a traveral if any views want to keep the screen on.
22765         */
22766        boolean mKeepScreenOn;
22767
22768        /**
22769         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22770         */
22771        int mSystemUiVisibility;
22772
22773        /**
22774         * Hack to force certain system UI visibility flags to be cleared.
22775         */
22776        int mDisabledSystemUiVisibility;
22777
22778        /**
22779         * Last global system UI visibility reported by the window manager.
22780         */
22781        int mGlobalSystemUiVisibility;
22782
22783        /**
22784         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22785         * attached.
22786         */
22787        boolean mHasSystemUiListeners;
22788
22789        /**
22790         * Set if the window has requested to extend into the overscan region
22791         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22792         */
22793        boolean mOverscanRequested;
22794
22795        /**
22796         * Set if the visibility of any views has changed.
22797         */
22798        boolean mViewVisibilityChanged;
22799
22800        /**
22801         * Set to true if a view has been scrolled.
22802         */
22803        boolean mViewScrollChanged;
22804
22805        /**
22806         * Set to true if high contrast mode enabled
22807         */
22808        boolean mHighContrastText;
22809
22810        /**
22811         * Set to true if a pointer event is currently being handled.
22812         */
22813        boolean mHandlingPointerEvent;
22814
22815        /**
22816         * Global to the view hierarchy used as a temporary for dealing with
22817         * x/y points in the transparent region computations.
22818         */
22819        final int[] mTransparentLocation = new int[2];
22820
22821        /**
22822         * Global to the view hierarchy used as a temporary for dealing with
22823         * x/y points in the ViewGroup.invalidateChild implementation.
22824         */
22825        final int[] mInvalidateChildLocation = new int[2];
22826
22827        /**
22828         * Global to the view hierarchy used as a temporary for dealng with
22829         * computing absolute on-screen location.
22830         */
22831        final int[] mTmpLocation = new int[2];
22832
22833        /**
22834         * Global to the view hierarchy used as a temporary for dealing with
22835         * x/y location when view is transformed.
22836         */
22837        final float[] mTmpTransformLocation = new float[2];
22838
22839        /**
22840         * The view tree observer used to dispatch global events like
22841         * layout, pre-draw, touch mode change, etc.
22842         */
22843        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
22844
22845        /**
22846         * A Canvas used by the view hierarchy to perform bitmap caching.
22847         */
22848        Canvas mCanvas;
22849
22850        /**
22851         * The view root impl.
22852         */
22853        final ViewRootImpl mViewRootImpl;
22854
22855        /**
22856         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
22857         * handler can be used to pump events in the UI events queue.
22858         */
22859        final Handler mHandler;
22860
22861        /**
22862         * Temporary for use in computing invalidate rectangles while
22863         * calling up the hierarchy.
22864         */
22865        final Rect mTmpInvalRect = new Rect();
22866
22867        /**
22868         * Temporary for use in computing hit areas with transformed views
22869         */
22870        final RectF mTmpTransformRect = new RectF();
22871
22872        /**
22873         * Temporary for use in computing hit areas with transformed views
22874         */
22875        final RectF mTmpTransformRect1 = new RectF();
22876
22877        /**
22878         * Temporary list of rectanges.
22879         */
22880        final List<RectF> mTmpRectList = new ArrayList<>();
22881
22882        /**
22883         * Temporary for use in transforming invalidation rect
22884         */
22885        final Matrix mTmpMatrix = new Matrix();
22886
22887        /**
22888         * Temporary for use in transforming invalidation rect
22889         */
22890        final Transformation mTmpTransformation = new Transformation();
22891
22892        /**
22893         * Temporary for use in querying outlines from OutlineProviders
22894         */
22895        final Outline mTmpOutline = new Outline();
22896
22897        /**
22898         * Temporary list for use in collecting focusable descendents of a view.
22899         */
22900        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
22901
22902        /**
22903         * The id of the window for accessibility purposes.
22904         */
22905        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
22906
22907        /**
22908         * Flags related to accessibility processing.
22909         *
22910         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
22911         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
22912         */
22913        int mAccessibilityFetchFlags;
22914
22915        /**
22916         * The drawable for highlighting accessibility focus.
22917         */
22918        Drawable mAccessibilityFocusDrawable;
22919
22920        /**
22921         * Show where the margins, bounds and layout bounds are for each view.
22922         */
22923        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
22924
22925        /**
22926         * Point used to compute visible regions.
22927         */
22928        final Point mPoint = new Point();
22929
22930        /**
22931         * Used to track which View originated a requestLayout() call, used when
22932         * requestLayout() is called during layout.
22933         */
22934        View mViewRequestingLayout;
22935
22936        /**
22937         * Used to track views that need (at least) a partial relayout at their current size
22938         * during the next traversal.
22939         */
22940        List<View> mPartialLayoutViews = new ArrayList<>();
22941
22942        /**
22943         * Swapped with mPartialLayoutViews during layout to avoid concurrent
22944         * modification. Lazily assigned during ViewRootImpl layout.
22945         */
22946        List<View> mEmptyPartialLayoutViews;
22947
22948        /**
22949         * Used to track the identity of the current drag operation.
22950         */
22951        IBinder mDragToken;
22952
22953        /**
22954         * The drag shadow surface for the current drag operation.
22955         */
22956        public Surface mDragSurface;
22957
22958        /**
22959         * Creates a new set of attachment information with the specified
22960         * events handler and thread.
22961         *
22962         * @param handler the events handler the view must use
22963         */
22964        AttachInfo(IWindowSession session, IWindow window, Display display,
22965                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
22966            mSession = session;
22967            mWindow = window;
22968            mWindowToken = window.asBinder();
22969            mDisplay = display;
22970            mViewRootImpl = viewRootImpl;
22971            mHandler = handler;
22972            mRootCallbacks = effectPlayer;
22973        }
22974    }
22975
22976    /**
22977     * <p>ScrollabilityCache holds various fields used by a View when scrolling
22978     * is supported. This avoids keeping too many unused fields in most
22979     * instances of View.</p>
22980     */
22981    private static class ScrollabilityCache implements Runnable {
22982
22983        /**
22984         * Scrollbars are not visible
22985         */
22986        public static final int OFF = 0;
22987
22988        /**
22989         * Scrollbars are visible
22990         */
22991        public static final int ON = 1;
22992
22993        /**
22994         * Scrollbars are fading away
22995         */
22996        public static final int FADING = 2;
22997
22998        public boolean fadeScrollBars;
22999
23000        public int fadingEdgeLength;
23001        public int scrollBarDefaultDelayBeforeFade;
23002        public int scrollBarFadeDuration;
23003
23004        public int scrollBarSize;
23005        public ScrollBarDrawable scrollBar;
23006        public float[] interpolatorValues;
23007        public View host;
23008
23009        public final Paint paint;
23010        public final Matrix matrix;
23011        public Shader shader;
23012
23013        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23014
23015        private static final float[] OPAQUE = { 255 };
23016        private static final float[] TRANSPARENT = { 0.0f };
23017
23018        /**
23019         * When fading should start. This time moves into the future every time
23020         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23021         */
23022        public long fadeStartTime;
23023
23024
23025        /**
23026         * The current state of the scrollbars: ON, OFF, or FADING
23027         */
23028        public int state = OFF;
23029
23030        private int mLastColor;
23031
23032        public final Rect mScrollBarBounds = new Rect();
23033
23034        public static final int NOT_DRAGGING = 0;
23035        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23036        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23037        public int mScrollBarDraggingState = NOT_DRAGGING;
23038
23039        public float mScrollBarDraggingPos = 0;
23040
23041        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23042            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23043            scrollBarSize = configuration.getScaledScrollBarSize();
23044            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23045            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23046
23047            paint = new Paint();
23048            matrix = new Matrix();
23049            // use use a height of 1, and then wack the matrix each time we
23050            // actually use it.
23051            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23052            paint.setShader(shader);
23053            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23054
23055            this.host = host;
23056        }
23057
23058        public void setFadeColor(int color) {
23059            if (color != mLastColor) {
23060                mLastColor = color;
23061
23062                if (color != 0) {
23063                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23064                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23065                    paint.setShader(shader);
23066                    // Restore the default transfer mode (src_over)
23067                    paint.setXfermode(null);
23068                } else {
23069                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23070                    paint.setShader(shader);
23071                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23072                }
23073            }
23074        }
23075
23076        public void run() {
23077            long now = AnimationUtils.currentAnimationTimeMillis();
23078            if (now >= fadeStartTime) {
23079
23080                // the animation fades the scrollbars out by changing
23081                // the opacity (alpha) from fully opaque to fully
23082                // transparent
23083                int nextFrame = (int) now;
23084                int framesCount = 0;
23085
23086                Interpolator interpolator = scrollBarInterpolator;
23087
23088                // Start opaque
23089                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23090
23091                // End transparent
23092                nextFrame += scrollBarFadeDuration;
23093                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23094
23095                state = FADING;
23096
23097                // Kick off the fade animation
23098                host.invalidate(true);
23099            }
23100        }
23101    }
23102
23103    /**
23104     * Resuable callback for sending
23105     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23106     */
23107    private class SendViewScrolledAccessibilityEvent implements Runnable {
23108        public volatile boolean mIsPending;
23109
23110        public void run() {
23111            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23112            mIsPending = false;
23113        }
23114    }
23115
23116    /**
23117     * <p>
23118     * This class represents a delegate that can be registered in a {@link View}
23119     * to enhance accessibility support via composition rather via inheritance.
23120     * It is specifically targeted to widget developers that extend basic View
23121     * classes i.e. classes in package android.view, that would like their
23122     * applications to be backwards compatible.
23123     * </p>
23124     * <div class="special reference">
23125     * <h3>Developer Guides</h3>
23126     * <p>For more information about making applications accessible, read the
23127     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23128     * developer guide.</p>
23129     * </div>
23130     * <p>
23131     * A scenario in which a developer would like to use an accessibility delegate
23132     * is overriding a method introduced in a later API version then the minimal API
23133     * version supported by the application. For example, the method
23134     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23135     * in API version 4 when the accessibility APIs were first introduced. If a
23136     * developer would like his application to run on API version 4 devices (assuming
23137     * all other APIs used by the application are version 4 or lower) and take advantage
23138     * of this method, instead of overriding the method which would break the application's
23139     * backwards compatibility, he can override the corresponding method in this
23140     * delegate and register the delegate in the target View if the API version of
23141     * the system is high enough i.e. the API version is same or higher to the API
23142     * version that introduced
23143     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23144     * </p>
23145     * <p>
23146     * Here is an example implementation:
23147     * </p>
23148     * <code><pre><p>
23149     * if (Build.VERSION.SDK_INT >= 14) {
23150     *     // If the API version is equal of higher than the version in
23151     *     // which onInitializeAccessibilityNodeInfo was introduced we
23152     *     // register a delegate with a customized implementation.
23153     *     View view = findViewById(R.id.view_id);
23154     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23155     *         public void onInitializeAccessibilityNodeInfo(View host,
23156     *                 AccessibilityNodeInfo info) {
23157     *             // Let the default implementation populate the info.
23158     *             super.onInitializeAccessibilityNodeInfo(host, info);
23159     *             // Set some other information.
23160     *             info.setEnabled(host.isEnabled());
23161     *         }
23162     *     });
23163     * }
23164     * </code></pre></p>
23165     * <p>
23166     * This delegate contains methods that correspond to the accessibility methods
23167     * in View. If a delegate has been specified the implementation in View hands
23168     * off handling to the corresponding method in this delegate. The default
23169     * implementation the delegate methods behaves exactly as the corresponding
23170     * method in View for the case of no accessibility delegate been set. Hence,
23171     * to customize the behavior of a View method, clients can override only the
23172     * corresponding delegate method without altering the behavior of the rest
23173     * accessibility related methods of the host view.
23174     * </p>
23175     * <p>
23176     * <strong>Note:</strong> On platform versions prior to
23177     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23178     * views in the {@code android.widget.*} package are called <i>before</i>
23179     * host methods. This prevents certain properties such as class name from
23180     * being modified by overriding
23181     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23182     * as any changes will be overwritten by the host class.
23183     * <p>
23184     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23185     * methods are called <i>after</i> host methods, which all properties to be
23186     * modified without being overwritten by the host class.
23187     */
23188    public static class AccessibilityDelegate {
23189
23190        /**
23191         * Sends an accessibility event of the given type. If accessibility is not
23192         * enabled this method has no effect.
23193         * <p>
23194         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23195         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23196         * been set.
23197         * </p>
23198         *
23199         * @param host The View hosting the delegate.
23200         * @param eventType The type of the event to send.
23201         *
23202         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23203         */
23204        public void sendAccessibilityEvent(View host, int eventType) {
23205            host.sendAccessibilityEventInternal(eventType);
23206        }
23207
23208        /**
23209         * Performs the specified accessibility action on the view. For
23210         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23211         * <p>
23212         * The default implementation behaves as
23213         * {@link View#performAccessibilityAction(int, Bundle)
23214         *  View#performAccessibilityAction(int, Bundle)} for the case of
23215         *  no accessibility delegate been set.
23216         * </p>
23217         *
23218         * @param action The action to perform.
23219         * @return Whether the action was performed.
23220         *
23221         * @see View#performAccessibilityAction(int, Bundle)
23222         *      View#performAccessibilityAction(int, Bundle)
23223         */
23224        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23225            return host.performAccessibilityActionInternal(action, args);
23226        }
23227
23228        /**
23229         * Sends an accessibility event. This method behaves exactly as
23230         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23231         * empty {@link AccessibilityEvent} and does not perform a check whether
23232         * accessibility is enabled.
23233         * <p>
23234         * The default implementation behaves as
23235         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23236         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23237         * the case of no accessibility delegate been set.
23238         * </p>
23239         *
23240         * @param host The View hosting the delegate.
23241         * @param event The event to send.
23242         *
23243         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23244         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23245         */
23246        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23247            host.sendAccessibilityEventUncheckedInternal(event);
23248        }
23249
23250        /**
23251         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23252         * to its children for adding their text content to the event.
23253         * <p>
23254         * The default implementation behaves as
23255         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23256         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23257         * the case of no accessibility delegate been set.
23258         * </p>
23259         *
23260         * @param host The View hosting the delegate.
23261         * @param event The event.
23262         * @return True if the event population was completed.
23263         *
23264         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23265         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23266         */
23267        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23268            return host.dispatchPopulateAccessibilityEventInternal(event);
23269        }
23270
23271        /**
23272         * Gives a chance to the host View to populate the accessibility event with its
23273         * text content.
23274         * <p>
23275         * The default implementation behaves as
23276         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23277         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23278         * the case of no accessibility delegate been set.
23279         * </p>
23280         *
23281         * @param host The View hosting the delegate.
23282         * @param event The accessibility event which to populate.
23283         *
23284         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23285         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23286         */
23287        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23288            host.onPopulateAccessibilityEventInternal(event);
23289        }
23290
23291        /**
23292         * Initializes an {@link AccessibilityEvent} with information about the
23293         * the host View which is the event source.
23294         * <p>
23295         * The default implementation behaves as
23296         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23297         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23298         * the case of no accessibility delegate been set.
23299         * </p>
23300         *
23301         * @param host The View hosting the delegate.
23302         * @param event The event to initialize.
23303         *
23304         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23305         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23306         */
23307        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23308            host.onInitializeAccessibilityEventInternal(event);
23309        }
23310
23311        /**
23312         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23313         * <p>
23314         * The default implementation behaves as
23315         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23316         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23317         * the case of no accessibility delegate been set.
23318         * </p>
23319         *
23320         * @param host The View hosting the delegate.
23321         * @param info The instance to initialize.
23322         *
23323         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23324         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23325         */
23326        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23327            host.onInitializeAccessibilityNodeInfoInternal(info);
23328        }
23329
23330        /**
23331         * Called when a child of the host View has requested sending an
23332         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23333         * to augment the event.
23334         * <p>
23335         * The default implementation behaves as
23336         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23337         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23338         * the case of no accessibility delegate been set.
23339         * </p>
23340         *
23341         * @param host The View hosting the delegate.
23342         * @param child The child which requests sending the event.
23343         * @param event The event to be sent.
23344         * @return True if the event should be sent
23345         *
23346         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23347         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23348         */
23349        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23350                AccessibilityEvent event) {
23351            return host.onRequestSendAccessibilityEventInternal(child, event);
23352        }
23353
23354        /**
23355         * Gets the provider for managing a virtual view hierarchy rooted at this View
23356         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23357         * that explore the window content.
23358         * <p>
23359         * The default implementation behaves as
23360         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23361         * the case of no accessibility delegate been set.
23362         * </p>
23363         *
23364         * @return The provider.
23365         *
23366         * @see AccessibilityNodeProvider
23367         */
23368        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23369            return null;
23370        }
23371
23372        /**
23373         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23374         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23375         * This method is responsible for obtaining an accessibility node info from a
23376         * pool of reusable instances and calling
23377         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23378         * view to initialize the former.
23379         * <p>
23380         * <strong>Note:</strong> The client is responsible for recycling the obtained
23381         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23382         * creation.
23383         * </p>
23384         * <p>
23385         * The default implementation behaves as
23386         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23387         * the case of no accessibility delegate been set.
23388         * </p>
23389         * @return A populated {@link AccessibilityNodeInfo}.
23390         *
23391         * @see AccessibilityNodeInfo
23392         *
23393         * @hide
23394         */
23395        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23396            return host.createAccessibilityNodeInfoInternal();
23397        }
23398    }
23399
23400    private class MatchIdPredicate implements Predicate<View> {
23401        public int mId;
23402
23403        @Override
23404        public boolean apply(View view) {
23405            return (view.mID == mId);
23406        }
23407    }
23408
23409    private class MatchLabelForPredicate implements Predicate<View> {
23410        private int mLabeledId;
23411
23412        @Override
23413        public boolean apply(View view) {
23414            return (view.mLabelForId == mLabeledId);
23415        }
23416    }
23417
23418    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23419        private int mChangeTypes = 0;
23420        private boolean mPosted;
23421        private boolean mPostedWithDelay;
23422        private long mLastEventTimeMillis;
23423
23424        @Override
23425        public void run() {
23426            mPosted = false;
23427            mPostedWithDelay = false;
23428            mLastEventTimeMillis = SystemClock.uptimeMillis();
23429            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23430                final AccessibilityEvent event = AccessibilityEvent.obtain();
23431                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23432                event.setContentChangeTypes(mChangeTypes);
23433                sendAccessibilityEventUnchecked(event);
23434            }
23435            mChangeTypes = 0;
23436        }
23437
23438        public void runOrPost(int changeType) {
23439            mChangeTypes |= changeType;
23440
23441            // If this is a live region or the child of a live region, collect
23442            // all events from this frame and send them on the next frame.
23443            if (inLiveRegion()) {
23444                // If we're already posted with a delay, remove that.
23445                if (mPostedWithDelay) {
23446                    removeCallbacks(this);
23447                    mPostedWithDelay = false;
23448                }
23449                // Only post if we're not already posted.
23450                if (!mPosted) {
23451                    post(this);
23452                    mPosted = true;
23453                }
23454                return;
23455            }
23456
23457            if (mPosted) {
23458                return;
23459            }
23460
23461            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23462            final long minEventIntevalMillis =
23463                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23464            if (timeSinceLastMillis >= minEventIntevalMillis) {
23465                removeCallbacks(this);
23466                run();
23467            } else {
23468                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23469                mPostedWithDelay = true;
23470            }
23471        }
23472    }
23473
23474    private boolean inLiveRegion() {
23475        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23476            return true;
23477        }
23478
23479        ViewParent parent = getParent();
23480        while (parent instanceof View) {
23481            if (((View) parent).getAccessibilityLiveRegion()
23482                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23483                return true;
23484            }
23485            parent = parent.getParent();
23486        }
23487
23488        return false;
23489    }
23490
23491    /**
23492     * Dump all private flags in readable format, useful for documentation and
23493     * sanity checking.
23494     */
23495    private static void dumpFlags() {
23496        final HashMap<String, String> found = Maps.newHashMap();
23497        try {
23498            for (Field field : View.class.getDeclaredFields()) {
23499                final int modifiers = field.getModifiers();
23500                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23501                    if (field.getType().equals(int.class)) {
23502                        final int value = field.getInt(null);
23503                        dumpFlag(found, field.getName(), value);
23504                    } else if (field.getType().equals(int[].class)) {
23505                        final int[] values = (int[]) field.get(null);
23506                        for (int i = 0; i < values.length; i++) {
23507                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23508                        }
23509                    }
23510                }
23511            }
23512        } catch (IllegalAccessException e) {
23513            throw new RuntimeException(e);
23514        }
23515
23516        final ArrayList<String> keys = Lists.newArrayList();
23517        keys.addAll(found.keySet());
23518        Collections.sort(keys);
23519        for (String key : keys) {
23520            Log.d(VIEW_LOG_TAG, found.get(key));
23521        }
23522    }
23523
23524    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23525        // Sort flags by prefix, then by bits, always keeping unique keys
23526        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23527        final int prefix = name.indexOf('_');
23528        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23529        final String output = bits + " " + name;
23530        found.put(key, output);
23531    }
23532
23533    /** {@hide} */
23534    public void encode(@NonNull ViewHierarchyEncoder stream) {
23535        stream.beginObject(this);
23536        encodeProperties(stream);
23537        stream.endObject();
23538    }
23539
23540    /** {@hide} */
23541    @CallSuper
23542    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23543        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23544        if (resolveId instanceof String) {
23545            stream.addProperty("id", (String) resolveId);
23546        } else {
23547            stream.addProperty("id", mID);
23548        }
23549
23550        stream.addProperty("misc:transformation.alpha",
23551                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23552        stream.addProperty("misc:transitionName", getTransitionName());
23553
23554        // layout
23555        stream.addProperty("layout:left", mLeft);
23556        stream.addProperty("layout:right", mRight);
23557        stream.addProperty("layout:top", mTop);
23558        stream.addProperty("layout:bottom", mBottom);
23559        stream.addProperty("layout:width", getWidth());
23560        stream.addProperty("layout:height", getHeight());
23561        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23562        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23563        stream.addProperty("layout:hasTransientState", hasTransientState());
23564        stream.addProperty("layout:baseline", getBaseline());
23565
23566        // layout params
23567        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23568        if (layoutParams != null) {
23569            stream.addPropertyKey("layoutParams");
23570            layoutParams.encode(stream);
23571        }
23572
23573        // scrolling
23574        stream.addProperty("scrolling:scrollX", mScrollX);
23575        stream.addProperty("scrolling:scrollY", mScrollY);
23576
23577        // padding
23578        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23579        stream.addProperty("padding:paddingRight", mPaddingRight);
23580        stream.addProperty("padding:paddingTop", mPaddingTop);
23581        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23582        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23583        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23584        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23585        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23586        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23587
23588        // measurement
23589        stream.addProperty("measurement:minHeight", mMinHeight);
23590        stream.addProperty("measurement:minWidth", mMinWidth);
23591        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23592        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23593
23594        // drawing
23595        stream.addProperty("drawing:elevation", getElevation());
23596        stream.addProperty("drawing:translationX", getTranslationX());
23597        stream.addProperty("drawing:translationY", getTranslationY());
23598        stream.addProperty("drawing:translationZ", getTranslationZ());
23599        stream.addProperty("drawing:rotation", getRotation());
23600        stream.addProperty("drawing:rotationX", getRotationX());
23601        stream.addProperty("drawing:rotationY", getRotationY());
23602        stream.addProperty("drawing:scaleX", getScaleX());
23603        stream.addProperty("drawing:scaleY", getScaleY());
23604        stream.addProperty("drawing:pivotX", getPivotX());
23605        stream.addProperty("drawing:pivotY", getPivotY());
23606        stream.addProperty("drawing:opaque", isOpaque());
23607        stream.addProperty("drawing:alpha", getAlpha());
23608        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23609        stream.addProperty("drawing:shadow", hasShadow());
23610        stream.addProperty("drawing:solidColor", getSolidColor());
23611        stream.addProperty("drawing:layerType", mLayerType);
23612        stream.addProperty("drawing:willNotDraw", willNotDraw());
23613        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23614        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23615        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23616        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23617
23618        // focus
23619        stream.addProperty("focus:hasFocus", hasFocus());
23620        stream.addProperty("focus:isFocused", isFocused());
23621        stream.addProperty("focus:isFocusable", isFocusable());
23622        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23623
23624        stream.addProperty("misc:clickable", isClickable());
23625        stream.addProperty("misc:pressed", isPressed());
23626        stream.addProperty("misc:selected", isSelected());
23627        stream.addProperty("misc:touchMode", isInTouchMode());
23628        stream.addProperty("misc:hovered", isHovered());
23629        stream.addProperty("misc:activated", isActivated());
23630
23631        stream.addProperty("misc:visibility", getVisibility());
23632        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23633        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23634
23635        stream.addProperty("misc:enabled", isEnabled());
23636        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23637        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23638
23639        // theme attributes
23640        Resources.Theme theme = getContext().getTheme();
23641        if (theme != null) {
23642            stream.addPropertyKey("theme");
23643            theme.encode(stream);
23644        }
23645
23646        // view attribute information
23647        int n = mAttributes != null ? mAttributes.length : 0;
23648        stream.addProperty("meta:__attrCount__", n/2);
23649        for (int i = 0; i < n; i += 2) {
23650            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23651        }
23652
23653        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23654
23655        // text
23656        stream.addProperty("text:textDirection", getTextDirection());
23657        stream.addProperty("text:textAlignment", getTextAlignment());
23658
23659        // accessibility
23660        CharSequence contentDescription = getContentDescription();
23661        stream.addProperty("accessibility:contentDescription",
23662                contentDescription == null ? "" : contentDescription.toString());
23663        stream.addProperty("accessibility:labelFor", getLabelFor());
23664        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23665    }
23666}
23667