View.java revision 0e95bc4fb2c9255223d1a27b1727416d81e4835c
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.LayoutRes;
28import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.Size;
31import android.annotation.UiThread;
32import android.content.ClipData;
33import android.content.Context;
34import android.content.ContextWrapper;
35import android.content.Intent;
36import android.content.res.ColorStateList;
37import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.content.res.TypedArray;
40import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Insets;
43import android.graphics.Interpolator;
44import android.graphics.LinearGradient;
45import android.graphics.Matrix;
46import android.graphics.Outline;
47import android.graphics.Paint;
48import android.graphics.PixelFormat;
49import android.graphics.Point;
50import android.graphics.PorterDuff;
51import android.graphics.PorterDuffXfermode;
52import android.graphics.Rect;
53import android.graphics.RectF;
54import android.graphics.Region;
55import android.graphics.Shader;
56import android.graphics.drawable.ColorDrawable;
57import android.graphics.drawable.Drawable;
58import android.hardware.display.DisplayManagerGlobal;
59import android.os.Build;
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.TextSegmentIterator;
84import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
85import android.view.AccessibilityIterators.WordTextSegmentIterator;
86import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
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;
102
103import static android.os.Build.VERSION_CODES.*;
104import static java.lang.Math.max;
105
106import com.android.internal.R;
107import com.android.internal.util.Predicate;
108import com.android.internal.view.menu.MenuBuilder;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.annotation.Retention;
113import java.lang.annotation.RetentionPolicy;
114import java.lang.ref.WeakReference;
115import java.lang.reflect.Field;
116import java.lang.reflect.InvocationTargetException;
117import java.lang.reflect.Method;
118import java.lang.reflect.Modifier;
119import java.util.ArrayList;
120import java.util.Arrays;
121import java.util.Collections;
122import java.util.HashMap;
123import java.util.List;
124import java.util.Locale;
125import java.util.Map;
126import java.util.concurrent.CopyOnWriteArrayList;
127import java.util.concurrent.atomic.AtomicInteger;
128
129/**
130 * <p>
131 * This class represents the basic building block for user interface components. A View
132 * occupies a rectangular area on the screen and is responsible for drawing and
133 * event handling. View is the base class for <em>widgets</em>, which are
134 * used to create interactive UI components (buttons, text fields, etc.). The
135 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
136 * are invisible containers that hold other Views (or other ViewGroups) and define
137 * their layout properties.
138 * </p>
139 *
140 * <div class="special reference">
141 * <h3>Developer Guides</h3>
142 * <p>For information about using this class to develop your application's user interface,
143 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
144 * </div>
145 *
146 * <a name="Using"></a>
147 * <h3>Using Views</h3>
148 * <p>
149 * All of the views in a window are arranged in a single tree. You can add views
150 * either from code or by specifying a tree of views in one or more XML layout
151 * files. There are many specialized subclasses of views that act as controls or
152 * are capable of displaying text, images, or other content.
153 * </p>
154 * <p>
155 * Once you have created a tree of views, there are typically a few types of
156 * common operations you may wish to perform:
157 * <ul>
158 * <li><strong>Set properties:</strong> for example setting the text of a
159 * {@link android.widget.TextView}. The available properties and the methods
160 * that set them will vary among the different subclasses of views. Note that
161 * properties that are known at build time can be set in the XML layout
162 * files.</li>
163 * <li><strong>Set focus:</strong> The framework will handled moving focus in
164 * response to user input. To force focus to a specific view, call
165 * {@link #requestFocus}.</li>
166 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
167 * that will be notified when something interesting happens to the view. For
168 * example, all views will let you set a listener to be notified when the view
169 * gains or loses focus. You can register such a listener using
170 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
171 * Other view subclasses offer more specialized listeners. For example, a Button
172 * exposes a listener to notify clients when the button is clicked.</li>
173 * <li><strong>Set visibility:</strong> You can hide or show views using
174 * {@link #setVisibility(int)}.</li>
175 * </ul>
176 * </p>
177 * <p><em>
178 * Note: The Android framework is responsible for measuring, laying out and
179 * drawing views. You should not call methods that perform these actions on
180 * views yourself unless you are actually implementing a
181 * {@link android.view.ViewGroup}.
182 * </em></p>
183 *
184 * <a name="Lifecycle"></a>
185 * <h3>Implementing a Custom View</h3>
186 *
187 * <p>
188 * To implement a custom view, you will usually begin by providing overrides for
189 * some of the standard methods that the framework calls on all views. You do
190 * not need to override all of these methods. In fact, you can start by just
191 * overriding {@link #onDraw(android.graphics.Canvas)}.
192 * <table border="2" width="85%" align="center" cellpadding="5">
193 *     <thead>
194 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
195 *     </thead>
196 *
197 *     <tbody>
198 *     <tr>
199 *         <td rowspan="2">Creation</td>
200 *         <td>Constructors</td>
201 *         <td>There is a form of the constructor that are called when the view
202 *         is created from code and a form that is called when the view is
203 *         inflated from a layout file. The second form should parse and apply
204 *         any attributes defined in the layout file.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onFinishInflate()}</code></td>
209 *         <td>Called after a view and all of its children has been inflated
210 *         from XML.</td>
211 *     </tr>
212 *
213 *     <tr>
214 *         <td rowspan="3">Layout</td>
215 *         <td><code>{@link #onMeasure(int, int)}</code></td>
216 *         <td>Called to determine the size requirements for this view and all
217 *         of its children.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
222 *         <td>Called when this view should assign a size and position to all
223 *         of its children.
224 *         </td>
225 *     </tr>
226 *     <tr>
227 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
228 *         <td>Called when the size of this view has changed.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td>Drawing</td>
234 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
235 *         <td>Called when the view should render its content.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="4">Event processing</td>
241 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
242 *         <td>Called when a new hardware key event occurs.
243 *         </td>
244 *     </tr>
245 *     <tr>
246 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
247 *         <td>Called when a hardware key up event occurs.
248 *         </td>
249 *     </tr>
250 *     <tr>
251 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
252 *         <td>Called when a trackball motion event occurs.
253 *         </td>
254 *     </tr>
255 *     <tr>
256 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
257 *         <td>Called when a touch screen motion event occurs.
258 *         </td>
259 *     </tr>
260 *
261 *     <tr>
262 *         <td rowspan="2">Focus</td>
263 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
264 *         <td>Called when the view gains or loses focus.
265 *         </td>
266 *     </tr>
267 *
268 *     <tr>
269 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
270 *         <td>Called when the window containing the view gains or loses focus.
271 *         </td>
272 *     </tr>
273 *
274 *     <tr>
275 *         <td rowspan="3">Attaching</td>
276 *         <td><code>{@link #onAttachedToWindow()}</code></td>
277 *         <td>Called when the view is attached to a window.
278 *         </td>
279 *     </tr>
280 *
281 *     <tr>
282 *         <td><code>{@link #onDetachedFromWindow}</code></td>
283 *         <td>Called when the view is detached from its window.
284 *         </td>
285 *     </tr>
286 *
287 *     <tr>
288 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
289 *         <td>Called when the visibility of the window containing the view
290 *         has changed.
291 *         </td>
292 *     </tr>
293 *     </tbody>
294 *
295 * </table>
296 * </p>
297 *
298 * <a name="IDs"></a>
299 * <h3>IDs</h3>
300 * Views may have an integer id associated with them. These ids are typically
301 * assigned in the layout XML files, and are used to find specific views within
302 * the view tree. A common pattern is to:
303 * <ul>
304 * <li>Define a Button in the layout file and assign it a unique ID.
305 * <pre>
306 * &lt;Button
307 *     android:id="@+id/my_button"
308 *     android:layout_width="wrap_content"
309 *     android:layout_height="wrap_content"
310 *     android:text="@string/my_button_text"/&gt;
311 * </pre></li>
312 * <li>From the onCreate method of an Activity, find the Button
313 * <pre class="prettyprint">
314 *      Button myButton = (Button) findViewById(R.id.my_button);
315 * </pre></li>
316 * </ul>
317 * <p>
318 * View IDs need not be unique throughout the tree, but it is good practice to
319 * ensure that they are at least unique within the part of the tree you are
320 * searching.
321 * </p>
322 *
323 * <a name="Position"></a>
324 * <h3>Position</h3>
325 * <p>
326 * The geometry of a view is that of a rectangle. A view has a location,
327 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
328 * two dimensions, expressed as a width and a height. The unit for location
329 * and dimensions is the pixel.
330 * </p>
331 *
332 * <p>
333 * It is possible to retrieve the location of a view by invoking the methods
334 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
335 * coordinate of the rectangle representing the view. The latter returns the
336 * top, or Y, coordinate of the rectangle representing the view. These methods
337 * both return the location of the view relative to its parent. For instance,
338 * when getLeft() returns 20, that means the view is located 20 pixels to the
339 * right of the left edge of its direct parent.
340 * </p>
341 *
342 * <p>
343 * In addition, several convenience methods are offered to avoid unnecessary
344 * computations, namely {@link #getRight()} and {@link #getBottom()}.
345 * These methods return the coordinates of the right and bottom edges of the
346 * rectangle representing the view. For instance, calling {@link #getRight()}
347 * is similar to the following computation: <code>getLeft() + getWidth()</code>
348 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
349 * </p>
350 *
351 * <a name="SizePaddingMargins"></a>
352 * <h3>Size, padding and margins</h3>
353 * <p>
354 * The size of a view is expressed with a width and a height. A view actually
355 * possess two pairs of width and height values.
356 * </p>
357 *
358 * <p>
359 * The first pair is known as <em>measured width</em> and
360 * <em>measured height</em>. These dimensions define how big a view wants to be
361 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
362 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
363 * and {@link #getMeasuredHeight()}.
364 * </p>
365 *
366 * <p>
367 * The second pair is simply known as <em>width</em> and <em>height</em>, or
368 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
369 * dimensions define the actual size of the view on screen, at drawing time and
370 * after layout. These values may, but do not have to, be different from the
371 * measured width and height. The width and height can be obtained by calling
372 * {@link #getWidth()} and {@link #getHeight()}.
373 * </p>
374 *
375 * <p>
376 * To measure its dimensions, a view takes into account its padding. The padding
377 * is expressed in pixels for the left, top, right and bottom parts of the view.
378 * Padding can be used to offset the content of the view by a specific amount of
379 * pixels. For instance, a left padding of 2 will push the view's content by
380 * 2 pixels to the right of the left edge. Padding can be set using the
381 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
382 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
383 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
384 * {@link #getPaddingEnd()}.
385 * </p>
386 *
387 * <p>
388 * Even though a view can define a padding, it does not provide any support for
389 * margins. However, view groups provide such a support. Refer to
390 * {@link android.view.ViewGroup} and
391 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
392 * </p>
393 *
394 * <a name="Layout"></a>
395 * <h3>Layout</h3>
396 * <p>
397 * Layout is a two pass process: a measure pass and a layout pass. The measuring
398 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
399 * of the view tree. Each view pushes dimension specifications down the tree
400 * during the recursion. At the end of the measure pass, every view has stored
401 * its measurements. The second pass happens in
402 * {@link #layout(int,int,int,int)} and is also top-down. During
403 * this pass each parent is responsible for positioning all of its children
404 * using the sizes computed in the measure pass.
405 * </p>
406 *
407 * <p>
408 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
409 * {@link #getMeasuredHeight()} values must be set, along with those for all of
410 * that view's descendants. A view's measured width and measured height values
411 * must respect the constraints imposed by the view's parents. This guarantees
412 * that at the end of the measure pass, all parents accept all of their
413 * children's measurements. A parent view may call measure() more than once on
414 * its children. For example, the parent may measure each child once with
415 * unspecified dimensions to find out how big they want to be, then call
416 * measure() on them again with actual numbers if the sum of all the children's
417 * unconstrained sizes is too big or too small.
418 * </p>
419 *
420 * <p>
421 * The measure pass uses two classes to communicate dimensions. The
422 * {@link MeasureSpec} class is used by views to tell their parents how they
423 * want to be measured and positioned. The base LayoutParams class just
424 * describes how big the view wants to be for both width and height. For each
425 * dimension, it can specify one of:
426 * <ul>
427 * <li> an exact number
428 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
429 * (minus padding)
430 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
431 * enclose its content (plus padding).
432 * </ul>
433 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
434 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
435 * an X and Y value.
436 * </p>
437 *
438 * <p>
439 * MeasureSpecs are used to push requirements down the tree from parent to
440 * child. A MeasureSpec can be in one of three modes:
441 * <ul>
442 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
443 * of a child view. For example, a LinearLayout may call measure() on its child
444 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
445 * tall the child view wants to be given a width of 240 pixels.
446 * <li>EXACTLY: This is used by the parent to impose an exact size on the
447 * child. The child must use this size, and guarantee that all of its
448 * descendants will fit within this size.
449 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
450 * child. The child must guarantee that it and all of its descendants will fit
451 * within this size.
452 * </ul>
453 * </p>
454 *
455 * <p>
456 * To initiate a layout, call {@link #requestLayout}. This method is typically
457 * called by a view on itself when it believes that is can no longer fit within
458 * its current bounds.
459 * </p>
460 *
461 * <a name="Drawing"></a>
462 * <h3>Drawing</h3>
463 * <p>
464 * Drawing is handled by walking the tree and recording the drawing commands of
465 * any View that needs to update. After this, the drawing commands of the
466 * entire tree are issued to screen, clipped to the newly damaged area.
467 * </p>
468 *
469 * <p>
470 * The tree is largely recorded and drawn in order, with parents drawn before
471 * (i.e., behind) their children, with siblings drawn in the order they appear
472 * in the tree. If you set a background drawable for a View, then the View will
473 * draw it before calling back to its <code>onDraw()</code> method. The child
474 * drawing order can be overridden with
475 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
476 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
477 * </p>
478 *
479 * <p>
480 * To force a view to draw, call {@link #invalidate()}.
481 * </p>
482 *
483 * <a name="EventHandlingThreading"></a>
484 * <h3>Event Handling and Threading</h3>
485 * <p>
486 * The basic cycle of a view is as follows:
487 * <ol>
488 * <li>An event comes in and is dispatched to the appropriate view. The view
489 * handles the event and notifies any listeners.</li>
490 * <li>If in the course of processing the event, the view's bounds may need
491 * to be changed, the view will call {@link #requestLayout()}.</li>
492 * <li>Similarly, if in the course of processing the event the view's appearance
493 * may need to be changed, the view will call {@link #invalidate()}.</li>
494 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
495 * the framework will take care of measuring, laying out, and drawing the tree
496 * as appropriate.</li>
497 * </ol>
498 * </p>
499 *
500 * <p><em>Note: The entire view tree is single threaded. You must always be on
501 * the UI thread when calling any method on any view.</em>
502 * If you are doing work on other threads and want to update the state of a view
503 * from that thread, you should use a {@link Handler}.
504 * </p>
505 *
506 * <a name="FocusHandling"></a>
507 * <h3>Focus Handling</h3>
508 * <p>
509 * The framework will handle routine focus movement in response to user input.
510 * This includes changing the focus as views are removed or hidden, or as new
511 * views become available. Views indicate their willingness to take focus
512 * through the {@link #isFocusable} method. To change whether a view can take
513 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
514 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
515 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
516 * </p>
517 * <p>
518 * Focus movement is based on an algorithm which finds the nearest neighbor in a
519 * given direction. In rare cases, the default algorithm may not match the
520 * intended behavior of the developer. In these situations, you can provide
521 * explicit overrides by using these XML attributes in the layout file:
522 * <pre>
523 * nextFocusDown
524 * nextFocusLeft
525 * nextFocusRight
526 * nextFocusUp
527 * </pre>
528 * </p>
529 *
530 *
531 * <p>
532 * To get a particular view to take focus, call {@link #requestFocus()}.
533 * </p>
534 *
535 * <a name="TouchMode"></a>
536 * <h3>Touch Mode</h3>
537 * <p>
538 * When a user is navigating a user interface via directional keys such as a D-pad, it is
539 * necessary to give focus to actionable items such as buttons so the user can see
540 * what will take input.  If the device has touch capabilities, however, and the user
541 * begins interacting with the interface by touching it, it is no longer necessary to
542 * always highlight, or give focus to, a particular view.  This motivates a mode
543 * for interaction named 'touch mode'.
544 * </p>
545 * <p>
546 * For a touch capable device, once the user touches the screen, the device
547 * will enter touch mode.  From this point onward, only views for which
548 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
549 * Other views that are touchable, like buttons, will not take focus when touched; they will
550 * only fire the on click listeners.
551 * </p>
552 * <p>
553 * Any time a user hits a directional key, such as a D-pad direction, the view device will
554 * exit touch mode, and find a view to take focus, so that the user may resume interacting
555 * with the user interface without touching the screen again.
556 * </p>
557 * <p>
558 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
559 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
560 * </p>
561 *
562 * <a name="Scrolling"></a>
563 * <h3>Scrolling</h3>
564 * <p>
565 * The framework provides basic support for views that wish to internally
566 * scroll their content. This includes keeping track of the X and Y scroll
567 * offset as well as mechanisms for drawing scrollbars. See
568 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
569 * {@link #awakenScrollBars()} for more details.
570 * </p>
571 *
572 * <a name="Tags"></a>
573 * <h3>Tags</h3>
574 * <p>
575 * Unlike IDs, tags are not used to identify views. Tags are essentially an
576 * extra piece of information that can be associated with a view. They are most
577 * often used as a convenience to store data related to views in the views
578 * themselves rather than by putting them in a separate structure.
579 * </p>
580 *
581 * <a name="Properties"></a>
582 * <h3>Properties</h3>
583 * <p>
584 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
585 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
586 * available both in the {@link Property} form as well as in similarly-named setter/getter
587 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
588 * be used to set persistent state associated with these rendering-related properties on the view.
589 * The properties and methods can also be used in conjunction with
590 * {@link android.animation.Animator Animator}-based animations, described more in the
591 * <a href="#Animation">Animation</a> section.
592 * </p>
593 *
594 * <a name="Animation"></a>
595 * <h3>Animation</h3>
596 * <p>
597 * Starting with Android 3.0, the preferred way of animating views is to use the
598 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
599 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
600 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
601 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
602 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
603 * makes animating these View properties particularly easy and efficient.
604 * </p>
605 * <p>
606 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
607 * You can attach an {@link Animation} object to a view using
608 * {@link #setAnimation(Animation)} or
609 * {@link #startAnimation(Animation)}. The animation can alter the scale,
610 * rotation, translation and alpha of a view over time. If the animation is
611 * attached to a view that has children, the animation will affect the entire
612 * subtree rooted by that node. When an animation is started, the framework will
613 * take care of redrawing the appropriate views until the animation completes.
614 * </p>
615 *
616 * <a name="Security"></a>
617 * <h3>Security</h3>
618 * <p>
619 * Sometimes it is essential that an application be able to verify that an action
620 * is being performed with the full knowledge and consent of the user, such as
621 * granting a permission request, making a purchase or clicking on an advertisement.
622 * Unfortunately, a malicious application could try to spoof the user into
623 * performing these actions, unaware, by concealing the intended purpose of the view.
624 * As a remedy, the framework offers a touch filtering mechanism that can be used to
625 * improve the security of views that provide access to sensitive functionality.
626 * </p><p>
627 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
628 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
629 * will discard touches that are received whenever the view's window is obscured by
630 * another visible window.  As a result, the view will not receive touches whenever a
631 * toast, dialog or other window appears above the view's window.
632 * </p><p>
633 * For more fine-grained control over security, consider overriding the
634 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
635 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
636 * </p>
637 *
638 * @attr ref android.R.styleable#View_alpha
639 * @attr ref android.R.styleable#View_background
640 * @attr ref android.R.styleable#View_clickable
641 * @attr ref android.R.styleable#View_contentDescription
642 * @attr ref android.R.styleable#View_drawingCacheQuality
643 * @attr ref android.R.styleable#View_duplicateParentState
644 * @attr ref android.R.styleable#View_id
645 * @attr ref android.R.styleable#View_requiresFadingEdge
646 * @attr ref android.R.styleable#View_fadeScrollbars
647 * @attr ref android.R.styleable#View_fadingEdgeLength
648 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
649 * @attr ref android.R.styleable#View_fitsSystemWindows
650 * @attr ref android.R.styleable#View_isScrollContainer
651 * @attr ref android.R.styleable#View_focusable
652 * @attr ref android.R.styleable#View_focusableInTouchMode
653 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
654 * @attr ref android.R.styleable#View_keepScreenOn
655 * @attr ref android.R.styleable#View_layerType
656 * @attr ref android.R.styleable#View_layoutDirection
657 * @attr ref android.R.styleable#View_longClickable
658 * @attr ref android.R.styleable#View_minHeight
659 * @attr ref android.R.styleable#View_minWidth
660 * @attr ref android.R.styleable#View_nextFocusDown
661 * @attr ref android.R.styleable#View_nextFocusLeft
662 * @attr ref android.R.styleable#View_nextFocusRight
663 * @attr ref android.R.styleable#View_nextFocusUp
664 * @attr ref android.R.styleable#View_onClick
665 * @attr ref android.R.styleable#View_padding
666 * @attr ref android.R.styleable#View_paddingBottom
667 * @attr ref android.R.styleable#View_paddingLeft
668 * @attr ref android.R.styleable#View_paddingRight
669 * @attr ref android.R.styleable#View_paddingTop
670 * @attr ref android.R.styleable#View_paddingStart
671 * @attr ref android.R.styleable#View_paddingEnd
672 * @attr ref android.R.styleable#View_saveEnabled
673 * @attr ref android.R.styleable#View_rotation
674 * @attr ref android.R.styleable#View_rotationX
675 * @attr ref android.R.styleable#View_rotationY
676 * @attr ref android.R.styleable#View_scaleX
677 * @attr ref android.R.styleable#View_scaleY
678 * @attr ref android.R.styleable#View_scrollX
679 * @attr ref android.R.styleable#View_scrollY
680 * @attr ref android.R.styleable#View_scrollbarSize
681 * @attr ref android.R.styleable#View_scrollbarStyle
682 * @attr ref android.R.styleable#View_scrollbars
683 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
684 * @attr ref android.R.styleable#View_scrollbarFadeDuration
685 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
686 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
687 * @attr ref android.R.styleable#View_scrollbarThumbVertical
688 * @attr ref android.R.styleable#View_scrollbarTrackVertical
689 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
690 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
691 * @attr ref android.R.styleable#View_stateListAnimator
692 * @attr ref android.R.styleable#View_transitionName
693 * @attr ref android.R.styleable#View_soundEffectsEnabled
694 * @attr ref android.R.styleable#View_tag
695 * @attr ref android.R.styleable#View_textAlignment
696 * @attr ref android.R.styleable#View_textDirection
697 * @attr ref android.R.styleable#View_transformPivotX
698 * @attr ref android.R.styleable#View_transformPivotY
699 * @attr ref android.R.styleable#View_translationX
700 * @attr ref android.R.styleable#View_translationY
701 * @attr ref android.R.styleable#View_translationZ
702 * @attr ref android.R.styleable#View_visibility
703 *
704 * @see android.view.ViewGroup
705 */
706@UiThread
707public class View implements Drawable.Callback, KeyEvent.Callback,
708        AccessibilityEventSource {
709    private static final boolean DBG = false;
710
711    /**
712     * The logging tag used by this class with android.util.Log.
713     */
714    protected static final String VIEW_LOG_TAG = "View";
715
716    /**
717     * When set to true, apps will draw debugging information about their layouts.
718     *
719     * @hide
720     */
721    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
722
723    /**
724     * When set to true, this view will save its attribute data.
725     *
726     * @hide
727     */
728    public static boolean mDebugViewAttributes = false;
729
730    /**
731     * Used to mark a View that has no ID.
732     */
733    public static final int NO_ID = -1;
734
735    /**
736     * Signals that compatibility booleans have been initialized according to
737     * target SDK versions.
738     */
739    private static boolean sCompatibilityDone = false;
740
741    /**
742     * Use the old (broken) way of building MeasureSpecs.
743     */
744    private static boolean sUseBrokenMakeMeasureSpec = false;
745
746    /**
747     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
748     */
749    static boolean sUseZeroUnspecifiedMeasureSpec = false;
750
751    /**
752     * Ignore any optimizations using the measure cache.
753     */
754    private static boolean sIgnoreMeasureCache = false;
755
756    /**
757     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
758     * calling setFlags.
759     */
760    private static final int NOT_FOCUSABLE = 0x00000000;
761
762    /**
763     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
764     * setFlags.
765     */
766    private static final int FOCUSABLE = 0x00000001;
767
768    /**
769     * Mask for use with setFlags indicating bits used for focus.
770     */
771    private static final int FOCUSABLE_MASK = 0x00000001;
772
773    /**
774     * This view will adjust its padding to fit sytem windows (e.g. status bar)
775     */
776    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
777
778    /** @hide */
779    @IntDef({VISIBLE, INVISIBLE, GONE})
780    @Retention(RetentionPolicy.SOURCE)
781    public @interface Visibility {}
782
783    /**
784     * This view is visible.
785     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
786     * android:visibility}.
787     */
788    public static final int VISIBLE = 0x00000000;
789
790    /**
791     * This view is invisible, but it still takes up space for layout purposes.
792     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
793     * android:visibility}.
794     */
795    public static final int INVISIBLE = 0x00000004;
796
797    /**
798     * This view is invisible, and it doesn't take any space for layout
799     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
800     * android:visibility}.
801     */
802    public static final int GONE = 0x00000008;
803
804    /**
805     * Mask for use with setFlags indicating bits used for visibility.
806     * {@hide}
807     */
808    static final int VISIBILITY_MASK = 0x0000000C;
809
810    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
811
812    /**
813     * This view is enabled. Interpretation varies by subclass.
814     * Use with ENABLED_MASK when calling setFlags.
815     * {@hide}
816     */
817    static final int ENABLED = 0x00000000;
818
819    /**
820     * This view is disabled. Interpretation varies by subclass.
821     * Use with ENABLED_MASK when calling setFlags.
822     * {@hide}
823     */
824    static final int DISABLED = 0x00000020;
825
826   /**
827    * Mask for use with setFlags indicating bits used for indicating whether
828    * this view is enabled
829    * {@hide}
830    */
831    static final int ENABLED_MASK = 0x00000020;
832
833    /**
834     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
835     * called and further optimizations will be performed. It is okay to have
836     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
837     * {@hide}
838     */
839    static final int WILL_NOT_DRAW = 0x00000080;
840
841    /**
842     * Mask for use with setFlags indicating bits used for indicating whether
843     * this view is will draw
844     * {@hide}
845     */
846    static final int DRAW_MASK = 0x00000080;
847
848    /**
849     * <p>This view doesn't show scrollbars.</p>
850     * {@hide}
851     */
852    static final int SCROLLBARS_NONE = 0x00000000;
853
854    /**
855     * <p>This view shows horizontal scrollbars.</p>
856     * {@hide}
857     */
858    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
859
860    /**
861     * <p>This view shows vertical scrollbars.</p>
862     * {@hide}
863     */
864    static final int SCROLLBARS_VERTICAL = 0x00000200;
865
866    /**
867     * <p>Mask for use with setFlags indicating bits used for indicating which
868     * scrollbars are enabled.</p>
869     * {@hide}
870     */
871    static final int SCROLLBARS_MASK = 0x00000300;
872
873    /**
874     * Indicates that the view should filter touches when its window is obscured.
875     * Refer to the class comments for more information about this security feature.
876     * {@hide}
877     */
878    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
879
880    /**
881     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
882     * that they are optional and should be skipped if the window has
883     * requested system UI flags that ignore those insets for layout.
884     */
885    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
886
887    /**
888     * <p>This view doesn't show fading edges.</p>
889     * {@hide}
890     */
891    static final int FADING_EDGE_NONE = 0x00000000;
892
893    /**
894     * <p>This view shows horizontal fading edges.</p>
895     * {@hide}
896     */
897    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
898
899    /**
900     * <p>This view shows vertical fading edges.</p>
901     * {@hide}
902     */
903    static final int FADING_EDGE_VERTICAL = 0x00002000;
904
905    /**
906     * <p>Mask for use with setFlags indicating bits used for indicating which
907     * fading edges are enabled.</p>
908     * {@hide}
909     */
910    static final int FADING_EDGE_MASK = 0x00003000;
911
912    /**
913     * <p>Indicates this view can be clicked. When clickable, a View reacts
914     * to clicks by notifying the OnClickListener.<p>
915     * {@hide}
916     */
917    static final int CLICKABLE = 0x00004000;
918
919    /**
920     * <p>Indicates this view is caching its drawing into a bitmap.</p>
921     * {@hide}
922     */
923    static final int DRAWING_CACHE_ENABLED = 0x00008000;
924
925    /**
926     * <p>Indicates that no icicle should be saved for this view.<p>
927     * {@hide}
928     */
929    static final int SAVE_DISABLED = 0x000010000;
930
931    /**
932     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
933     * property.</p>
934     * {@hide}
935     */
936    static final int SAVE_DISABLED_MASK = 0x000010000;
937
938    /**
939     * <p>Indicates that no drawing cache should ever be created for this view.<p>
940     * {@hide}
941     */
942    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
943
944    /**
945     * <p>Indicates this view can take / keep focus when int touch mode.</p>
946     * {@hide}
947     */
948    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
949
950    /** @hide */
951    @Retention(RetentionPolicy.SOURCE)
952    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
953    public @interface DrawingCacheQuality {}
954
955    /**
956     * <p>Enables low quality mode for the drawing cache.</p>
957     */
958    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
959
960    /**
961     * <p>Enables high quality mode for the drawing cache.</p>
962     */
963    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
964
965    /**
966     * <p>Enables automatic quality mode for the drawing cache.</p>
967     */
968    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
969
970    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
971            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
972    };
973
974    /**
975     * <p>Mask for use with setFlags indicating bits used for the cache
976     * quality property.</p>
977     * {@hide}
978     */
979    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
980
981    /**
982     * <p>
983     * Indicates this view can be long clicked. When long clickable, a View
984     * reacts to long clicks by notifying the OnLongClickListener or showing a
985     * context menu.
986     * </p>
987     * {@hide}
988     */
989    static final int LONG_CLICKABLE = 0x00200000;
990
991    /**
992     * <p>Indicates that this view gets its drawable states from its direct parent
993     * and ignores its original internal states.</p>
994     *
995     * @hide
996     */
997    static final int DUPLICATE_PARENT_STATE = 0x00400000;
998
999    /**
1000     * <p>
1001     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1002     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1003     * OnContextClickListener.
1004     * </p>
1005     * {@hide}
1006     */
1007    static final int CONTEXT_CLICKABLE = 0x00800000;
1008
1009
1010    /** @hide */
1011    @IntDef({
1012        SCROLLBARS_INSIDE_OVERLAY,
1013        SCROLLBARS_INSIDE_INSET,
1014        SCROLLBARS_OUTSIDE_OVERLAY,
1015        SCROLLBARS_OUTSIDE_INSET
1016    })
1017    @Retention(RetentionPolicy.SOURCE)
1018    public @interface ScrollBarStyle {}
1019
1020    /**
1021     * The scrollbar style to display the scrollbars inside the content area,
1022     * without increasing the padding. The scrollbars will be overlaid with
1023     * translucency on the view's content.
1024     */
1025    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1026
1027    /**
1028     * The scrollbar style to display the scrollbars inside the padded area,
1029     * increasing the padding of the view. The scrollbars will not overlap the
1030     * content area of the view.
1031     */
1032    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1033
1034    /**
1035     * The scrollbar style to display the scrollbars at the edge of the view,
1036     * without increasing the padding. The scrollbars will be overlaid with
1037     * translucency.
1038     */
1039    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1040
1041    /**
1042     * The scrollbar style to display the scrollbars at the edge of the view,
1043     * increasing the padding of the view. The scrollbars will only overlap the
1044     * background, if any.
1045     */
1046    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1047
1048    /**
1049     * Mask to check if the scrollbar style is overlay or inset.
1050     * {@hide}
1051     */
1052    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1053
1054    /**
1055     * Mask to check if the scrollbar style is inside or outside.
1056     * {@hide}
1057     */
1058    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1059
1060    /**
1061     * Mask for scrollbar style.
1062     * {@hide}
1063     */
1064    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1065
1066    /**
1067     * View flag indicating that the screen should remain on while the
1068     * window containing this view is visible to the user.  This effectively
1069     * takes care of automatically setting the WindowManager's
1070     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1071     */
1072    public static final int KEEP_SCREEN_ON = 0x04000000;
1073
1074    /**
1075     * View flag indicating whether this view should have sound effects enabled
1076     * for events such as clicking and touching.
1077     */
1078    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1079
1080    /**
1081     * View flag indicating whether this view should have haptic feedback
1082     * enabled for events such as long presses.
1083     */
1084    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1085
1086    /**
1087     * <p>Indicates that the view hierarchy should stop saving state when
1088     * it reaches this view.  If state saving is initiated immediately at
1089     * the view, it will be allowed.
1090     * {@hide}
1091     */
1092    static final int PARENT_SAVE_DISABLED = 0x20000000;
1093
1094    /**
1095     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1096     * {@hide}
1097     */
1098    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1099
1100    /** @hide */
1101    @IntDef(flag = true,
1102            value = {
1103                FOCUSABLES_ALL,
1104                FOCUSABLES_TOUCH_MODE
1105            })
1106    @Retention(RetentionPolicy.SOURCE)
1107    public @interface FocusableMode {}
1108
1109    /**
1110     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1111     * should add all focusable Views regardless if they are focusable in touch mode.
1112     */
1113    public static final int FOCUSABLES_ALL = 0x00000000;
1114
1115    /**
1116     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1117     * should add only Views focusable in touch mode.
1118     */
1119    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1120
1121    /** @hide */
1122    @IntDef({
1123            FOCUS_BACKWARD,
1124            FOCUS_FORWARD,
1125            FOCUS_LEFT,
1126            FOCUS_UP,
1127            FOCUS_RIGHT,
1128            FOCUS_DOWN
1129    })
1130    @Retention(RetentionPolicy.SOURCE)
1131    public @interface FocusDirection {}
1132
1133    /** @hide */
1134    @IntDef({
1135            FOCUS_LEFT,
1136            FOCUS_UP,
1137            FOCUS_RIGHT,
1138            FOCUS_DOWN
1139    })
1140    @Retention(RetentionPolicy.SOURCE)
1141    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1142
1143    /**
1144     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1145     * item.
1146     */
1147    public static final int FOCUS_BACKWARD = 0x00000001;
1148
1149    /**
1150     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1151     * item.
1152     */
1153    public static final int FOCUS_FORWARD = 0x00000002;
1154
1155    /**
1156     * Use with {@link #focusSearch(int)}. Move focus to the left.
1157     */
1158    public static final int FOCUS_LEFT = 0x00000011;
1159
1160    /**
1161     * Use with {@link #focusSearch(int)}. Move focus up.
1162     */
1163    public static final int FOCUS_UP = 0x00000021;
1164
1165    /**
1166     * Use with {@link #focusSearch(int)}. Move focus to the right.
1167     */
1168    public static final int FOCUS_RIGHT = 0x00000042;
1169
1170    /**
1171     * Use with {@link #focusSearch(int)}. Move focus down.
1172     */
1173    public static final int FOCUS_DOWN = 0x00000082;
1174
1175    /**
1176     * Bits of {@link #getMeasuredWidthAndState()} and
1177     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1178     */
1179    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1180
1181    /**
1182     * Bits of {@link #getMeasuredWidthAndState()} and
1183     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1184     */
1185    public static final int MEASURED_STATE_MASK = 0xff000000;
1186
1187    /**
1188     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1189     * for functions that combine both width and height into a single int,
1190     * such as {@link #getMeasuredState()} and the childState argument of
1191     * {@link #resolveSizeAndState(int, int, int)}.
1192     */
1193    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1194
1195    /**
1196     * Bit of {@link #getMeasuredWidthAndState()} and
1197     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1198     * is smaller that the space the view would like to have.
1199     */
1200    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1201
1202    /**
1203     * Base View state sets
1204     */
1205    // Singles
1206    /**
1207     * Indicates the view has no states set. States are used with
1208     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1209     * view depending on its state.
1210     *
1211     * @see android.graphics.drawable.Drawable
1212     * @see #getDrawableState()
1213     */
1214    protected static final int[] EMPTY_STATE_SET;
1215    /**
1216     * Indicates the view is enabled. States are used with
1217     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1218     * view depending on its state.
1219     *
1220     * @see android.graphics.drawable.Drawable
1221     * @see #getDrawableState()
1222     */
1223    protected static final int[] ENABLED_STATE_SET;
1224    /**
1225     * Indicates the view is focused. States are used with
1226     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1227     * view depending on its state.
1228     *
1229     * @see android.graphics.drawable.Drawable
1230     * @see #getDrawableState()
1231     */
1232    protected static final int[] FOCUSED_STATE_SET;
1233    /**
1234     * Indicates the view is selected. States are used with
1235     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1236     * view depending on its state.
1237     *
1238     * @see android.graphics.drawable.Drawable
1239     * @see #getDrawableState()
1240     */
1241    protected static final int[] SELECTED_STATE_SET;
1242    /**
1243     * Indicates the view is pressed. States are used with
1244     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1245     * view depending on its state.
1246     *
1247     * @see android.graphics.drawable.Drawable
1248     * @see #getDrawableState()
1249     */
1250    protected static final int[] PRESSED_STATE_SET;
1251    /**
1252     * Indicates the view's window has focus. States are used with
1253     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1254     * view depending on its state.
1255     *
1256     * @see android.graphics.drawable.Drawable
1257     * @see #getDrawableState()
1258     */
1259    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1260    // Doubles
1261    /**
1262     * Indicates the view is enabled and has the focus.
1263     *
1264     * @see #ENABLED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1268    /**
1269     * Indicates the view is enabled and selected.
1270     *
1271     * @see #ENABLED_STATE_SET
1272     * @see #SELECTED_STATE_SET
1273     */
1274    protected static final int[] ENABLED_SELECTED_STATE_SET;
1275    /**
1276     * Indicates the view is enabled and that its window has focus.
1277     *
1278     * @see #ENABLED_STATE_SET
1279     * @see #WINDOW_FOCUSED_STATE_SET
1280     */
1281    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1282    /**
1283     * Indicates the view is focused and selected.
1284     *
1285     * @see #FOCUSED_STATE_SET
1286     * @see #SELECTED_STATE_SET
1287     */
1288    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1289    /**
1290     * Indicates the view has the focus and that its window has the focus.
1291     *
1292     * @see #FOCUSED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is selected and that its window has the focus.
1298     *
1299     * @see #SELECTED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1303    // Triples
1304    /**
1305     * Indicates the view is enabled, focused and selected.
1306     *
1307     * @see #ENABLED_STATE_SET
1308     * @see #FOCUSED_STATE_SET
1309     * @see #SELECTED_STATE_SET
1310     */
1311    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1312    /**
1313     * Indicates the view is enabled, focused and its window has the focus.
1314     *
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     * @see #WINDOW_FOCUSED_STATE_SET
1318     */
1319    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1320    /**
1321     * Indicates the view is enabled, selected and its window has the focus.
1322     *
1323     * @see #ENABLED_STATE_SET
1324     * @see #SELECTED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is focused, selected and its window has the focus.
1330     *
1331     * @see #FOCUSED_STATE_SET
1332     * @see #SELECTED_STATE_SET
1333     * @see #WINDOW_FOCUSED_STATE_SET
1334     */
1335    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1336    /**
1337     * Indicates the view is enabled, focused, selected and its window
1338     * has the focus.
1339     *
1340     * @see #ENABLED_STATE_SET
1341     * @see #FOCUSED_STATE_SET
1342     * @see #SELECTED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed and its window has the focus.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #WINDOW_FOCUSED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed and selected.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #SELECTED_STATE_SET
1358     */
1359    protected static final int[] PRESSED_SELECTED_STATE_SET;
1360    /**
1361     * Indicates the view is pressed, selected and its window has the focus.
1362     *
1363     * @see #PRESSED_STATE_SET
1364     * @see #SELECTED_STATE_SET
1365     * @see #WINDOW_FOCUSED_STATE_SET
1366     */
1367    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1368    /**
1369     * Indicates the view is pressed and focused.
1370     *
1371     * @see #PRESSED_STATE_SET
1372     * @see #FOCUSED_STATE_SET
1373     */
1374    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1375    /**
1376     * Indicates the view is pressed, focused and its window has the focus.
1377     *
1378     * @see #PRESSED_STATE_SET
1379     * @see #FOCUSED_STATE_SET
1380     * @see #WINDOW_FOCUSED_STATE_SET
1381     */
1382    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1383    /**
1384     * Indicates the view is pressed, focused and selected.
1385     *
1386     * @see #PRESSED_STATE_SET
1387     * @see #SELECTED_STATE_SET
1388     * @see #FOCUSED_STATE_SET
1389     */
1390    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1391    /**
1392     * Indicates the view is pressed, focused, selected and its window has the focus.
1393     *
1394     * @see #PRESSED_STATE_SET
1395     * @see #FOCUSED_STATE_SET
1396     * @see #SELECTED_STATE_SET
1397     * @see #WINDOW_FOCUSED_STATE_SET
1398     */
1399    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1400    /**
1401     * Indicates the view is pressed and enabled.
1402     *
1403     * @see #PRESSED_STATE_SET
1404     * @see #ENABLED_STATE_SET
1405     */
1406    protected static final int[] PRESSED_ENABLED_STATE_SET;
1407    /**
1408     * Indicates the view is pressed, enabled and its window has the focus.
1409     *
1410     * @see #PRESSED_STATE_SET
1411     * @see #ENABLED_STATE_SET
1412     * @see #WINDOW_FOCUSED_STATE_SET
1413     */
1414    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1415    /**
1416     * Indicates the view is pressed, enabled and selected.
1417     *
1418     * @see #PRESSED_STATE_SET
1419     * @see #ENABLED_STATE_SET
1420     * @see #SELECTED_STATE_SET
1421     */
1422    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1423    /**
1424     * Indicates the view is pressed, enabled, selected and its window has the
1425     * focus.
1426     *
1427     * @see #PRESSED_STATE_SET
1428     * @see #ENABLED_STATE_SET
1429     * @see #SELECTED_STATE_SET
1430     * @see #WINDOW_FOCUSED_STATE_SET
1431     */
1432    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1433    /**
1434     * Indicates the view is pressed, enabled and focused.
1435     *
1436     * @see #PRESSED_STATE_SET
1437     * @see #ENABLED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1441    /**
1442     * Indicates the view is pressed, enabled, focused and its window has the
1443     * focus.
1444     *
1445     * @see #PRESSED_STATE_SET
1446     * @see #ENABLED_STATE_SET
1447     * @see #FOCUSED_STATE_SET
1448     * @see #WINDOW_FOCUSED_STATE_SET
1449     */
1450    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1451    /**
1452     * Indicates the view is pressed, enabled, focused and selected.
1453     *
1454     * @see #PRESSED_STATE_SET
1455     * @see #ENABLED_STATE_SET
1456     * @see #SELECTED_STATE_SET
1457     * @see #FOCUSED_STATE_SET
1458     */
1459    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1460    /**
1461     * Indicates the view is pressed, enabled, focused, selected and its window
1462     * has the focus.
1463     *
1464     * @see #PRESSED_STATE_SET
1465     * @see #ENABLED_STATE_SET
1466     * @see #SELECTED_STATE_SET
1467     * @see #FOCUSED_STATE_SET
1468     * @see #WINDOW_FOCUSED_STATE_SET
1469     */
1470    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1471
1472    static {
1473        EMPTY_STATE_SET = StateSet.get(0);
1474
1475        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1476
1477        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1478        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1479                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1480
1481        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1482        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1483                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1484        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1485                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1486        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1487                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1488                        | StateSet.VIEW_STATE_FOCUSED);
1489
1490        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1491        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1492                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1493        ENABLED_SELECTED_STATE_SET = StateSet.get(
1494                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1495        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1496                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1497                        | StateSet.VIEW_STATE_ENABLED);
1498        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1499                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1500        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1501                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1502                        | StateSet.VIEW_STATE_ENABLED);
1503        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1504                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1505                        | StateSet.VIEW_STATE_ENABLED);
1506        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1507                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1508                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1509
1510        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1511        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1512                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1513        PRESSED_SELECTED_STATE_SET = StateSet.get(
1514                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1515        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1516                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1517                        | StateSet.VIEW_STATE_PRESSED);
1518        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1519                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1520        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1521                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1522                        | StateSet.VIEW_STATE_PRESSED);
1523        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1524                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1525                        | StateSet.VIEW_STATE_PRESSED);
1526        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1527                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1528                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1529        PRESSED_ENABLED_STATE_SET = StateSet.get(
1530                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1531        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1532                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1533                        | StateSet.VIEW_STATE_PRESSED);
1534        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1535                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1536                        | StateSet.VIEW_STATE_PRESSED);
1537        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1538                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1539                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1540        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1541                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1542                        | StateSet.VIEW_STATE_PRESSED);
1543        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1544                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1545                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1546        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1547                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1548                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1549        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1550                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1551                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1552                        | StateSet.VIEW_STATE_PRESSED);
1553    }
1554
1555    /**
1556     * Accessibility event types that are dispatched for text population.
1557     */
1558    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1559            AccessibilityEvent.TYPE_VIEW_CLICKED
1560            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1561            | AccessibilityEvent.TYPE_VIEW_SELECTED
1562            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1563            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1564            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1565            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1566            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1567            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1568            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1569            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1570
1571    /**
1572     * Temporary Rect currently for use in setBackground().  This will probably
1573     * be extended in the future to hold our own class with more than just
1574     * a Rect. :)
1575     */
1576    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1577
1578    /**
1579     * Map used to store views' tags.
1580     */
1581    private SparseArray<Object> mKeyedTags;
1582
1583    /**
1584     * The next available accessibility id.
1585     */
1586    private static int sNextAccessibilityViewId;
1587
1588    /**
1589     * The animation currently associated with this view.
1590     * @hide
1591     */
1592    protected Animation mCurrentAnimation = null;
1593
1594    /**
1595     * Width as measured during measure pass.
1596     * {@hide}
1597     */
1598    @ViewDebug.ExportedProperty(category = "measurement")
1599    int mMeasuredWidth;
1600
1601    /**
1602     * Height as measured during measure pass.
1603     * {@hide}
1604     */
1605    @ViewDebug.ExportedProperty(category = "measurement")
1606    int mMeasuredHeight;
1607
1608    /**
1609     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1610     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1611     * its display list. This flag, used only when hw accelerated, allows us to clear the
1612     * flag while retaining this information until it's needed (at getDisplayList() time and
1613     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1614     *
1615     * {@hide}
1616     */
1617    boolean mRecreateDisplayList = false;
1618
1619    /**
1620     * The view's identifier.
1621     * {@hide}
1622     *
1623     * @see #setId(int)
1624     * @see #getId()
1625     */
1626    @IdRes
1627    @ViewDebug.ExportedProperty(resolveId = true)
1628    int mID = NO_ID;
1629
1630    /**
1631     * The stable ID of this view for accessibility purposes.
1632     */
1633    int mAccessibilityViewId = NO_ID;
1634
1635    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1636
1637    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1638
1639    /**
1640     * The view's tag.
1641     * {@hide}
1642     *
1643     * @see #setTag(Object)
1644     * @see #getTag()
1645     */
1646    protected Object mTag = null;
1647
1648    // for mPrivateFlags:
1649    /** {@hide} */
1650    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1651    /** {@hide} */
1652    static final int PFLAG_FOCUSED                     = 0x00000002;
1653    /** {@hide} */
1654    static final int PFLAG_SELECTED                    = 0x00000004;
1655    /** {@hide} */
1656    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1657    /** {@hide} */
1658    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1659    /** {@hide} */
1660    static final int PFLAG_DRAWN                       = 0x00000020;
1661    /**
1662     * When this flag is set, this view is running an animation on behalf of its
1663     * children and should therefore not cancel invalidate requests, even if they
1664     * lie outside of this view's bounds.
1665     *
1666     * {@hide}
1667     */
1668    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1669    /** {@hide} */
1670    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1671    /** {@hide} */
1672    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1673    /** {@hide} */
1674    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1675    /** {@hide} */
1676    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1677    /** {@hide} */
1678    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1679    /** {@hide} */
1680    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1681
1682    private static final int PFLAG_PRESSED             = 0x00004000;
1683
1684    /** {@hide} */
1685    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1686    /**
1687     * Flag used to indicate that this view should be drawn once more (and only once
1688     * more) after its animation has completed.
1689     * {@hide}
1690     */
1691    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1692
1693    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1694
1695    /**
1696     * Indicates that the View returned true when onSetAlpha() was called and that
1697     * the alpha must be restored.
1698     * {@hide}
1699     */
1700    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1701
1702    /**
1703     * Set by {@link #setScrollContainer(boolean)}.
1704     */
1705    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1706
1707    /**
1708     * Set by {@link #setScrollContainer(boolean)}.
1709     */
1710    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1711
1712    /**
1713     * View flag indicating whether this view was invalidated (fully or partially.)
1714     *
1715     * @hide
1716     */
1717    static final int PFLAG_DIRTY                       = 0x00200000;
1718
1719    /**
1720     * View flag indicating whether this view was invalidated by an opaque
1721     * invalidate request.
1722     *
1723     * @hide
1724     */
1725    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1726
1727    /**
1728     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1729     *
1730     * @hide
1731     */
1732    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1733
1734    /**
1735     * Indicates whether the background is opaque.
1736     *
1737     * @hide
1738     */
1739    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1740
1741    /**
1742     * Indicates whether the scrollbars are opaque.
1743     *
1744     * @hide
1745     */
1746    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1747
1748    /**
1749     * Indicates whether the view is opaque.
1750     *
1751     * @hide
1752     */
1753    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1754
1755    /**
1756     * Indicates a prepressed state;
1757     * the short time between ACTION_DOWN and recognizing
1758     * a 'real' press. Prepressed is used to recognize quick taps
1759     * even when they are shorter than ViewConfiguration.getTapTimeout().
1760     *
1761     * @hide
1762     */
1763    private static final int PFLAG_PREPRESSED          = 0x02000000;
1764
1765    /**
1766     * Indicates whether the view is temporarily detached.
1767     *
1768     * @hide
1769     */
1770    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1771
1772    /**
1773     * Indicates that we should awaken scroll bars once attached
1774     *
1775     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1776     * during window attachment and it is no longer needed. Feel free to repurpose it.
1777     *
1778     * @hide
1779     */
1780    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1781
1782    /**
1783     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1784     * @hide
1785     */
1786    private static final int PFLAG_HOVERED             = 0x10000000;
1787
1788    /**
1789     * no longer needed, should be reused
1790     */
1791    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1792
1793    /** {@hide} */
1794    static final int PFLAG_ACTIVATED                   = 0x40000000;
1795
1796    /**
1797     * Indicates that this view was specifically invalidated, not just dirtied because some
1798     * child view was invalidated. The flag is used to determine when we need to recreate
1799     * a view's display list (as opposed to just returning a reference to its existing
1800     * display list).
1801     *
1802     * @hide
1803     */
1804    static final int PFLAG_INVALIDATED                 = 0x80000000;
1805
1806    /**
1807     * Masks for mPrivateFlags2, as generated by dumpFlags():
1808     *
1809     * |-------|-------|-------|-------|
1810     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1811     *                                1  PFLAG2_DRAG_HOVERED
1812     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1813     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1814     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1815     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1816     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1817     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1818     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1819     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1820     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1821     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1822     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1823     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1824     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1825     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1826     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1827     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1828     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1829     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1830     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1831     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1832     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1833     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1834     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1835     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1836     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1837     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1838     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1839     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1840     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1841     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1842     *    1                              PFLAG2_PADDING_RESOLVED
1843     *   1                               PFLAG2_DRAWABLE_RESOLVED
1844     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1845     * |-------|-------|-------|-------|
1846     */
1847
1848    /**
1849     * Indicates that this view has reported that it can accept the current drag's content.
1850     * Cleared when the drag operation concludes.
1851     * @hide
1852     */
1853    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1854
1855    /**
1856     * Indicates that this view is currently directly under the drag location in a
1857     * drag-and-drop operation involving content that it can accept.  Cleared when
1858     * the drag exits the view, or when the drag operation concludes.
1859     * @hide
1860     */
1861    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1862
1863    /** @hide */
1864    @IntDef({
1865        LAYOUT_DIRECTION_LTR,
1866        LAYOUT_DIRECTION_RTL,
1867        LAYOUT_DIRECTION_INHERIT,
1868        LAYOUT_DIRECTION_LOCALE
1869    })
1870    @Retention(RetentionPolicy.SOURCE)
1871    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1872    public @interface LayoutDir {}
1873
1874    /** @hide */
1875    @IntDef({
1876        LAYOUT_DIRECTION_LTR,
1877        LAYOUT_DIRECTION_RTL
1878    })
1879    @Retention(RetentionPolicy.SOURCE)
1880    public @interface ResolvedLayoutDir {}
1881
1882    /**
1883     * A flag to indicate that the layout direction of this view has not been defined yet.
1884     * @hide
1885     */
1886    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1887
1888    /**
1889     * Horizontal layout direction of this view is from Left to Right.
1890     * Use with {@link #setLayoutDirection}.
1891     */
1892    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1893
1894    /**
1895     * Horizontal layout direction of this view is from Right to Left.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1899
1900    /**
1901     * Horizontal layout direction of this view is inherited from its parent.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1905
1906    /**
1907     * Horizontal layout direction of this view is from deduced from the default language
1908     * script for the locale. Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1911
1912    /**
1913     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1914     * @hide
1915     */
1916    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1917
1918    /**
1919     * Mask for use with private flags indicating bits used for horizontal layout direction.
1920     * @hide
1921     */
1922    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1923
1924    /**
1925     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1926     * right-to-left direction.
1927     * @hide
1928     */
1929    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1930
1931    /**
1932     * Indicates whether the view horizontal layout direction has been resolved.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1936
1937    /**
1938     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1942            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1943
1944    /*
1945     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1946     * flag value.
1947     * @hide
1948     */
1949    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1950            LAYOUT_DIRECTION_LTR,
1951            LAYOUT_DIRECTION_RTL,
1952            LAYOUT_DIRECTION_INHERIT,
1953            LAYOUT_DIRECTION_LOCALE
1954    };
1955
1956    /**
1957     * Default horizontal layout direction.
1958     */
1959    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1960
1961    /**
1962     * Default horizontal layout direction.
1963     * @hide
1964     */
1965    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1966
1967    /**
1968     * Text direction is inherited through {@link ViewGroup}
1969     */
1970    public static final int TEXT_DIRECTION_INHERIT = 0;
1971
1972    /**
1973     * Text direction is using "first strong algorithm". The first strong directional character
1974     * determines the paragraph direction. If there is no strong directional character, the
1975     * paragraph direction is the view's resolved layout direction.
1976     */
1977    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1978
1979    /**
1980     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1981     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1982     * If there are neither, the paragraph direction is the view's resolved layout direction.
1983     */
1984    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1985
1986    /**
1987     * Text direction is forced to LTR.
1988     */
1989    public static final int TEXT_DIRECTION_LTR = 3;
1990
1991    /**
1992     * Text direction is forced to RTL.
1993     */
1994    public static final int TEXT_DIRECTION_RTL = 4;
1995
1996    /**
1997     * Text direction is coming from the system Locale.
1998     */
1999    public static final int TEXT_DIRECTION_LOCALE = 5;
2000
2001    /**
2002     * Text direction is using "first strong algorithm". The first strong directional character
2003     * determines the paragraph direction. If there is no strong directional character, the
2004     * paragraph direction is LTR.
2005     */
2006    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2007
2008    /**
2009     * Text direction is using "first strong algorithm". The first strong directional character
2010     * determines the paragraph direction. If there is no strong directional character, the
2011     * paragraph direction is RTL.
2012     */
2013    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2014
2015    /**
2016     * Default text direction is inherited
2017     */
2018    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2019
2020    /**
2021     * Default resolved text direction
2022     * @hide
2023     */
2024    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2025
2026    /**
2027     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2028     * @hide
2029     */
2030    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2031
2032    /**
2033     * Mask for use with private flags indicating bits used for text direction.
2034     * @hide
2035     */
2036    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2037            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2038
2039    /**
2040     * Array of text direction flags for mapping attribute "textDirection" to correct
2041     * flag value.
2042     * @hide
2043     */
2044    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2045            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2046            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2047            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2048            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2049            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2050            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2051            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2052            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2053    };
2054
2055    /**
2056     * Indicates whether the view text direction has been resolved.
2057     * @hide
2058     */
2059    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2060            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2061
2062    /**
2063     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2064     * @hide
2065     */
2066    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2067
2068    /**
2069     * Mask for use with private flags indicating bits used for resolved text direction.
2070     * @hide
2071     */
2072    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2073            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2074
2075    /**
2076     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2077     * @hide
2078     */
2079    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2080            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2081
2082    /** @hide */
2083    @IntDef({
2084        TEXT_ALIGNMENT_INHERIT,
2085        TEXT_ALIGNMENT_GRAVITY,
2086        TEXT_ALIGNMENT_CENTER,
2087        TEXT_ALIGNMENT_TEXT_START,
2088        TEXT_ALIGNMENT_TEXT_END,
2089        TEXT_ALIGNMENT_VIEW_START,
2090        TEXT_ALIGNMENT_VIEW_END
2091    })
2092    @Retention(RetentionPolicy.SOURCE)
2093    public @interface TextAlignment {}
2094
2095    /**
2096     * Default text alignment. The text alignment of this View is inherited from its parent.
2097     * Use with {@link #setTextAlignment(int)}
2098     */
2099    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2100
2101    /**
2102     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2103     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2104     *
2105     * Use with {@link #setTextAlignment(int)}
2106     */
2107    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2108
2109    /**
2110     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2111     *
2112     * Use with {@link #setTextAlignment(int)}
2113     */
2114    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2115
2116    /**
2117     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2118     *
2119     * Use with {@link #setTextAlignment(int)}
2120     */
2121    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2122
2123    /**
2124     * Center the paragraph, e.g. ALIGN_CENTER.
2125     *
2126     * Use with {@link #setTextAlignment(int)}
2127     */
2128    public static final int TEXT_ALIGNMENT_CENTER = 4;
2129
2130    /**
2131     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2132     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2133     *
2134     * Use with {@link #setTextAlignment(int)}
2135     */
2136    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2137
2138    /**
2139     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2140     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2141     *
2142     * Use with {@link #setTextAlignment(int)}
2143     */
2144    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2145
2146    /**
2147     * Default text alignment is inherited
2148     */
2149    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2150
2151    /**
2152     * Default resolved text alignment
2153     * @hide
2154     */
2155    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2156
2157    /**
2158      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2159      * @hide
2160      */
2161    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2162
2163    /**
2164      * Mask for use with private flags indicating bits used for text alignment.
2165      * @hide
2166      */
2167    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2168
2169    /**
2170     * Array of text direction flags for mapping attribute "textAlignment" to correct
2171     * flag value.
2172     * @hide
2173     */
2174    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2175            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2176            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2177            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2178            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2179            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2180            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2181            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2182    };
2183
2184    /**
2185     * Indicates whether the view text alignment has been resolved.
2186     * @hide
2187     */
2188    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2189
2190    /**
2191     * Bit shift to get the resolved text alignment.
2192     * @hide
2193     */
2194    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2195
2196    /**
2197     * Mask for use with private flags indicating bits used for text alignment.
2198     * @hide
2199     */
2200    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2201            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2202
2203    /**
2204     * Indicates whether if the view text alignment has been resolved to gravity
2205     */
2206    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2207            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2208
2209    // Accessiblity constants for mPrivateFlags2
2210
2211    /**
2212     * Shift for the bits in {@link #mPrivateFlags2} related to the
2213     * "importantForAccessibility" attribute.
2214     */
2215    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2216
2217    /**
2218     * Automatically determine whether a view is important for accessibility.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2221
2222    /**
2223     * The view is important for accessibility.
2224     */
2225    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2226
2227    /**
2228     * The view is not important for accessibility.
2229     */
2230    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2231
2232    /**
2233     * The view is not important for accessibility, nor are any of its
2234     * descendant views.
2235     */
2236    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2237
2238    /**
2239     * The default whether the view is important for accessibility.
2240     */
2241    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2242
2243    /**
2244     * Mask for obtainig the bits which specify how to determine
2245     * whether a view is important for accessibility.
2246     */
2247    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2248        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2249        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2250        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2251
2252    /**
2253     * Shift for the bits in {@link #mPrivateFlags2} related to the
2254     * "accessibilityLiveRegion" attribute.
2255     */
2256    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2257
2258    /**
2259     * Live region mode specifying that accessibility services should not
2260     * automatically announce changes to this view. This is the default live
2261     * region mode for most views.
2262     * <p>
2263     * Use with {@link #setAccessibilityLiveRegion(int)}.
2264     */
2265    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2266
2267    /**
2268     * Live region mode specifying that accessibility services should announce
2269     * changes to this view.
2270     * <p>
2271     * Use with {@link #setAccessibilityLiveRegion(int)}.
2272     */
2273    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2274
2275    /**
2276     * Live region mode specifying that accessibility services should interrupt
2277     * ongoing speech to immediately announce changes to this view.
2278     * <p>
2279     * Use with {@link #setAccessibilityLiveRegion(int)}.
2280     */
2281    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2282
2283    /**
2284     * The default whether the view is important for accessibility.
2285     */
2286    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2287
2288    /**
2289     * Mask for obtaining the bits which specify a view's accessibility live
2290     * region mode.
2291     */
2292    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2293            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2294            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2295
2296    /**
2297     * Flag indicating whether a view has accessibility focus.
2298     */
2299    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2300
2301    /**
2302     * Flag whether the accessibility state of the subtree rooted at this view changed.
2303     */
2304    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2305
2306    /**
2307     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2308     * is used to check whether later changes to the view's transform should invalidate the
2309     * view to force the quickReject test to run again.
2310     */
2311    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2312
2313    /**
2314     * Flag indicating that start/end padding has been resolved into left/right padding
2315     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2316     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2317     * during measurement. In some special cases this is required such as when an adapter-based
2318     * view measures prospective children without attaching them to a window.
2319     */
2320    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2321
2322    /**
2323     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2324     */
2325    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2326
2327    /**
2328     * Indicates that the view is tracking some sort of transient state
2329     * that the app should not need to be aware of, but that the framework
2330     * should take special care to preserve.
2331     */
2332    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2333
2334    /**
2335     * Group of bits indicating that RTL properties resolution is done.
2336     */
2337    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2338            PFLAG2_TEXT_DIRECTION_RESOLVED |
2339            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2340            PFLAG2_PADDING_RESOLVED |
2341            PFLAG2_DRAWABLE_RESOLVED;
2342
2343    // There are a couple of flags left in mPrivateFlags2
2344
2345    /* End of masks for mPrivateFlags2 */
2346
2347    /**
2348     * Masks for mPrivateFlags3, as generated by dumpFlags():
2349     *
2350     * |-------|-------|-------|-------|
2351     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2352     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2353     *                               1   PFLAG3_IS_LAID_OUT
2354     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2355     *                             1     PFLAG3_CALLED_SUPER
2356     *                            1      PFLAG3_APPLYING_INSETS
2357     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2358     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2359     *                         1         PFLAG3_ASSIST_BLOCKED
2360     * |-------|-------|-------|-------|
2361     */
2362
2363    /**
2364     * Flag indicating that view has a transform animation set on it. This is used to track whether
2365     * an animation is cleared between successive frames, in order to tell the associated
2366     * DisplayList to clear its animation matrix.
2367     */
2368    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2369
2370    /**
2371     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2372     * animation is cleared between successive frames, in order to tell the associated
2373     * DisplayList to restore its alpha value.
2374     */
2375    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2376
2377    /**
2378     * Flag indicating that the view has been through at least one layout since it
2379     * was last attached to a window.
2380     */
2381    static final int PFLAG3_IS_LAID_OUT = 0x4;
2382
2383    /**
2384     * Flag indicating that a call to measure() was skipped and should be done
2385     * instead when layout() is invoked.
2386     */
2387    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2388
2389    /**
2390     * Flag indicating that an overridden method correctly called down to
2391     * the superclass implementation as required by the API spec.
2392     */
2393    static final int PFLAG3_CALLED_SUPER = 0x10;
2394
2395    /**
2396     * Flag indicating that we're in the process of applying window insets.
2397     */
2398    static final int PFLAG3_APPLYING_INSETS = 0x20;
2399
2400    /**
2401     * Flag indicating that we're in the process of fitting system windows using the old method.
2402     */
2403    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2404
2405    /**
2406     * Flag indicating that nested scrolling is enabled for this view.
2407     * The view will optionally cooperate with views up its parent chain to allow for
2408     * integrated nested scrolling along the same axis.
2409     */
2410    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2411
2412    /**
2413     * Flag indicating that the bottom scroll indicator should be displayed
2414     * when this view can scroll up.
2415     */
2416    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2417
2418    /**
2419     * Flag indicating that the bottom scroll indicator should be displayed
2420     * when this view can scroll down.
2421     */
2422    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2423
2424    /**
2425     * Flag indicating that the left scroll indicator should be displayed
2426     * when this view can scroll left.
2427     */
2428    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2429
2430    /**
2431     * Flag indicating that the right scroll indicator should be displayed
2432     * when this view can scroll right.
2433     */
2434    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2435
2436    /**
2437     * Flag indicating that the start scroll indicator should be displayed
2438     * when this view can scroll in the start direction.
2439     */
2440    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2441
2442    /**
2443     * Flag indicating that the end scroll indicator should be displayed
2444     * when this view can scroll in the end direction.
2445     */
2446    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2447
2448    /* End of masks for mPrivateFlags3 */
2449
2450    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2451
2452    static final int SCROLL_INDICATORS_NONE = 0x0000;
2453
2454    /**
2455     * Mask for use with setFlags indicating bits used for indicating which
2456     * scroll indicators are enabled.
2457     */
2458    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2459            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2460            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2461            | PFLAG3_SCROLL_INDICATOR_END;
2462
2463    /**
2464     * Left-shift required to translate between public scroll indicator flags
2465     * and internal PFLAGS3 flags. When used as a right-shift, translates
2466     * PFLAGS3 flags to public flags.
2467     */
2468    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2469
2470    /** @hide */
2471    @Retention(RetentionPolicy.SOURCE)
2472    @IntDef(flag = true,
2473            value = {
2474                    SCROLL_INDICATOR_TOP,
2475                    SCROLL_INDICATOR_BOTTOM,
2476                    SCROLL_INDICATOR_LEFT,
2477                    SCROLL_INDICATOR_RIGHT,
2478                    SCROLL_INDICATOR_START,
2479                    SCROLL_INDICATOR_END,
2480            })
2481    public @interface ScrollIndicators {}
2482
2483    /**
2484     * Scroll indicator direction for the top edge of the view.
2485     *
2486     * @see #setScrollIndicators(int)
2487     * @see #setScrollIndicators(int, int)
2488     * @see #getScrollIndicators()
2489     */
2490    public static final int SCROLL_INDICATOR_TOP =
2491            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2492
2493    /**
2494     * Scroll indicator direction for the bottom edge of the view.
2495     *
2496     * @see #setScrollIndicators(int)
2497     * @see #setScrollIndicators(int, int)
2498     * @see #getScrollIndicators()
2499     */
2500    public static final int SCROLL_INDICATOR_BOTTOM =
2501            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2502
2503    /**
2504     * Scroll indicator direction for the left edge of the view.
2505     *
2506     * @see #setScrollIndicators(int)
2507     * @see #setScrollIndicators(int, int)
2508     * @see #getScrollIndicators()
2509     */
2510    public static final int SCROLL_INDICATOR_LEFT =
2511            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2512
2513    /**
2514     * Scroll indicator direction for the right edge of the view.
2515     *
2516     * @see #setScrollIndicators(int)
2517     * @see #setScrollIndicators(int, int)
2518     * @see #getScrollIndicators()
2519     */
2520    public static final int SCROLL_INDICATOR_RIGHT =
2521            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2522
2523    /**
2524     * Scroll indicator direction for the starting edge of the view.
2525     * <p>
2526     * Resolved according to the view's layout direction, see
2527     * {@link #getLayoutDirection()} for more information.
2528     *
2529     * @see #setScrollIndicators(int)
2530     * @see #setScrollIndicators(int, int)
2531     * @see #getScrollIndicators()
2532     */
2533    public static final int SCROLL_INDICATOR_START =
2534            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2535
2536    /**
2537     * Scroll indicator direction for the ending edge of the view.
2538     * <p>
2539     * Resolved according to the view's layout direction, see
2540     * {@link #getLayoutDirection()} for more information.
2541     *
2542     * @see #setScrollIndicators(int)
2543     * @see #setScrollIndicators(int, int)
2544     * @see #getScrollIndicators()
2545     */
2546    public static final int SCROLL_INDICATOR_END =
2547            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2548
2549    /**
2550     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2551     * into this view.<p>
2552     */
2553    static final int PFLAG3_ASSIST_BLOCKED = 0x100;
2554
2555    /**
2556     * Always allow a user to over-scroll this view, provided it is a
2557     * view that can scroll.
2558     *
2559     * @see #getOverScrollMode()
2560     * @see #setOverScrollMode(int)
2561     */
2562    public static final int OVER_SCROLL_ALWAYS = 0;
2563
2564    /**
2565     * Allow a user to over-scroll this view only if the content is large
2566     * enough to meaningfully scroll, provided it is a view that can scroll.
2567     *
2568     * @see #getOverScrollMode()
2569     * @see #setOverScrollMode(int)
2570     */
2571    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2572
2573    /**
2574     * Never allow a user to over-scroll this view.
2575     *
2576     * @see #getOverScrollMode()
2577     * @see #setOverScrollMode(int)
2578     */
2579    public static final int OVER_SCROLL_NEVER = 2;
2580
2581    /**
2582     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2583     * requested the system UI (status bar) to be visible (the default).
2584     *
2585     * @see #setSystemUiVisibility(int)
2586     */
2587    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2588
2589    /**
2590     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2591     * system UI to enter an unobtrusive "low profile" mode.
2592     *
2593     * <p>This is for use in games, book readers, video players, or any other
2594     * "immersive" application where the usual system chrome is deemed too distracting.
2595     *
2596     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2597     *
2598     * @see #setSystemUiVisibility(int)
2599     */
2600    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2601
2602    /**
2603     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2604     * system navigation be temporarily hidden.
2605     *
2606     * <p>This is an even less obtrusive state than that called for by
2607     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2608     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2609     * those to disappear. This is useful (in conjunction with the
2610     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2611     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2612     * window flags) for displaying content using every last pixel on the display.
2613     *
2614     * <p>There is a limitation: because navigation controls are so important, the least user
2615     * interaction will cause them to reappear immediately.  When this happens, both
2616     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2617     * so that both elements reappear at the same time.
2618     *
2619     * @see #setSystemUiVisibility(int)
2620     */
2621    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2622
2623    /**
2624     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2625     * into the normal fullscreen mode so that its content can take over the screen
2626     * while still allowing the user to interact with the application.
2627     *
2628     * <p>This has the same visual effect as
2629     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2630     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2631     * meaning that non-critical screen decorations (such as the status bar) will be
2632     * hidden while the user is in the View's window, focusing the experience on
2633     * that content.  Unlike the window flag, if you are using ActionBar in
2634     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2635     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2636     * hide the action bar.
2637     *
2638     * <p>This approach to going fullscreen is best used over the window flag when
2639     * it is a transient state -- that is, the application does this at certain
2640     * points in its user interaction where it wants to allow the user to focus
2641     * on content, but not as a continuous state.  For situations where the application
2642     * would like to simply stay full screen the entire time (such as a game that
2643     * wants to take over the screen), the
2644     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2645     * is usually a better approach.  The state set here will be removed by the system
2646     * in various situations (such as the user moving to another application) like
2647     * the other system UI states.
2648     *
2649     * <p>When using this flag, the application should provide some easy facility
2650     * for the user to go out of it.  A common example would be in an e-book
2651     * reader, where tapping on the screen brings back whatever screen and UI
2652     * decorations that had been hidden while the user was immersed in reading
2653     * the book.
2654     *
2655     * @see #setSystemUiVisibility(int)
2656     */
2657    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2658
2659    /**
2660     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2661     * flags, we would like a stable view of the content insets given to
2662     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2663     * will always represent the worst case that the application can expect
2664     * as a continuous state.  In the stock Android UI this is the space for
2665     * the system bar, nav bar, and status bar, but not more transient elements
2666     * such as an input method.
2667     *
2668     * The stable layout your UI sees is based on the system UI modes you can
2669     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2670     * then you will get a stable layout for changes of the
2671     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2672     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2673     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2674     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2675     * with a stable layout.  (Note that you should avoid using
2676     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2677     *
2678     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2679     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2680     * then a hidden status bar will be considered a "stable" state for purposes
2681     * here.  This allows your UI to continually hide the status bar, while still
2682     * using the system UI flags to hide the action bar while still retaining
2683     * a stable layout.  Note that changing the window fullscreen flag will never
2684     * provide a stable layout for a clean transition.
2685     *
2686     * <p>If you are using ActionBar in
2687     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2688     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2689     * insets it adds to those given to the application.
2690     */
2691    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2692
2693    /**
2694     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2695     * to be laid out as if it has requested
2696     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2697     * allows it to avoid artifacts when switching in and out of that mode, at
2698     * the expense that some of its user interface may be covered by screen
2699     * decorations when they are shown.  You can perform layout of your inner
2700     * UI elements to account for the navigation system UI through the
2701     * {@link #fitSystemWindows(Rect)} method.
2702     */
2703    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2704
2705    /**
2706     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2707     * to be laid out as if it has requested
2708     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2709     * allows it to avoid artifacts when switching in and out of that mode, at
2710     * the expense that some of its user interface may be covered by screen
2711     * decorations when they are shown.  You can perform layout of your inner
2712     * UI elements to account for non-fullscreen system UI through the
2713     * {@link #fitSystemWindows(Rect)} method.
2714     */
2715    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2716
2717    /**
2718     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2719     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2720     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2721     * user interaction.
2722     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2723     * has an effect when used in combination with that flag.</p>
2724     */
2725    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2726
2727    /**
2728     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2729     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2730     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2731     * experience while also hiding the system bars.  If this flag is not set,
2732     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2733     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2734     * if the user swipes from the top of the screen.
2735     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2736     * system gestures, such as swiping from the top of the screen.  These transient system bars
2737     * will overlay app’s content, may have some degree of transparency, and will automatically
2738     * hide after a short timeout.
2739     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2740     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2741     * with one or both of those flags.</p>
2742     */
2743    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2744
2745    /**
2746     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2747     * is compatible with light status bar backgrounds.
2748     *
2749     * <p>For this to take effect, the window must request
2750     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2751     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2752     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2753     *         FLAG_TRANSLUCENT_STATUS}.
2754     *
2755     * @see android.R.attr#windowLightStatusBar
2756     */
2757    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2758
2759    /**
2760     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2761     */
2762    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2763
2764    /**
2765     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2766     */
2767    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2768
2769    /**
2770     * @hide
2771     *
2772     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2773     * out of the public fields to keep the undefined bits out of the developer's way.
2774     *
2775     * Flag to make the status bar not expandable.  Unless you also
2776     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2777     */
2778    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2779
2780    /**
2781     * @hide
2782     *
2783     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2784     * out of the public fields to keep the undefined bits out of the developer's way.
2785     *
2786     * Flag to hide notification icons and scrolling ticker text.
2787     */
2788    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2789
2790    /**
2791     * @hide
2792     *
2793     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2794     * out of the public fields to keep the undefined bits out of the developer's way.
2795     *
2796     * Flag to disable incoming notification alerts.  This will not block
2797     * icons, but it will block sound, vibrating and other visual or aural notifications.
2798     */
2799    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2800
2801    /**
2802     * @hide
2803     *
2804     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2805     * out of the public fields to keep the undefined bits out of the developer's way.
2806     *
2807     * Flag to hide only the scrolling ticker.  Note that
2808     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2809     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2810     */
2811    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2812
2813    /**
2814     * @hide
2815     *
2816     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2817     * out of the public fields to keep the undefined bits out of the developer's way.
2818     *
2819     * Flag to hide the center system info area.
2820     */
2821    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2822
2823    /**
2824     * @hide
2825     *
2826     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2827     * out of the public fields to keep the undefined bits out of the developer's way.
2828     *
2829     * Flag to hide only the home button.  Don't use this
2830     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2831     */
2832    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2833
2834    /**
2835     * @hide
2836     *
2837     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2838     * out of the public fields to keep the undefined bits out of the developer's way.
2839     *
2840     * Flag to hide only the back button. Don't use this
2841     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2842     */
2843    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2844
2845    /**
2846     * @hide
2847     *
2848     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2849     * out of the public fields to keep the undefined bits out of the developer's way.
2850     *
2851     * Flag to hide only the clock.  You might use this if your activity has
2852     * its own clock making the status bar's clock redundant.
2853     */
2854    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2855
2856    /**
2857     * @hide
2858     *
2859     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2860     * out of the public fields to keep the undefined bits out of the developer's way.
2861     *
2862     * Flag to hide only the recent apps button. Don't use this
2863     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2864     */
2865    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2866
2867    /**
2868     * @hide
2869     *
2870     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2871     * out of the public fields to keep the undefined bits out of the developer's way.
2872     *
2873     * Flag to disable the global search gesture. Don't use this
2874     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2875     */
2876    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2877
2878    /**
2879     * @hide
2880     *
2881     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2882     * out of the public fields to keep the undefined bits out of the developer's way.
2883     *
2884     * Flag to specify that the status bar is displayed in transient mode.
2885     */
2886    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2887
2888    /**
2889     * @hide
2890     *
2891     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2892     * out of the public fields to keep the undefined bits out of the developer's way.
2893     *
2894     * Flag to specify that the navigation bar is displayed in transient mode.
2895     */
2896    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2897
2898    /**
2899     * @hide
2900     *
2901     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2902     * out of the public fields to keep the undefined bits out of the developer's way.
2903     *
2904     * Flag to specify that the hidden status bar would like to be shown.
2905     */
2906    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2907
2908    /**
2909     * @hide
2910     *
2911     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2912     * out of the public fields to keep the undefined bits out of the developer's way.
2913     *
2914     * Flag to specify that the hidden navigation bar would like to be shown.
2915     */
2916    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
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 specify that the status bar is displayed in translucent mode.
2925     */
2926    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2927
2928    /**
2929     * @hide
2930     *
2931     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2932     * out of the public fields to keep the undefined bits out of the developer's way.
2933     *
2934     * Flag to specify that the navigation bar is displayed in translucent mode.
2935     */
2936    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2937
2938    /**
2939     * @hide
2940     *
2941     * Whether Recents is visible or not.
2942     */
2943    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2944
2945    /**
2946     * @hide
2947     *
2948     * Makes system ui transparent.
2949     */
2950    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2951
2952    /**
2953     * @hide
2954     */
2955    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2956
2957    /**
2958     * These are the system UI flags that can be cleared by events outside
2959     * of an application.  Currently this is just the ability to tap on the
2960     * screen while hiding the navigation bar to have it return.
2961     * @hide
2962     */
2963    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2964            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2965            | SYSTEM_UI_FLAG_FULLSCREEN;
2966
2967    /**
2968     * Flags that can impact the layout in relation to system UI.
2969     */
2970    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2971            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2972            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2973
2974    /** @hide */
2975    @IntDef(flag = true,
2976            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2977    @Retention(RetentionPolicy.SOURCE)
2978    public @interface FindViewFlags {}
2979
2980    /**
2981     * Find views that render the specified text.
2982     *
2983     * @see #findViewsWithText(ArrayList, CharSequence, int)
2984     */
2985    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2986
2987    /**
2988     * Find find views that contain the specified content description.
2989     *
2990     * @see #findViewsWithText(ArrayList, CharSequence, int)
2991     */
2992    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2993
2994    /**
2995     * Find views that contain {@link AccessibilityNodeProvider}. Such
2996     * a View is a root of virtual view hierarchy and may contain the searched
2997     * text. If this flag is set Views with providers are automatically
2998     * added and it is a responsibility of the client to call the APIs of
2999     * the provider to determine whether the virtual tree rooted at this View
3000     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3001     * representing the virtual views with this text.
3002     *
3003     * @see #findViewsWithText(ArrayList, CharSequence, int)
3004     *
3005     * @hide
3006     */
3007    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3008
3009    /**
3010     * The undefined cursor position.
3011     *
3012     * @hide
3013     */
3014    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3015
3016    /**
3017     * Indicates that the screen has changed state and is now off.
3018     *
3019     * @see #onScreenStateChanged(int)
3020     */
3021    public static final int SCREEN_STATE_OFF = 0x0;
3022
3023    /**
3024     * Indicates that the screen has changed state and is now on.
3025     *
3026     * @see #onScreenStateChanged(int)
3027     */
3028    public static final int SCREEN_STATE_ON = 0x1;
3029
3030    /**
3031     * Indicates no axis of view scrolling.
3032     */
3033    public static final int SCROLL_AXIS_NONE = 0;
3034
3035    /**
3036     * Indicates scrolling along the horizontal axis.
3037     */
3038    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3039
3040    /**
3041     * Indicates scrolling along the vertical axis.
3042     */
3043    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3044
3045    /**
3046     * Controls the over-scroll mode for this view.
3047     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3048     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3049     * and {@link #OVER_SCROLL_NEVER}.
3050     */
3051    private int mOverScrollMode;
3052
3053    /**
3054     * The parent this view is attached to.
3055     * {@hide}
3056     *
3057     * @see #getParent()
3058     */
3059    protected ViewParent mParent;
3060
3061    /**
3062     * {@hide}
3063     */
3064    AttachInfo mAttachInfo;
3065
3066    /**
3067     * {@hide}
3068     */
3069    @ViewDebug.ExportedProperty(flagMapping = {
3070        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3071                name = "FORCE_LAYOUT"),
3072        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3073                name = "LAYOUT_REQUIRED"),
3074        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3075            name = "DRAWING_CACHE_INVALID", outputIf = false),
3076        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3077        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3078        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3079        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3080    }, formatToHexString = true)
3081    int mPrivateFlags;
3082    int mPrivateFlags2;
3083    int mPrivateFlags3;
3084
3085    /**
3086     * This view's request for the visibility of the status bar.
3087     * @hide
3088     */
3089    @ViewDebug.ExportedProperty(flagMapping = {
3090        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3091                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3092                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3093        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3094                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3095                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3096        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3097                                equals = SYSTEM_UI_FLAG_VISIBLE,
3098                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3099    }, formatToHexString = true)
3100    int mSystemUiVisibility;
3101
3102    /**
3103     * Reference count for transient state.
3104     * @see #setHasTransientState(boolean)
3105     */
3106    int mTransientStateCount = 0;
3107
3108    /**
3109     * Count of how many windows this view has been attached to.
3110     */
3111    int mWindowAttachCount;
3112
3113    /**
3114     * The layout parameters associated with this view and used by the parent
3115     * {@link android.view.ViewGroup} to determine how this view should be
3116     * laid out.
3117     * {@hide}
3118     */
3119    protected ViewGroup.LayoutParams mLayoutParams;
3120
3121    /**
3122     * The view flags hold various views states.
3123     * {@hide}
3124     */
3125    @ViewDebug.ExportedProperty(formatToHexString = true)
3126    int mViewFlags;
3127
3128    static class TransformationInfo {
3129        /**
3130         * The transform matrix for the View. This transform is calculated internally
3131         * based on the translation, rotation, and scale properties.
3132         *
3133         * Do *not* use this variable directly; instead call getMatrix(), which will
3134         * load the value from the View's RenderNode.
3135         */
3136        private final Matrix mMatrix = new Matrix();
3137
3138        /**
3139         * The inverse transform matrix for the View. This transform is calculated
3140         * internally based on the translation, rotation, and scale properties.
3141         *
3142         * Do *not* use this variable directly; instead call getInverseMatrix(),
3143         * which will load the value from the View's RenderNode.
3144         */
3145        private Matrix mInverseMatrix;
3146
3147        /**
3148         * The opacity of the View. This is a value from 0 to 1, where 0 means
3149         * completely transparent and 1 means completely opaque.
3150         */
3151        @ViewDebug.ExportedProperty
3152        float mAlpha = 1f;
3153
3154        /**
3155         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3156         * property only used by transitions, which is composited with the other alpha
3157         * values to calculate the final visual alpha value.
3158         */
3159        float mTransitionAlpha = 1f;
3160    }
3161
3162    TransformationInfo mTransformationInfo;
3163
3164    /**
3165     * Current clip bounds. to which all drawing of this view are constrained.
3166     */
3167    Rect mClipBounds = null;
3168
3169    private boolean mLastIsOpaque;
3170
3171    /**
3172     * The distance in pixels from the left edge of this view's parent
3173     * to the left edge of this view.
3174     * {@hide}
3175     */
3176    @ViewDebug.ExportedProperty(category = "layout")
3177    protected int mLeft;
3178    /**
3179     * The distance in pixels from the left edge of this view's parent
3180     * to the right edge of this view.
3181     * {@hide}
3182     */
3183    @ViewDebug.ExportedProperty(category = "layout")
3184    protected int mRight;
3185    /**
3186     * The distance in pixels from the top edge of this view's parent
3187     * to the top edge of this view.
3188     * {@hide}
3189     */
3190    @ViewDebug.ExportedProperty(category = "layout")
3191    protected int mTop;
3192    /**
3193     * The distance in pixels from the top edge of this view's parent
3194     * to the bottom edge of this view.
3195     * {@hide}
3196     */
3197    @ViewDebug.ExportedProperty(category = "layout")
3198    protected int mBottom;
3199
3200    /**
3201     * The offset, in pixels, by which the content of this view is scrolled
3202     * horizontally.
3203     * {@hide}
3204     */
3205    @ViewDebug.ExportedProperty(category = "scrolling")
3206    protected int mScrollX;
3207    /**
3208     * The offset, in pixels, by which the content of this view is scrolled
3209     * vertically.
3210     * {@hide}
3211     */
3212    @ViewDebug.ExportedProperty(category = "scrolling")
3213    protected int mScrollY;
3214
3215    /**
3216     * The left padding in pixels, that is the distance in pixels between the
3217     * left edge of this view and the left edge of its content.
3218     * {@hide}
3219     */
3220    @ViewDebug.ExportedProperty(category = "padding")
3221    protected int mPaddingLeft = 0;
3222    /**
3223     * The right padding in pixels, that is the distance in pixels between the
3224     * right edge of this view and the right edge of its content.
3225     * {@hide}
3226     */
3227    @ViewDebug.ExportedProperty(category = "padding")
3228    protected int mPaddingRight = 0;
3229    /**
3230     * The top padding in pixels, that is the distance in pixels between the
3231     * top edge of this view and the top edge of its content.
3232     * {@hide}
3233     */
3234    @ViewDebug.ExportedProperty(category = "padding")
3235    protected int mPaddingTop;
3236    /**
3237     * The bottom padding in pixels, that is the distance in pixels between the
3238     * bottom edge of this view and the bottom edge of its content.
3239     * {@hide}
3240     */
3241    @ViewDebug.ExportedProperty(category = "padding")
3242    protected int mPaddingBottom;
3243
3244    /**
3245     * The layout insets in pixels, that is the distance in pixels between the
3246     * visible edges of this view its bounds.
3247     */
3248    private Insets mLayoutInsets;
3249
3250    /**
3251     * Briefly describes the view and is primarily used for accessibility support.
3252     */
3253    private CharSequence mContentDescription;
3254
3255    /**
3256     * Specifies the id of a view for which this view serves as a label for
3257     * accessibility purposes.
3258     */
3259    private int mLabelForId = View.NO_ID;
3260
3261    /**
3262     * Predicate for matching labeled view id with its label for
3263     * accessibility purposes.
3264     */
3265    private MatchLabelForPredicate mMatchLabelForPredicate;
3266
3267    /**
3268     * Specifies a view before which this one is visited in accessibility traversal.
3269     */
3270    private int mAccessibilityTraversalBeforeId = NO_ID;
3271
3272    /**
3273     * Specifies a view after which this one is visited in accessibility traversal.
3274     */
3275    private int mAccessibilityTraversalAfterId = NO_ID;
3276
3277    /**
3278     * Predicate for matching a view by its id.
3279     */
3280    private MatchIdPredicate mMatchIdPredicate;
3281
3282    /**
3283     * Cache the paddingRight set by the user to append to the scrollbar's size.
3284     *
3285     * @hide
3286     */
3287    @ViewDebug.ExportedProperty(category = "padding")
3288    protected int mUserPaddingRight;
3289
3290    /**
3291     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3292     *
3293     * @hide
3294     */
3295    @ViewDebug.ExportedProperty(category = "padding")
3296    protected int mUserPaddingBottom;
3297
3298    /**
3299     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3300     *
3301     * @hide
3302     */
3303    @ViewDebug.ExportedProperty(category = "padding")
3304    protected int mUserPaddingLeft;
3305
3306    /**
3307     * Cache the paddingStart set by the user to append to the scrollbar's size.
3308     *
3309     */
3310    @ViewDebug.ExportedProperty(category = "padding")
3311    int mUserPaddingStart;
3312
3313    /**
3314     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3315     *
3316     */
3317    @ViewDebug.ExportedProperty(category = "padding")
3318    int mUserPaddingEnd;
3319
3320    /**
3321     * Cache initial left padding.
3322     *
3323     * @hide
3324     */
3325    int mUserPaddingLeftInitial;
3326
3327    /**
3328     * Cache initial right padding.
3329     *
3330     * @hide
3331     */
3332    int mUserPaddingRightInitial;
3333
3334    /**
3335     * Default undefined padding
3336     */
3337    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3338
3339    /**
3340     * Cache if a left padding has been defined
3341     */
3342    private boolean mLeftPaddingDefined = false;
3343
3344    /**
3345     * Cache if a right padding has been defined
3346     */
3347    private boolean mRightPaddingDefined = false;
3348
3349    /**
3350     * @hide
3351     */
3352    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3353    /**
3354     * @hide
3355     */
3356    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3357
3358    private LongSparseLongArray mMeasureCache;
3359
3360    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3361    private Drawable mBackground;
3362    private TintInfo mBackgroundTint;
3363
3364    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3365    private ForegroundInfo mForegroundInfo;
3366
3367    private Drawable mScrollIndicatorDrawable;
3368
3369    /**
3370     * RenderNode used for backgrounds.
3371     * <p>
3372     * When non-null and valid, this is expected to contain an up-to-date copy
3373     * of the background drawable. It is cleared on temporary detach, and reset
3374     * on cleanup.
3375     */
3376    private RenderNode mBackgroundRenderNode;
3377
3378    private int mBackgroundResource;
3379    private boolean mBackgroundSizeChanged;
3380
3381    private String mTransitionName;
3382
3383    static class TintInfo {
3384        ColorStateList mTintList;
3385        PorterDuff.Mode mTintMode;
3386        boolean mHasTintMode;
3387        boolean mHasTintList;
3388    }
3389
3390    private static class ForegroundInfo {
3391        private Drawable mDrawable;
3392        private TintInfo mTintInfo;
3393        private int mGravity = Gravity.FILL;
3394        private boolean mInsidePadding = true;
3395        private boolean mBoundsChanged = true;
3396        private final Rect mSelfBounds = new Rect();
3397        private final Rect mOverlayBounds = new Rect();
3398    }
3399
3400    static class ListenerInfo {
3401        /**
3402         * Listener used to dispatch focus change events.
3403         * This field should be made private, so it is hidden from the SDK.
3404         * {@hide}
3405         */
3406        protected OnFocusChangeListener mOnFocusChangeListener;
3407
3408        /**
3409         * Listeners for layout change events.
3410         */
3411        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3412
3413        protected OnScrollChangeListener mOnScrollChangeListener;
3414
3415        /**
3416         * Listeners for attach events.
3417         */
3418        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3419
3420        /**
3421         * Listener used to dispatch click events.
3422         * This field should be made private, so it is hidden from the SDK.
3423         * {@hide}
3424         */
3425        public OnClickListener mOnClickListener;
3426
3427        /**
3428         * Listener used to dispatch long click events.
3429         * This field should be made private, so it is hidden from the SDK.
3430         * {@hide}
3431         */
3432        protected OnLongClickListener mOnLongClickListener;
3433
3434        /**
3435         * Listener used to dispatch context click events. This field should be made private, so it
3436         * is hidden from the SDK.
3437         * {@hide}
3438         */
3439        protected OnContextClickListener mOnContextClickListener;
3440
3441        /**
3442         * Listener used to build the context menu.
3443         * This field should be made private, so it is hidden from the SDK.
3444         * {@hide}
3445         */
3446        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3447
3448        private OnKeyListener mOnKeyListener;
3449
3450        private OnTouchListener mOnTouchListener;
3451
3452        private OnHoverListener mOnHoverListener;
3453
3454        private OnGenericMotionListener mOnGenericMotionListener;
3455
3456        private OnDragListener mOnDragListener;
3457
3458        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3459
3460        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3461    }
3462
3463    ListenerInfo mListenerInfo;
3464
3465    /**
3466     * The application environment this view lives in.
3467     * This field should be made private, so it is hidden from the SDK.
3468     * {@hide}
3469     */
3470    @ViewDebug.ExportedProperty(deepExport = true)
3471    protected Context mContext;
3472
3473    private final Resources mResources;
3474
3475    private ScrollabilityCache mScrollCache;
3476
3477    private int[] mDrawableState = null;
3478
3479    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3480
3481    /**
3482     * Animator that automatically runs based on state changes.
3483     */
3484    private StateListAnimator mStateListAnimator;
3485
3486    /**
3487     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3488     * the user may specify which view to go to next.
3489     */
3490    private int mNextFocusLeftId = View.NO_ID;
3491
3492    /**
3493     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3494     * the user may specify which view to go to next.
3495     */
3496    private int mNextFocusRightId = View.NO_ID;
3497
3498    /**
3499     * When this view has focus and the next focus is {@link #FOCUS_UP},
3500     * the user may specify which view to go to next.
3501     */
3502    private int mNextFocusUpId = View.NO_ID;
3503
3504    /**
3505     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3506     * the user may specify which view to go to next.
3507     */
3508    private int mNextFocusDownId = View.NO_ID;
3509
3510    /**
3511     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3512     * the user may specify which view to go to next.
3513     */
3514    int mNextFocusForwardId = View.NO_ID;
3515
3516    private CheckForLongPress mPendingCheckForLongPress;
3517    private CheckForTap mPendingCheckForTap = null;
3518    private PerformClick mPerformClick;
3519    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3520
3521    private UnsetPressedState mUnsetPressedState;
3522
3523    /**
3524     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3525     * up event while a long press is invoked as soon as the long press duration is reached, so
3526     * a long press could be performed before the tap is checked, in which case the tap's action
3527     * should not be invoked.
3528     */
3529    private boolean mHasPerformedLongPress;
3530
3531    /**
3532     * Whether a context click button is currently pressed down. This is true when the stylus is
3533     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3534     * pressed. This is false once the button is released or if the stylus has been lifted.
3535     */
3536    private boolean mInContextButtonPress;
3537
3538    /**
3539     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3540     * true after a stylus button press has occured, when the next up event should not be recognized
3541     * as a tap.
3542     */
3543    private boolean mIgnoreNextUpEvent;
3544
3545    /**
3546     * The minimum height of the view. We'll try our best to have the height
3547     * of this view to at least this amount.
3548     */
3549    @ViewDebug.ExportedProperty(category = "measurement")
3550    private int mMinHeight;
3551
3552    /**
3553     * The minimum width of the view. We'll try our best to have the width
3554     * of this view to at least this amount.
3555     */
3556    @ViewDebug.ExportedProperty(category = "measurement")
3557    private int mMinWidth;
3558
3559    /**
3560     * The delegate to handle touch events that are physically in this view
3561     * but should be handled by another view.
3562     */
3563    private TouchDelegate mTouchDelegate = null;
3564
3565    /**
3566     * Solid color to use as a background when creating the drawing cache. Enables
3567     * the cache to use 16 bit bitmaps instead of 32 bit.
3568     */
3569    private int mDrawingCacheBackgroundColor = 0;
3570
3571    /**
3572     * Special tree observer used when mAttachInfo is null.
3573     */
3574    private ViewTreeObserver mFloatingTreeObserver;
3575
3576    /**
3577     * Cache the touch slop from the context that created the view.
3578     */
3579    private int mTouchSlop;
3580
3581    /**
3582     * Object that handles automatic animation of view properties.
3583     */
3584    private ViewPropertyAnimator mAnimator = null;
3585
3586    /**
3587     * Flag indicating that a drag can cross window boundaries.  When
3588     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3589     * with this flag set, all visible applications will be able to participate
3590     * in the drag operation and receive the dragged content.
3591     *
3592     * @hide
3593     */
3594    public static final int DRAG_FLAG_GLOBAL = 1;
3595
3596    /**
3597     * Flag indicating that the drag shadow will be opaque.  When
3598     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3599     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3600     */
3601    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3602
3603    /**
3604     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3605     */
3606    private float mVerticalScrollFactor;
3607
3608    /**
3609     * Position of the vertical scroll bar.
3610     */
3611    private int mVerticalScrollbarPosition;
3612
3613    /**
3614     * Position the scroll bar at the default position as determined by the system.
3615     */
3616    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3617
3618    /**
3619     * Position the scroll bar along the left edge.
3620     */
3621    public static final int SCROLLBAR_POSITION_LEFT = 1;
3622
3623    /**
3624     * Position the scroll bar along the right edge.
3625     */
3626    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3627
3628    /**
3629     * Indicates that the view does not have a layer.
3630     *
3631     * @see #getLayerType()
3632     * @see #setLayerType(int, android.graphics.Paint)
3633     * @see #LAYER_TYPE_SOFTWARE
3634     * @see #LAYER_TYPE_HARDWARE
3635     */
3636    public static final int LAYER_TYPE_NONE = 0;
3637
3638    /**
3639     * <p>Indicates that the view has a software layer. A software layer is backed
3640     * by a bitmap and causes the view to be rendered using Android's software
3641     * rendering pipeline, even if hardware acceleration is enabled.</p>
3642     *
3643     * <p>Software layers have various usages:</p>
3644     * <p>When the application is not using hardware acceleration, a software layer
3645     * is useful to apply a specific color filter and/or blending mode and/or
3646     * translucency to a view and all its children.</p>
3647     * <p>When the application is using hardware acceleration, a software layer
3648     * is useful to render drawing primitives not supported by the hardware
3649     * accelerated pipeline. It can also be used to cache a complex view tree
3650     * into a texture and reduce the complexity of drawing operations. For instance,
3651     * when animating a complex view tree with a translation, a software layer can
3652     * be used to render the view tree only once.</p>
3653     * <p>Software layers should be avoided when the affected view tree updates
3654     * often. Every update will require to re-render the software layer, which can
3655     * potentially be slow (particularly when hardware acceleration is turned on
3656     * since the layer will have to be uploaded into a hardware texture after every
3657     * update.)</p>
3658     *
3659     * @see #getLayerType()
3660     * @see #setLayerType(int, android.graphics.Paint)
3661     * @see #LAYER_TYPE_NONE
3662     * @see #LAYER_TYPE_HARDWARE
3663     */
3664    public static final int LAYER_TYPE_SOFTWARE = 1;
3665
3666    /**
3667     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3668     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3669     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3670     * rendering pipeline, but only if hardware acceleration is turned on for the
3671     * view hierarchy. When hardware acceleration is turned off, hardware layers
3672     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3673     *
3674     * <p>A hardware layer is useful to apply a specific color filter and/or
3675     * blending mode and/or translucency to a view and all its children.</p>
3676     * <p>A hardware layer can be used to cache a complex view tree into a
3677     * texture and reduce the complexity of drawing operations. For instance,
3678     * when animating a complex view tree with a translation, a hardware layer can
3679     * be used to render the view tree only once.</p>
3680     * <p>A hardware layer can also be used to increase the rendering quality when
3681     * rotation transformations are applied on a view. It can also be used to
3682     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3683     *
3684     * @see #getLayerType()
3685     * @see #setLayerType(int, android.graphics.Paint)
3686     * @see #LAYER_TYPE_NONE
3687     * @see #LAYER_TYPE_SOFTWARE
3688     */
3689    public static final int LAYER_TYPE_HARDWARE = 2;
3690
3691    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3692            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3693            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3694            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3695    })
3696    int mLayerType = LAYER_TYPE_NONE;
3697    Paint mLayerPaint;
3698
3699    /**
3700     * Set to true when drawing cache is enabled and cannot be created.
3701     *
3702     * @hide
3703     */
3704    public boolean mCachingFailed;
3705    private Bitmap mDrawingCache;
3706    private Bitmap mUnscaledDrawingCache;
3707
3708    /**
3709     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3710     * <p>
3711     * When non-null and valid, this is expected to contain an up-to-date copy
3712     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3713     * cleanup.
3714     */
3715    final RenderNode mRenderNode;
3716
3717    /**
3718     * Set to true when the view is sending hover accessibility events because it
3719     * is the innermost hovered view.
3720     */
3721    private boolean mSendingHoverAccessibilityEvents;
3722
3723    /**
3724     * Delegate for injecting accessibility functionality.
3725     */
3726    AccessibilityDelegate mAccessibilityDelegate;
3727
3728    /**
3729     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3730     * and add/remove objects to/from the overlay directly through the Overlay methods.
3731     */
3732    ViewOverlay mOverlay;
3733
3734    /**
3735     * The currently active parent view for receiving delegated nested scrolling events.
3736     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3737     * by {@link #stopNestedScroll()} at the same point where we clear
3738     * requestDisallowInterceptTouchEvent.
3739     */
3740    private ViewParent mNestedScrollingParent;
3741
3742    /**
3743     * Consistency verifier for debugging purposes.
3744     * @hide
3745     */
3746    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3747            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3748                    new InputEventConsistencyVerifier(this, 0) : null;
3749
3750    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3751
3752    private int[] mTempNestedScrollConsumed;
3753
3754    /**
3755     * An overlay is going to draw this View instead of being drawn as part of this
3756     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3757     * when this view is invalidated.
3758     */
3759    GhostView mGhostView;
3760
3761    /**
3762     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3763     * @hide
3764     */
3765    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3766    public String[] mAttributes;
3767
3768    /**
3769     * Maps a Resource id to its name.
3770     */
3771    private static SparseArray<String> mAttributeMap;
3772
3773    /**
3774     * @hide
3775     */
3776    String mStartActivityRequestWho;
3777
3778    /**
3779     * Simple constructor to use when creating a view from code.
3780     *
3781     * @param context The Context the view is running in, through which it can
3782     *        access the current theme, resources, etc.
3783     */
3784    public View(Context context) {
3785        mContext = context;
3786        mResources = context != null ? context.getResources() : null;
3787        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3788        // Set some flags defaults
3789        mPrivateFlags2 =
3790                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3791                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3792                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3793                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3794                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3795                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3796        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3797        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3798        mUserPaddingStart = UNDEFINED_PADDING;
3799        mUserPaddingEnd = UNDEFINED_PADDING;
3800        mRenderNode = RenderNode.create(getClass().getName(), this);
3801
3802        if (!sCompatibilityDone && context != null) {
3803            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3804
3805            // Older apps may need this compatibility hack for measurement.
3806            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3807
3808            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3809            // of whether a layout was requested on that View.
3810            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3811
3812            Canvas.sCompatibilityRestore = targetSdkVersion < MNC;
3813
3814            // In MNC and newer, our widgets can pass a "hint" value in the size
3815            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
3816            // know what the expected parent size is going to be, so e.g. list items can size
3817            // themselves at 1/3 the size of their container. It breaks older apps though,
3818            // specifically apps that use some popular open source libraries.
3819            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < MNC;
3820
3821            sCompatibilityDone = true;
3822        }
3823    }
3824
3825    /**
3826     * Constructor that is called when inflating a view from XML. This is called
3827     * when a view is being constructed from an XML file, supplying attributes
3828     * that were specified in the XML file. This version uses a default style of
3829     * 0, so the only attribute values applied are those in the Context's Theme
3830     * and the given AttributeSet.
3831     *
3832     * <p>
3833     * The method onFinishInflate() will be called after all children have been
3834     * added.
3835     *
3836     * @param context The Context the view is running in, through which it can
3837     *        access the current theme, resources, etc.
3838     * @param attrs The attributes of the XML tag that is inflating the view.
3839     * @see #View(Context, AttributeSet, int)
3840     */
3841    public View(Context context, @Nullable AttributeSet attrs) {
3842        this(context, attrs, 0);
3843    }
3844
3845    /**
3846     * Perform inflation from XML and apply a class-specific base style from a
3847     * theme attribute. This constructor of View allows subclasses to use their
3848     * own base style when they are inflating. For example, a Button class's
3849     * constructor would call this version of the super class constructor and
3850     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3851     * allows the theme's button style to modify all of the base view attributes
3852     * (in particular its background) as well as the Button class's attributes.
3853     *
3854     * @param context The Context the view is running in, through which it can
3855     *        access the current theme, resources, etc.
3856     * @param attrs The attributes of the XML tag that is inflating the view.
3857     * @param defStyleAttr An attribute in the current theme that contains a
3858     *        reference to a style resource that supplies default values for
3859     *        the view. Can be 0 to not look for defaults.
3860     * @see #View(Context, AttributeSet)
3861     */
3862    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
3863        this(context, attrs, defStyleAttr, 0);
3864    }
3865
3866    /**
3867     * Perform inflation from XML and apply a class-specific base style from a
3868     * theme attribute or style resource. This constructor of View allows
3869     * subclasses to use their own base style when they are inflating.
3870     * <p>
3871     * When determining the final value of a particular attribute, there are
3872     * four inputs that come into play:
3873     * <ol>
3874     * <li>Any attribute values in the given AttributeSet.
3875     * <li>The style resource specified in the AttributeSet (named "style").
3876     * <li>The default style specified by <var>defStyleAttr</var>.
3877     * <li>The default style specified by <var>defStyleRes</var>.
3878     * <li>The base values in this theme.
3879     * </ol>
3880     * <p>
3881     * Each of these inputs is considered in-order, with the first listed taking
3882     * precedence over the following ones. In other words, if in the
3883     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3884     * , then the button's text will <em>always</em> be black, regardless of
3885     * what is specified in any of the styles.
3886     *
3887     * @param context The Context the view is running in, through which it can
3888     *        access the current theme, resources, etc.
3889     * @param attrs The attributes of the XML tag that is inflating the view.
3890     * @param defStyleAttr An attribute in the current theme that contains a
3891     *        reference to a style resource that supplies default values for
3892     *        the view. Can be 0 to not look for defaults.
3893     * @param defStyleRes A resource identifier of a style resource that
3894     *        supplies default values for the view, used only if
3895     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3896     *        to not look for defaults.
3897     * @see #View(Context, AttributeSet, int)
3898     */
3899    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3900        this(context);
3901
3902        final TypedArray a = context.obtainStyledAttributes(
3903                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3904
3905        if (mDebugViewAttributes) {
3906            saveAttributeData(attrs, a);
3907        }
3908
3909        Drawable background = null;
3910
3911        int leftPadding = -1;
3912        int topPadding = -1;
3913        int rightPadding = -1;
3914        int bottomPadding = -1;
3915        int startPadding = UNDEFINED_PADDING;
3916        int endPadding = UNDEFINED_PADDING;
3917
3918        int padding = -1;
3919
3920        int viewFlagValues = 0;
3921        int viewFlagMasks = 0;
3922
3923        boolean setScrollContainer = false;
3924
3925        int x = 0;
3926        int y = 0;
3927
3928        float tx = 0;
3929        float ty = 0;
3930        float tz = 0;
3931        float elevation = 0;
3932        float rotation = 0;
3933        float rotationX = 0;
3934        float rotationY = 0;
3935        float sx = 1f;
3936        float sy = 1f;
3937        boolean transformSet = false;
3938
3939        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3940        int overScrollMode = mOverScrollMode;
3941        boolean initializeScrollbars = false;
3942        boolean initializeScrollIndicators = false;
3943
3944        boolean startPaddingDefined = false;
3945        boolean endPaddingDefined = false;
3946        boolean leftPaddingDefined = false;
3947        boolean rightPaddingDefined = false;
3948
3949        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3950
3951        final int N = a.getIndexCount();
3952        for (int i = 0; i < N; i++) {
3953            int attr = a.getIndex(i);
3954            switch (attr) {
3955                case com.android.internal.R.styleable.View_background:
3956                    background = a.getDrawable(attr);
3957                    break;
3958                case com.android.internal.R.styleable.View_padding:
3959                    padding = a.getDimensionPixelSize(attr, -1);
3960                    mUserPaddingLeftInitial = padding;
3961                    mUserPaddingRightInitial = padding;
3962                    leftPaddingDefined = true;
3963                    rightPaddingDefined = true;
3964                    break;
3965                 case com.android.internal.R.styleable.View_paddingLeft:
3966                    leftPadding = a.getDimensionPixelSize(attr, -1);
3967                    mUserPaddingLeftInitial = leftPadding;
3968                    leftPaddingDefined = true;
3969                    break;
3970                case com.android.internal.R.styleable.View_paddingTop:
3971                    topPadding = a.getDimensionPixelSize(attr, -1);
3972                    break;
3973                case com.android.internal.R.styleable.View_paddingRight:
3974                    rightPadding = a.getDimensionPixelSize(attr, -1);
3975                    mUserPaddingRightInitial = rightPadding;
3976                    rightPaddingDefined = true;
3977                    break;
3978                case com.android.internal.R.styleable.View_paddingBottom:
3979                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3980                    break;
3981                case com.android.internal.R.styleable.View_paddingStart:
3982                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3983                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3984                    break;
3985                case com.android.internal.R.styleable.View_paddingEnd:
3986                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3987                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3988                    break;
3989                case com.android.internal.R.styleable.View_scrollX:
3990                    x = a.getDimensionPixelOffset(attr, 0);
3991                    break;
3992                case com.android.internal.R.styleable.View_scrollY:
3993                    y = a.getDimensionPixelOffset(attr, 0);
3994                    break;
3995                case com.android.internal.R.styleable.View_alpha:
3996                    setAlpha(a.getFloat(attr, 1f));
3997                    break;
3998                case com.android.internal.R.styleable.View_transformPivotX:
3999                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4000                    break;
4001                case com.android.internal.R.styleable.View_transformPivotY:
4002                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4003                    break;
4004                case com.android.internal.R.styleable.View_translationX:
4005                    tx = a.getDimensionPixelOffset(attr, 0);
4006                    transformSet = true;
4007                    break;
4008                case com.android.internal.R.styleable.View_translationY:
4009                    ty = a.getDimensionPixelOffset(attr, 0);
4010                    transformSet = true;
4011                    break;
4012                case com.android.internal.R.styleable.View_translationZ:
4013                    tz = a.getDimensionPixelOffset(attr, 0);
4014                    transformSet = true;
4015                    break;
4016                case com.android.internal.R.styleable.View_elevation:
4017                    elevation = a.getDimensionPixelOffset(attr, 0);
4018                    transformSet = true;
4019                    break;
4020                case com.android.internal.R.styleable.View_rotation:
4021                    rotation = a.getFloat(attr, 0);
4022                    transformSet = true;
4023                    break;
4024                case com.android.internal.R.styleable.View_rotationX:
4025                    rotationX = a.getFloat(attr, 0);
4026                    transformSet = true;
4027                    break;
4028                case com.android.internal.R.styleable.View_rotationY:
4029                    rotationY = a.getFloat(attr, 0);
4030                    transformSet = true;
4031                    break;
4032                case com.android.internal.R.styleable.View_scaleX:
4033                    sx = a.getFloat(attr, 1f);
4034                    transformSet = true;
4035                    break;
4036                case com.android.internal.R.styleable.View_scaleY:
4037                    sy = a.getFloat(attr, 1f);
4038                    transformSet = true;
4039                    break;
4040                case com.android.internal.R.styleable.View_id:
4041                    mID = a.getResourceId(attr, NO_ID);
4042                    break;
4043                case com.android.internal.R.styleable.View_tag:
4044                    mTag = a.getText(attr);
4045                    break;
4046                case com.android.internal.R.styleable.View_fitsSystemWindows:
4047                    if (a.getBoolean(attr, false)) {
4048                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4049                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4050                    }
4051                    break;
4052                case com.android.internal.R.styleable.View_focusable:
4053                    if (a.getBoolean(attr, false)) {
4054                        viewFlagValues |= FOCUSABLE;
4055                        viewFlagMasks |= FOCUSABLE_MASK;
4056                    }
4057                    break;
4058                case com.android.internal.R.styleable.View_focusableInTouchMode:
4059                    if (a.getBoolean(attr, false)) {
4060                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4061                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4062                    }
4063                    break;
4064                case com.android.internal.R.styleable.View_clickable:
4065                    if (a.getBoolean(attr, false)) {
4066                        viewFlagValues |= CLICKABLE;
4067                        viewFlagMasks |= CLICKABLE;
4068                    }
4069                    break;
4070                case com.android.internal.R.styleable.View_longClickable:
4071                    if (a.getBoolean(attr, false)) {
4072                        viewFlagValues |= LONG_CLICKABLE;
4073                        viewFlagMasks |= LONG_CLICKABLE;
4074                    }
4075                    break;
4076                case com.android.internal.R.styleable.View_contextClickable:
4077                    if (a.getBoolean(attr, false)) {
4078                        viewFlagValues |= CONTEXT_CLICKABLE;
4079                        viewFlagMasks |= CONTEXT_CLICKABLE;
4080                    }
4081                    break;
4082                case com.android.internal.R.styleable.View_saveEnabled:
4083                    if (!a.getBoolean(attr, true)) {
4084                        viewFlagValues |= SAVE_DISABLED;
4085                        viewFlagMasks |= SAVE_DISABLED_MASK;
4086                    }
4087                    break;
4088                case com.android.internal.R.styleable.View_duplicateParentState:
4089                    if (a.getBoolean(attr, false)) {
4090                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4091                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4092                    }
4093                    break;
4094                case com.android.internal.R.styleable.View_visibility:
4095                    final int visibility = a.getInt(attr, 0);
4096                    if (visibility != 0) {
4097                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4098                        viewFlagMasks |= VISIBILITY_MASK;
4099                    }
4100                    break;
4101                case com.android.internal.R.styleable.View_layoutDirection:
4102                    // Clear any layout direction flags (included resolved bits) already set
4103                    mPrivateFlags2 &=
4104                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4105                    // Set the layout direction flags depending on the value of the attribute
4106                    final int layoutDirection = a.getInt(attr, -1);
4107                    final int value = (layoutDirection != -1) ?
4108                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4109                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4110                    break;
4111                case com.android.internal.R.styleable.View_drawingCacheQuality:
4112                    final int cacheQuality = a.getInt(attr, 0);
4113                    if (cacheQuality != 0) {
4114                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4115                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4116                    }
4117                    break;
4118                case com.android.internal.R.styleable.View_contentDescription:
4119                    setContentDescription(a.getString(attr));
4120                    break;
4121                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4122                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4123                    break;
4124                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4125                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4126                    break;
4127                case com.android.internal.R.styleable.View_labelFor:
4128                    setLabelFor(a.getResourceId(attr, NO_ID));
4129                    break;
4130                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4131                    if (!a.getBoolean(attr, true)) {
4132                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4133                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4134                    }
4135                    break;
4136                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4137                    if (!a.getBoolean(attr, true)) {
4138                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4139                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4140                    }
4141                    break;
4142                case R.styleable.View_scrollbars:
4143                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4144                    if (scrollbars != SCROLLBARS_NONE) {
4145                        viewFlagValues |= scrollbars;
4146                        viewFlagMasks |= SCROLLBARS_MASK;
4147                        initializeScrollbars = true;
4148                    }
4149                    break;
4150                //noinspection deprecation
4151                case R.styleable.View_fadingEdge:
4152                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4153                        // Ignore the attribute starting with ICS
4154                        break;
4155                    }
4156                    // With builds < ICS, fall through and apply fading edges
4157                case R.styleable.View_requiresFadingEdge:
4158                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4159                    if (fadingEdge != FADING_EDGE_NONE) {
4160                        viewFlagValues |= fadingEdge;
4161                        viewFlagMasks |= FADING_EDGE_MASK;
4162                        initializeFadingEdgeInternal(a);
4163                    }
4164                    break;
4165                case R.styleable.View_scrollbarStyle:
4166                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4167                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4168                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4169                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4170                    }
4171                    break;
4172                case R.styleable.View_isScrollContainer:
4173                    setScrollContainer = true;
4174                    if (a.getBoolean(attr, false)) {
4175                        setScrollContainer(true);
4176                    }
4177                    break;
4178                case com.android.internal.R.styleable.View_keepScreenOn:
4179                    if (a.getBoolean(attr, false)) {
4180                        viewFlagValues |= KEEP_SCREEN_ON;
4181                        viewFlagMasks |= KEEP_SCREEN_ON;
4182                    }
4183                    break;
4184                case R.styleable.View_filterTouchesWhenObscured:
4185                    if (a.getBoolean(attr, false)) {
4186                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4187                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4188                    }
4189                    break;
4190                case R.styleable.View_nextFocusLeft:
4191                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4192                    break;
4193                case R.styleable.View_nextFocusRight:
4194                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4195                    break;
4196                case R.styleable.View_nextFocusUp:
4197                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4198                    break;
4199                case R.styleable.View_nextFocusDown:
4200                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4201                    break;
4202                case R.styleable.View_nextFocusForward:
4203                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4204                    break;
4205                case R.styleable.View_minWidth:
4206                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4207                    break;
4208                case R.styleable.View_minHeight:
4209                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4210                    break;
4211                case R.styleable.View_onClick:
4212                    if (context.isRestricted()) {
4213                        throw new IllegalStateException("The android:onClick attribute cannot "
4214                                + "be used within a restricted context");
4215                    }
4216
4217                    final String handlerName = a.getString(attr);
4218                    if (handlerName != null) {
4219                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4220                    }
4221                    break;
4222                case R.styleable.View_overScrollMode:
4223                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4224                    break;
4225                case R.styleable.View_verticalScrollbarPosition:
4226                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4227                    break;
4228                case R.styleable.View_layerType:
4229                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4230                    break;
4231                case R.styleable.View_textDirection:
4232                    // Clear any text direction flag already set
4233                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4234                    // Set the text direction flags depending on the value of the attribute
4235                    final int textDirection = a.getInt(attr, -1);
4236                    if (textDirection != -1) {
4237                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4238                    }
4239                    break;
4240                case R.styleable.View_textAlignment:
4241                    // Clear any text alignment flag already set
4242                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4243                    // Set the text alignment flag depending on the value of the attribute
4244                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4245                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4246                    break;
4247                case R.styleable.View_importantForAccessibility:
4248                    setImportantForAccessibility(a.getInt(attr,
4249                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4250                    break;
4251                case R.styleable.View_accessibilityLiveRegion:
4252                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4253                    break;
4254                case R.styleable.View_transitionName:
4255                    setTransitionName(a.getString(attr));
4256                    break;
4257                case R.styleable.View_nestedScrollingEnabled:
4258                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4259                    break;
4260                case R.styleable.View_stateListAnimator:
4261                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4262                            a.getResourceId(attr, 0)));
4263                    break;
4264                case R.styleable.View_backgroundTint:
4265                    // This will get applied later during setBackground().
4266                    if (mBackgroundTint == null) {
4267                        mBackgroundTint = new TintInfo();
4268                    }
4269                    mBackgroundTint.mTintList = a.getColorStateList(
4270                            R.styleable.View_backgroundTint);
4271                    mBackgroundTint.mHasTintList = true;
4272                    break;
4273                case R.styleable.View_backgroundTintMode:
4274                    // This will get applied later during setBackground().
4275                    if (mBackgroundTint == null) {
4276                        mBackgroundTint = new TintInfo();
4277                    }
4278                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4279                            R.styleable.View_backgroundTintMode, -1), null);
4280                    mBackgroundTint.mHasTintMode = true;
4281                    break;
4282                case R.styleable.View_outlineProvider:
4283                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4284                            PROVIDER_BACKGROUND));
4285                    break;
4286                case R.styleable.View_foreground:
4287                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4288                        setForeground(a.getDrawable(attr));
4289                    }
4290                    break;
4291                case R.styleable.View_foregroundGravity:
4292                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4293                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4294                    }
4295                    break;
4296                case R.styleable.View_foregroundTintMode:
4297                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4298                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4299                    }
4300                    break;
4301                case R.styleable.View_foregroundTint:
4302                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4303                        setForegroundTintList(a.getColorStateList(attr));
4304                    }
4305                    break;
4306                case R.styleable.View_foregroundInsidePadding:
4307                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4308                        if (mForegroundInfo == null) {
4309                            mForegroundInfo = new ForegroundInfo();
4310                        }
4311                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4312                                mForegroundInfo.mInsidePadding);
4313                    }
4314                    break;
4315                case R.styleable.View_scrollIndicators:
4316                    final int scrollIndicators =
4317                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4318                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4319                    if (scrollIndicators != 0) {
4320                        mPrivateFlags3 |= scrollIndicators;
4321                        initializeScrollIndicators = true;
4322                    }
4323                    break;
4324            }
4325        }
4326
4327        setOverScrollMode(overScrollMode);
4328
4329        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4330        // the resolved layout direction). Those cached values will be used later during padding
4331        // resolution.
4332        mUserPaddingStart = startPadding;
4333        mUserPaddingEnd = endPadding;
4334
4335        if (background != null) {
4336            setBackground(background);
4337        }
4338
4339        // setBackground above will record that padding is currently provided by the background.
4340        // If we have padding specified via xml, record that here instead and use it.
4341        mLeftPaddingDefined = leftPaddingDefined;
4342        mRightPaddingDefined = rightPaddingDefined;
4343
4344        if (padding >= 0) {
4345            leftPadding = padding;
4346            topPadding = padding;
4347            rightPadding = padding;
4348            bottomPadding = padding;
4349            mUserPaddingLeftInitial = padding;
4350            mUserPaddingRightInitial = padding;
4351        }
4352
4353        if (isRtlCompatibilityMode()) {
4354            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4355            // left / right padding are used if defined (meaning here nothing to do). If they are not
4356            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4357            // start / end and resolve them as left / right (layout direction is not taken into account).
4358            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4359            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4360            // defined.
4361            if (!mLeftPaddingDefined && startPaddingDefined) {
4362                leftPadding = startPadding;
4363            }
4364            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4365            if (!mRightPaddingDefined && endPaddingDefined) {
4366                rightPadding = endPadding;
4367            }
4368            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4369        } else {
4370            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4371            // values defined. Otherwise, left /right values are used.
4372            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4373            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4374            // defined.
4375            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4376
4377            if (mLeftPaddingDefined && !hasRelativePadding) {
4378                mUserPaddingLeftInitial = leftPadding;
4379            }
4380            if (mRightPaddingDefined && !hasRelativePadding) {
4381                mUserPaddingRightInitial = rightPadding;
4382            }
4383        }
4384
4385        internalSetPadding(
4386                mUserPaddingLeftInitial,
4387                topPadding >= 0 ? topPadding : mPaddingTop,
4388                mUserPaddingRightInitial,
4389                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4390
4391        if (viewFlagMasks != 0) {
4392            setFlags(viewFlagValues, viewFlagMasks);
4393        }
4394
4395        if (initializeScrollbars) {
4396            initializeScrollbarsInternal(a);
4397        }
4398
4399        if (initializeScrollIndicators) {
4400            initializeScrollIndicatorsInternal();
4401        }
4402
4403        a.recycle();
4404
4405        // Needs to be called after mViewFlags is set
4406        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4407            recomputePadding();
4408        }
4409
4410        if (x != 0 || y != 0) {
4411            scrollTo(x, y);
4412        }
4413
4414        if (transformSet) {
4415            setTranslationX(tx);
4416            setTranslationY(ty);
4417            setTranslationZ(tz);
4418            setElevation(elevation);
4419            setRotation(rotation);
4420            setRotationX(rotationX);
4421            setRotationY(rotationY);
4422            setScaleX(sx);
4423            setScaleY(sy);
4424        }
4425
4426        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4427            setScrollContainer(true);
4428        }
4429
4430        computeOpaqueFlags();
4431    }
4432
4433    /**
4434     * An implementation of OnClickListener that attempts to lazily load a
4435     * named click handling method from a parent or ancestor context.
4436     */
4437    private static class DeclaredOnClickListener implements OnClickListener {
4438        private final View mHostView;
4439        private final String mMethodName;
4440
4441        private Method mMethod;
4442
4443        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4444            mHostView = hostView;
4445            mMethodName = methodName;
4446        }
4447
4448        @Override
4449        public void onClick(@NonNull View v) {
4450            if (mMethod == null) {
4451                mMethod = resolveMethod(mHostView.getContext(), mMethodName);
4452            }
4453
4454            try {
4455                mMethod.invoke(mHostView.getContext(), v);
4456            } catch (IllegalAccessException e) {
4457                throw new IllegalStateException(
4458                        "Could not execute non-public method for android:onClick", e);
4459            } catch (InvocationTargetException e) {
4460                throw new IllegalStateException(
4461                        "Could not execute method for android:onClick", e);
4462            }
4463        }
4464
4465        @NonNull
4466        private Method resolveMethod(@Nullable Context context, @NonNull String name) {
4467            while (context != null) {
4468                try {
4469                    if (!context.isRestricted()) {
4470                        return context.getClass().getMethod(mMethodName, View.class);
4471                    }
4472                } catch (NoSuchMethodException e) {
4473                    // Failed to find method, keep searching up the hierarchy.
4474                }
4475
4476                if (context instanceof ContextWrapper) {
4477                    context = ((ContextWrapper) context).getBaseContext();
4478                } else {
4479                    // Can't search up the hierarchy, null out and fail.
4480                    context = null;
4481                }
4482            }
4483
4484            final int id = mHostView.getId();
4485            final String idText = id == NO_ID ? "" : " with id '"
4486                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4487            throw new IllegalStateException("Could not find method " + mMethodName
4488                    + "(View) in a parent or ancestor Context for android:onClick "
4489                    + "attribute defined on view " + mHostView.getClass() + idText);
4490        }
4491    }
4492
4493    /**
4494     * Non-public constructor for use in testing
4495     */
4496    View() {
4497        mResources = null;
4498        mRenderNode = RenderNode.create(getClass().getName(), this);
4499    }
4500
4501    private static SparseArray<String> getAttributeMap() {
4502        if (mAttributeMap == null) {
4503            mAttributeMap = new SparseArray<>();
4504        }
4505        return mAttributeMap;
4506    }
4507
4508    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4509        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4510        final int indexCount = t.getIndexCount();
4511        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4512
4513        int i = 0;
4514
4515        // Store raw XML attributes.
4516        for (int j = 0; j < attrsCount; ++j) {
4517            attributes[i] = attrs.getAttributeName(j);
4518            attributes[i + 1] = attrs.getAttributeValue(j);
4519            i += 2;
4520        }
4521
4522        // Store resolved styleable attributes.
4523        final Resources res = t.getResources();
4524        final SparseArray<String> attributeMap = getAttributeMap();
4525        for (int j = 0; j < indexCount; ++j) {
4526            final int index = t.getIndex(j);
4527            if (!t.hasValueOrEmpty(index)) {
4528                // Value is undefined. Skip it.
4529                continue;
4530            }
4531
4532            final int resourceId = t.getResourceId(index, 0);
4533            if (resourceId == 0) {
4534                // Value is not a reference. Skip it.
4535                continue;
4536            }
4537
4538            String resourceName = attributeMap.get(resourceId);
4539            if (resourceName == null) {
4540                try {
4541                    resourceName = res.getResourceName(resourceId);
4542                } catch (Resources.NotFoundException e) {
4543                    resourceName = "0x" + Integer.toHexString(resourceId);
4544                }
4545                attributeMap.put(resourceId, resourceName);
4546            }
4547
4548            attributes[i] = resourceName;
4549            attributes[i + 1] = t.getString(index);
4550            i += 2;
4551        }
4552
4553        // Trim to fit contents.
4554        final String[] trimmed = new String[i];
4555        System.arraycopy(attributes, 0, trimmed, 0, i);
4556        mAttributes = trimmed;
4557    }
4558
4559    public String toString() {
4560        StringBuilder out = new StringBuilder(128);
4561        out.append(getClass().getName());
4562        out.append('{');
4563        out.append(Integer.toHexString(System.identityHashCode(this)));
4564        out.append(' ');
4565        switch (mViewFlags&VISIBILITY_MASK) {
4566            case VISIBLE: out.append('V'); break;
4567            case INVISIBLE: out.append('I'); break;
4568            case GONE: out.append('G'); break;
4569            default: out.append('.'); break;
4570        }
4571        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4572        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4573        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4574        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4575        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4576        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4577        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4578        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4579        out.append(' ');
4580        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4581        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4582        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4583        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4584            out.append('p');
4585        } else {
4586            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4587        }
4588        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4589        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4590        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4591        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4592        out.append(' ');
4593        out.append(mLeft);
4594        out.append(',');
4595        out.append(mTop);
4596        out.append('-');
4597        out.append(mRight);
4598        out.append(',');
4599        out.append(mBottom);
4600        final int id = getId();
4601        if (id != NO_ID) {
4602            out.append(" #");
4603            out.append(Integer.toHexString(id));
4604            final Resources r = mResources;
4605            if (Resources.resourceHasPackage(id) && r != null) {
4606                try {
4607                    String pkgname;
4608                    switch (id&0xff000000) {
4609                        case 0x7f000000:
4610                            pkgname="app";
4611                            break;
4612                        case 0x01000000:
4613                            pkgname="android";
4614                            break;
4615                        default:
4616                            pkgname = r.getResourcePackageName(id);
4617                            break;
4618                    }
4619                    String typename = r.getResourceTypeName(id);
4620                    String entryname = r.getResourceEntryName(id);
4621                    out.append(" ");
4622                    out.append(pkgname);
4623                    out.append(":");
4624                    out.append(typename);
4625                    out.append("/");
4626                    out.append(entryname);
4627                } catch (Resources.NotFoundException e) {
4628                }
4629            }
4630        }
4631        out.append("}");
4632        return out.toString();
4633    }
4634
4635    /**
4636     * <p>
4637     * Initializes the fading edges from a given set of styled attributes. This
4638     * method should be called by subclasses that need fading edges and when an
4639     * instance of these subclasses is created programmatically rather than
4640     * being inflated from XML. This method is automatically called when the XML
4641     * is inflated.
4642     * </p>
4643     *
4644     * @param a the styled attributes set to initialize the fading edges from
4645     *
4646     * @removed
4647     */
4648    protected void initializeFadingEdge(TypedArray a) {
4649        // This method probably shouldn't have been included in the SDK to begin with.
4650        // It relies on 'a' having been initialized using an attribute filter array that is
4651        // not publicly available to the SDK. The old method has been renamed
4652        // to initializeFadingEdgeInternal and hidden for framework use only;
4653        // this one initializes using defaults to make it safe to call for apps.
4654
4655        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4656
4657        initializeFadingEdgeInternal(arr);
4658
4659        arr.recycle();
4660    }
4661
4662    /**
4663     * <p>
4664     * Initializes the fading edges from a given set of styled attributes. This
4665     * method should be called by subclasses that need fading edges and when an
4666     * instance of these subclasses is created programmatically rather than
4667     * being inflated from XML. This method is automatically called when the XML
4668     * is inflated.
4669     * </p>
4670     *
4671     * @param a the styled attributes set to initialize the fading edges from
4672     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4673     */
4674    protected void initializeFadingEdgeInternal(TypedArray a) {
4675        initScrollCache();
4676
4677        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4678                R.styleable.View_fadingEdgeLength,
4679                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4680    }
4681
4682    /**
4683     * Returns the size of the vertical faded edges used to indicate that more
4684     * content in this view is visible.
4685     *
4686     * @return The size in pixels of the vertical faded edge or 0 if vertical
4687     *         faded edges are not enabled for this view.
4688     * @attr ref android.R.styleable#View_fadingEdgeLength
4689     */
4690    public int getVerticalFadingEdgeLength() {
4691        if (isVerticalFadingEdgeEnabled()) {
4692            ScrollabilityCache cache = mScrollCache;
4693            if (cache != null) {
4694                return cache.fadingEdgeLength;
4695            }
4696        }
4697        return 0;
4698    }
4699
4700    /**
4701     * Set the size of the faded edge used to indicate that more content in this
4702     * view is available.  Will not change whether the fading edge is enabled; use
4703     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4704     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4705     * for the vertical or horizontal fading edges.
4706     *
4707     * @param length The size in pixels of the faded edge used to indicate that more
4708     *        content in this view is visible.
4709     */
4710    public void setFadingEdgeLength(int length) {
4711        initScrollCache();
4712        mScrollCache.fadingEdgeLength = length;
4713    }
4714
4715    /**
4716     * Returns the size of the horizontal faded edges used to indicate that more
4717     * content in this view is visible.
4718     *
4719     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4720     *         faded edges are not enabled for this view.
4721     * @attr ref android.R.styleable#View_fadingEdgeLength
4722     */
4723    public int getHorizontalFadingEdgeLength() {
4724        if (isHorizontalFadingEdgeEnabled()) {
4725            ScrollabilityCache cache = mScrollCache;
4726            if (cache != null) {
4727                return cache.fadingEdgeLength;
4728            }
4729        }
4730        return 0;
4731    }
4732
4733    /**
4734     * Returns the width of the vertical scrollbar.
4735     *
4736     * @return The width in pixels of the vertical scrollbar or 0 if there
4737     *         is no vertical scrollbar.
4738     */
4739    public int getVerticalScrollbarWidth() {
4740        ScrollabilityCache cache = mScrollCache;
4741        if (cache != null) {
4742            ScrollBarDrawable scrollBar = cache.scrollBar;
4743            if (scrollBar != null) {
4744                int size = scrollBar.getSize(true);
4745                if (size <= 0) {
4746                    size = cache.scrollBarSize;
4747                }
4748                return size;
4749            }
4750            return 0;
4751        }
4752        return 0;
4753    }
4754
4755    /**
4756     * Returns the height of the horizontal scrollbar.
4757     *
4758     * @return The height in pixels of the horizontal scrollbar or 0 if
4759     *         there is no horizontal scrollbar.
4760     */
4761    protected int getHorizontalScrollbarHeight() {
4762        ScrollabilityCache cache = mScrollCache;
4763        if (cache != null) {
4764            ScrollBarDrawable scrollBar = cache.scrollBar;
4765            if (scrollBar != null) {
4766                int size = scrollBar.getSize(false);
4767                if (size <= 0) {
4768                    size = cache.scrollBarSize;
4769                }
4770                return size;
4771            }
4772            return 0;
4773        }
4774        return 0;
4775    }
4776
4777    /**
4778     * <p>
4779     * Initializes the scrollbars from a given set of styled attributes. This
4780     * method should be called by subclasses that need scrollbars and when an
4781     * instance of these subclasses is created programmatically rather than
4782     * being inflated from XML. This method is automatically called when the XML
4783     * is inflated.
4784     * </p>
4785     *
4786     * @param a the styled attributes set to initialize the scrollbars from
4787     *
4788     * @removed
4789     */
4790    protected void initializeScrollbars(TypedArray a) {
4791        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4792        // using the View filter array which is not available to the SDK. As such, internal
4793        // framework usage now uses initializeScrollbarsInternal and we grab a default
4794        // TypedArray with the right filter instead here.
4795        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4796
4797        initializeScrollbarsInternal(arr);
4798
4799        // We ignored the method parameter. Recycle the one we actually did use.
4800        arr.recycle();
4801    }
4802
4803    /**
4804     * <p>
4805     * Initializes the scrollbars from a given set of styled attributes. This
4806     * method should be called by subclasses that need scrollbars and when an
4807     * instance of these subclasses is created programmatically rather than
4808     * being inflated from XML. This method is automatically called when the XML
4809     * is inflated.
4810     * </p>
4811     *
4812     * @param a the styled attributes set to initialize the scrollbars from
4813     * @hide
4814     */
4815    protected void initializeScrollbarsInternal(TypedArray a) {
4816        initScrollCache();
4817
4818        final ScrollabilityCache scrollabilityCache = mScrollCache;
4819
4820        if (scrollabilityCache.scrollBar == null) {
4821            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4822            scrollabilityCache.scrollBar.setCallback(this);
4823            scrollabilityCache.scrollBar.setState(getDrawableState());
4824        }
4825
4826        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4827
4828        if (!fadeScrollbars) {
4829            scrollabilityCache.state = ScrollabilityCache.ON;
4830        }
4831        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4832
4833
4834        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4835                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4836                        .getScrollBarFadeDuration());
4837        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4838                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4839                ViewConfiguration.getScrollDefaultDelay());
4840
4841
4842        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4843                com.android.internal.R.styleable.View_scrollbarSize,
4844                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4845
4846        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4847        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4848
4849        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4850        if (thumb != null) {
4851            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4852        }
4853
4854        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4855                false);
4856        if (alwaysDraw) {
4857            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4858        }
4859
4860        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4861        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4862
4863        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4864        if (thumb != null) {
4865            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4866        }
4867
4868        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4869                false);
4870        if (alwaysDraw) {
4871            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4872        }
4873
4874        // Apply layout direction to the new Drawables if needed
4875        final int layoutDirection = getLayoutDirection();
4876        if (track != null) {
4877            track.setLayoutDirection(layoutDirection);
4878        }
4879        if (thumb != null) {
4880            thumb.setLayoutDirection(layoutDirection);
4881        }
4882
4883        // Re-apply user/background padding so that scrollbar(s) get added
4884        resolvePadding();
4885    }
4886
4887    private void initializeScrollIndicatorsInternal() {
4888        // Some day maybe we'll break this into top/left/start/etc. and let the
4889        // client control it. Until then, you can have any scroll indicator you
4890        // want as long as it's a 1dp foreground-colored rectangle.
4891        if (mScrollIndicatorDrawable == null) {
4892            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
4893        }
4894    }
4895
4896    /**
4897     * <p>
4898     * Initalizes the scrollability cache if necessary.
4899     * </p>
4900     */
4901    private void initScrollCache() {
4902        if (mScrollCache == null) {
4903            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4904        }
4905    }
4906
4907    private ScrollabilityCache getScrollCache() {
4908        initScrollCache();
4909        return mScrollCache;
4910    }
4911
4912    /**
4913     * Set the position of the vertical scroll bar. Should be one of
4914     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4915     * {@link #SCROLLBAR_POSITION_RIGHT}.
4916     *
4917     * @param position Where the vertical scroll bar should be positioned.
4918     */
4919    public void setVerticalScrollbarPosition(int position) {
4920        if (mVerticalScrollbarPosition != position) {
4921            mVerticalScrollbarPosition = position;
4922            computeOpaqueFlags();
4923            resolvePadding();
4924        }
4925    }
4926
4927    /**
4928     * @return The position where the vertical scroll bar will show, if applicable.
4929     * @see #setVerticalScrollbarPosition(int)
4930     */
4931    public int getVerticalScrollbarPosition() {
4932        return mVerticalScrollbarPosition;
4933    }
4934
4935    /**
4936     * Sets the state of all scroll indicators.
4937     * <p>
4938     * See {@link #setScrollIndicators(int, int)} for usage information.
4939     *
4940     * @param indicators a bitmask of indicators that should be enabled, or
4941     *                   {@code 0} to disable all indicators
4942     * @see #setScrollIndicators(int, int)
4943     * @see #getScrollIndicators()
4944     * @attr ref android.R.styleable#View_scrollIndicators
4945     */
4946    public void setScrollIndicators(@ScrollIndicators int indicators) {
4947        setScrollIndicators(indicators,
4948                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
4949    }
4950
4951    /**
4952     * Sets the state of the scroll indicators specified by the mask. To change
4953     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
4954     * <p>
4955     * When a scroll indicator is enabled, it will be displayed if the view
4956     * can scroll in the direction of the indicator.
4957     * <p>
4958     * Multiple indicator types may be enabled or disabled by passing the
4959     * logical OR of the desired types. If multiple types are specified, they
4960     * will all be set to the same enabled state.
4961     * <p>
4962     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
4963     *
4964     * @param indicators the indicator direction, or the logical OR of multiple
4965     *             indicator directions. One or more of:
4966     *             <ul>
4967     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
4968     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
4969     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
4970     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
4971     *               <li>{@link #SCROLL_INDICATOR_START}</li>
4972     *               <li>{@link #SCROLL_INDICATOR_END}</li>
4973     *             </ul>
4974     * @see #setScrollIndicators(int)
4975     * @see #getScrollIndicators()
4976     * @attr ref android.R.styleable#View_scrollIndicators
4977     */
4978    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
4979        // Shift and sanitize mask.
4980        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
4981        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
4982
4983        // Shift and mask indicators.
4984        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
4985        indicators &= mask;
4986
4987        // Merge with non-masked flags.
4988        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
4989
4990        if (mPrivateFlags3 != updatedFlags) {
4991            mPrivateFlags3 = updatedFlags;
4992
4993            if (indicators != 0) {
4994                initializeScrollIndicatorsInternal();
4995            }
4996            invalidate();
4997        }
4998    }
4999
5000    /**
5001     * Returns a bitmask representing the enabled scroll indicators.
5002     * <p>
5003     * For example, if the top and left scroll indicators are enabled and all
5004     * other indicators are disabled, the return value will be
5005     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5006     * <p>
5007     * To check whether the bottom scroll indicator is enabled, use the value
5008     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5009     *
5010     * @return a bitmask representing the enabled scroll indicators
5011     */
5012    @ScrollIndicators
5013    public int getScrollIndicators() {
5014        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5015                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5016    }
5017
5018    ListenerInfo getListenerInfo() {
5019        if (mListenerInfo != null) {
5020            return mListenerInfo;
5021        }
5022        mListenerInfo = new ListenerInfo();
5023        return mListenerInfo;
5024    }
5025
5026    /**
5027     * Register a callback to be invoked when the scroll X or Y positions of
5028     * this view change.
5029     * <p>
5030     * <b>Note:</b> Some views handle scrolling independently from View and may
5031     * have their own separate listeners for scroll-type events. For example,
5032     * {@link android.widget.ListView ListView} allows clients to register an
5033     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5034     * to listen for changes in list scroll position.
5035     *
5036     * @param l The listener to notify when the scroll X or Y position changes.
5037     * @see android.view.View#getScrollX()
5038     * @see android.view.View#getScrollY()
5039     */
5040    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5041        getListenerInfo().mOnScrollChangeListener = l;
5042    }
5043
5044    /**
5045     * Register a callback to be invoked when focus of this view changed.
5046     *
5047     * @param l The callback that will run.
5048     */
5049    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5050        getListenerInfo().mOnFocusChangeListener = l;
5051    }
5052
5053    /**
5054     * Add a listener that will be called when the bounds of the view change due to
5055     * layout processing.
5056     *
5057     * @param listener The listener that will be called when layout bounds change.
5058     */
5059    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5060        ListenerInfo li = getListenerInfo();
5061        if (li.mOnLayoutChangeListeners == null) {
5062            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5063        }
5064        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5065            li.mOnLayoutChangeListeners.add(listener);
5066        }
5067    }
5068
5069    /**
5070     * Remove a listener for layout changes.
5071     *
5072     * @param listener The listener for layout bounds change.
5073     */
5074    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5075        ListenerInfo li = mListenerInfo;
5076        if (li == null || li.mOnLayoutChangeListeners == null) {
5077            return;
5078        }
5079        li.mOnLayoutChangeListeners.remove(listener);
5080    }
5081
5082    /**
5083     * Add a listener for attach state changes.
5084     *
5085     * This listener will be called whenever this view is attached or detached
5086     * from a window. Remove the listener using
5087     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5088     *
5089     * @param listener Listener to attach
5090     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5091     */
5092    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5093        ListenerInfo li = getListenerInfo();
5094        if (li.mOnAttachStateChangeListeners == null) {
5095            li.mOnAttachStateChangeListeners
5096                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5097        }
5098        li.mOnAttachStateChangeListeners.add(listener);
5099    }
5100
5101    /**
5102     * Remove a listener for attach state changes. The listener will receive no further
5103     * notification of window attach/detach events.
5104     *
5105     * @param listener Listener to remove
5106     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5107     */
5108    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5109        ListenerInfo li = mListenerInfo;
5110        if (li == null || li.mOnAttachStateChangeListeners == null) {
5111            return;
5112        }
5113        li.mOnAttachStateChangeListeners.remove(listener);
5114    }
5115
5116    /**
5117     * Returns the focus-change callback registered for this view.
5118     *
5119     * @return The callback, or null if one is not registered.
5120     */
5121    public OnFocusChangeListener getOnFocusChangeListener() {
5122        ListenerInfo li = mListenerInfo;
5123        return li != null ? li.mOnFocusChangeListener : null;
5124    }
5125
5126    /**
5127     * Register a callback to be invoked when this view is clicked. If this view is not
5128     * clickable, it becomes clickable.
5129     *
5130     * @param l The callback that will run
5131     *
5132     * @see #setClickable(boolean)
5133     */
5134    public void setOnClickListener(@Nullable OnClickListener l) {
5135        if (!isClickable()) {
5136            setClickable(true);
5137        }
5138        getListenerInfo().mOnClickListener = l;
5139    }
5140
5141    /**
5142     * Return whether this view has an attached OnClickListener.  Returns
5143     * true if there is a listener, false if there is none.
5144     */
5145    public boolean hasOnClickListeners() {
5146        ListenerInfo li = mListenerInfo;
5147        return (li != null && li.mOnClickListener != null);
5148    }
5149
5150    /**
5151     * Register a callback to be invoked when this view is clicked and held. If this view is not
5152     * long clickable, it becomes long clickable.
5153     *
5154     * @param l The callback that will run
5155     *
5156     * @see #setLongClickable(boolean)
5157     */
5158    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5159        if (!isLongClickable()) {
5160            setLongClickable(true);
5161        }
5162        getListenerInfo().mOnLongClickListener = l;
5163    }
5164
5165    /**
5166     * Register a callback to be invoked when this view is context clicked. If the view is not
5167     * context clickable, it becomes context clickable.
5168     *
5169     * @param l The callback that will run
5170     * @see #setContextClickable(boolean)
5171     */
5172    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5173        if (!isContextClickable()) {
5174            setContextClickable(true);
5175        }
5176        getListenerInfo().mOnContextClickListener = l;
5177    }
5178
5179    /**
5180     * Register a callback to be invoked when the context menu for this view is
5181     * being built. If this view is not long clickable, it becomes long clickable.
5182     *
5183     * @param l The callback that will run
5184     *
5185     */
5186    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5187        if (!isLongClickable()) {
5188            setLongClickable(true);
5189        }
5190        getListenerInfo().mOnCreateContextMenuListener = l;
5191    }
5192
5193    /**
5194     * Call this view's OnClickListener, if it is defined.  Performs all normal
5195     * actions associated with clicking: reporting accessibility event, playing
5196     * a sound, etc.
5197     *
5198     * @return True there was an assigned OnClickListener that was called, false
5199     *         otherwise is returned.
5200     */
5201    public boolean performClick() {
5202        final boolean result;
5203        final ListenerInfo li = mListenerInfo;
5204        if (li != null && li.mOnClickListener != null) {
5205            playSoundEffect(SoundEffectConstants.CLICK);
5206            li.mOnClickListener.onClick(this);
5207            result = true;
5208        } else {
5209            result = false;
5210        }
5211
5212        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5213        return result;
5214    }
5215
5216    /**
5217     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5218     * this only calls the listener, and does not do any associated clicking
5219     * actions like reporting an accessibility event.
5220     *
5221     * @return True there was an assigned OnClickListener that was called, false
5222     *         otherwise is returned.
5223     */
5224    public boolean callOnClick() {
5225        ListenerInfo li = mListenerInfo;
5226        if (li != null && li.mOnClickListener != null) {
5227            li.mOnClickListener.onClick(this);
5228            return true;
5229        }
5230        return false;
5231    }
5232
5233    /**
5234     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
5235     * OnLongClickListener did not consume the event.
5236     *
5237     * @return True if one of the above receivers consumed the event, false otherwise.
5238     */
5239    public boolean performLongClick() {
5240        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5241
5242        boolean handled = false;
5243        ListenerInfo li = mListenerInfo;
5244        if (li != null && li.mOnLongClickListener != null) {
5245            handled = li.mOnLongClickListener.onLongClick(View.this);
5246        }
5247        if (!handled) {
5248            handled = showContextMenu();
5249        }
5250        if (handled) {
5251            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5252        }
5253        return handled;
5254    }
5255
5256    /**
5257     * Call this view's OnContextClickListener, if it is defined.
5258     *
5259     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5260     *         otherwise.
5261     */
5262    public boolean performContextClick() {
5263        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5264
5265        boolean handled = false;
5266        ListenerInfo li = mListenerInfo;
5267        if (li != null && li.mOnContextClickListener != null) {
5268            handled = li.mOnContextClickListener.onContextClick(View.this);
5269        }
5270        if (handled) {
5271            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5272        }
5273        return handled;
5274    }
5275
5276    /**
5277     * Performs button-related actions during a touch down event.
5278     *
5279     * @param event The event.
5280     * @return True if the down was consumed.
5281     *
5282     * @hide
5283     */
5284    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5285        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&
5286            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5287            showContextMenu(event.getX(), event.getY(), event.getMetaState());
5288            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5289            return true;
5290        }
5291        return false;
5292    }
5293
5294    /**
5295     * Bring up the context menu for this view.
5296     *
5297     * @return Whether a context menu was displayed.
5298     */
5299    public boolean showContextMenu() {
5300        return getParent().showContextMenuForChild(this);
5301    }
5302
5303    /**
5304     * Bring up the context menu for this view, referring to the item under the specified point.
5305     *
5306     * @param x The referenced x coordinate.
5307     * @param y The referenced y coordinate.
5308     * @param metaState The keyboard modifiers that were pressed.
5309     * @return Whether a context menu was displayed.
5310     *
5311     * @hide
5312     */
5313    public boolean showContextMenu(float x, float y, int metaState) {
5314        return showContextMenu();
5315    }
5316
5317    /**
5318     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5319     *
5320     * @param callback Callback that will control the lifecycle of the action mode
5321     * @return The new action mode if it is started, null otherwise
5322     *
5323     * @see ActionMode
5324     * @see #startActionMode(android.view.ActionMode.Callback, int)
5325     */
5326    public ActionMode startActionMode(ActionMode.Callback callback) {
5327        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5328    }
5329
5330    /**
5331     * Start an action mode with the given type.
5332     *
5333     * @param callback Callback that will control the lifecycle of the action mode
5334     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5335     * @return The new action mode if it is started, null otherwise
5336     *
5337     * @see ActionMode
5338     */
5339    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5340        ViewParent parent = getParent();
5341        if (parent == null) return null;
5342        try {
5343            return parent.startActionModeForChild(this, callback, type);
5344        } catch (AbstractMethodError ame) {
5345            // Older implementations of custom views might not implement this.
5346            return parent.startActionModeForChild(this, callback);
5347        }
5348    }
5349
5350    /**
5351     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5352     * Context, creating a unique View identifier to retrieve the result.
5353     *
5354     * @param intent The Intent to be started.
5355     * @param requestCode The request code to use.
5356     * @hide
5357     */
5358    public void startActivityForResult(Intent intent, int requestCode) {
5359        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5360        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5361    }
5362
5363    /**
5364     * If this View corresponds to the calling who, dispatches the activity result.
5365     * @param who The identifier for the targeted View to receive the result.
5366     * @param requestCode The integer request code originally supplied to
5367     *                    startActivityForResult(), allowing you to identify who this
5368     *                    result came from.
5369     * @param resultCode The integer result code returned by the child activity
5370     *                   through its setResult().
5371     * @param data An Intent, which can return result data to the caller
5372     *               (various data can be attached to Intent "extras").
5373     * @return {@code true} if the activity result was dispatched.
5374     * @hide
5375     */
5376    public boolean dispatchActivityResult(
5377            String who, int requestCode, int resultCode, Intent data) {
5378        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5379            onActivityResult(requestCode, resultCode, data);
5380            mStartActivityRequestWho = null;
5381            return true;
5382        }
5383        return false;
5384    }
5385
5386    /**
5387     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5388     *
5389     * @param requestCode The integer request code originally supplied to
5390     *                    startActivityForResult(), allowing you to identify who this
5391     *                    result came from.
5392     * @param resultCode The integer result code returned by the child activity
5393     *                   through its setResult().
5394     * @param data An Intent, which can return result data to the caller
5395     *               (various data can be attached to Intent "extras").
5396     * @hide
5397     */
5398    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5399        // Do nothing.
5400    }
5401
5402    /**
5403     * Register a callback to be invoked when a hardware key is pressed in this view.
5404     * Key presses in software input methods will generally not trigger the methods of
5405     * this listener.
5406     * @param l the key listener to attach to this view
5407     */
5408    public void setOnKeyListener(OnKeyListener l) {
5409        getListenerInfo().mOnKeyListener = l;
5410    }
5411
5412    /**
5413     * Register a callback to be invoked when a touch event is sent to this view.
5414     * @param l the touch listener to attach to this view
5415     */
5416    public void setOnTouchListener(OnTouchListener l) {
5417        getListenerInfo().mOnTouchListener = l;
5418    }
5419
5420    /**
5421     * Register a callback to be invoked when a generic motion event is sent to this view.
5422     * @param l the generic motion listener to attach to this view
5423     */
5424    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5425        getListenerInfo().mOnGenericMotionListener = l;
5426    }
5427
5428    /**
5429     * Register a callback to be invoked when a hover event is sent to this view.
5430     * @param l the hover listener to attach to this view
5431     */
5432    public void setOnHoverListener(OnHoverListener l) {
5433        getListenerInfo().mOnHoverListener = l;
5434    }
5435
5436    /**
5437     * Register a drag event listener callback object for this View. The parameter is
5438     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5439     * View, the system calls the
5440     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5441     * @param l An implementation of {@link android.view.View.OnDragListener}.
5442     */
5443    public void setOnDragListener(OnDragListener l) {
5444        getListenerInfo().mOnDragListener = l;
5445    }
5446
5447    /**
5448     * Give this view focus. This will cause
5449     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5450     *
5451     * Note: this does not check whether this {@link View} should get focus, it just
5452     * gives it focus no matter what.  It should only be called internally by framework
5453     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5454     *
5455     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5456     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5457     *        focus moved when requestFocus() is called. It may not always
5458     *        apply, in which case use the default View.FOCUS_DOWN.
5459     * @param previouslyFocusedRect The rectangle of the view that had focus
5460     *        prior in this View's coordinate system.
5461     */
5462    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5463        if (DBG) {
5464            System.out.println(this + " requestFocus()");
5465        }
5466
5467        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5468            mPrivateFlags |= PFLAG_FOCUSED;
5469
5470            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5471
5472            if (mParent != null) {
5473                mParent.requestChildFocus(this, this);
5474            }
5475
5476            if (mAttachInfo != null) {
5477                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5478            }
5479
5480            onFocusChanged(true, direction, previouslyFocusedRect);
5481            refreshDrawableState();
5482        }
5483    }
5484
5485    /**
5486     * Populates <code>outRect</code> with the hotspot bounds. By default,
5487     * the hotspot bounds are identical to the screen bounds.
5488     *
5489     * @param outRect rect to populate with hotspot bounds
5490     * @hide Only for internal use by views and widgets.
5491     */
5492    public void getHotspotBounds(Rect outRect) {
5493        final Drawable background = getBackground();
5494        if (background != null) {
5495            background.getHotspotBounds(outRect);
5496        } else {
5497            getBoundsOnScreen(outRect);
5498        }
5499    }
5500
5501    /**
5502     * Request that a rectangle of this view be visible on the screen,
5503     * scrolling if necessary just enough.
5504     *
5505     * <p>A View should call this if it maintains some notion of which part
5506     * of its content is interesting.  For example, a text editing view
5507     * should call this when its cursor moves.
5508     *
5509     * @param rectangle The rectangle.
5510     * @return Whether any parent scrolled.
5511     */
5512    public boolean requestRectangleOnScreen(Rect rectangle) {
5513        return requestRectangleOnScreen(rectangle, false);
5514    }
5515
5516    /**
5517     * Request that a rectangle of this view be visible on the screen,
5518     * scrolling if necessary just enough.
5519     *
5520     * <p>A View should call this if it maintains some notion of which part
5521     * of its content is interesting.  For example, a text editing view
5522     * should call this when its cursor moves.
5523     *
5524     * <p>When <code>immediate</code> is set to true, scrolling will not be
5525     * animated.
5526     *
5527     * @param rectangle The rectangle.
5528     * @param immediate True to forbid animated scrolling, false otherwise
5529     * @return Whether any parent scrolled.
5530     */
5531    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5532        if (mParent == null) {
5533            return false;
5534        }
5535
5536        View child = this;
5537
5538        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5539        position.set(rectangle);
5540
5541        ViewParent parent = mParent;
5542        boolean scrolled = false;
5543        while (parent != null) {
5544            rectangle.set((int) position.left, (int) position.top,
5545                    (int) position.right, (int) position.bottom);
5546
5547            scrolled |= parent.requestChildRectangleOnScreen(child,
5548                    rectangle, immediate);
5549
5550            if (!child.hasIdentityMatrix()) {
5551                child.getMatrix().mapRect(position);
5552            }
5553
5554            position.offset(child.mLeft, child.mTop);
5555
5556            if (!(parent instanceof View)) {
5557                break;
5558            }
5559
5560            View parentView = (View) parent;
5561
5562            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5563
5564            child = parentView;
5565            parent = child.getParent();
5566        }
5567
5568        return scrolled;
5569    }
5570
5571    /**
5572     * Called when this view wants to give up focus. If focus is cleared
5573     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5574     * <p>
5575     * <strong>Note:</strong> When a View clears focus the framework is trying
5576     * to give focus to the first focusable View from the top. Hence, if this
5577     * View is the first from the top that can take focus, then all callbacks
5578     * related to clearing focus will be invoked after which the framework will
5579     * give focus to this view.
5580     * </p>
5581     */
5582    public void clearFocus() {
5583        if (DBG) {
5584            System.out.println(this + " clearFocus()");
5585        }
5586
5587        clearFocusInternal(null, true, true);
5588    }
5589
5590    /**
5591     * Clears focus from the view, optionally propagating the change up through
5592     * the parent hierarchy and requesting that the root view place new focus.
5593     *
5594     * @param propagate whether to propagate the change up through the parent
5595     *            hierarchy
5596     * @param refocus when propagate is true, specifies whether to request the
5597     *            root view place new focus
5598     */
5599    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5600        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5601            mPrivateFlags &= ~PFLAG_FOCUSED;
5602
5603            if (propagate && mParent != null) {
5604                mParent.clearChildFocus(this);
5605            }
5606
5607            onFocusChanged(false, 0, null);
5608            refreshDrawableState();
5609
5610            if (propagate && (!refocus || !rootViewRequestFocus())) {
5611                notifyGlobalFocusCleared(this);
5612            }
5613        }
5614    }
5615
5616    void notifyGlobalFocusCleared(View oldFocus) {
5617        if (oldFocus != null && mAttachInfo != null) {
5618            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5619        }
5620    }
5621
5622    boolean rootViewRequestFocus() {
5623        final View root = getRootView();
5624        return root != null && root.requestFocus();
5625    }
5626
5627    /**
5628     * Called internally by the view system when a new view is getting focus.
5629     * This is what clears the old focus.
5630     * <p>
5631     * <b>NOTE:</b> The parent view's focused child must be updated manually
5632     * after calling this method. Otherwise, the view hierarchy may be left in
5633     * an inconstent state.
5634     */
5635    void unFocus(View focused) {
5636        if (DBG) {
5637            System.out.println(this + " unFocus()");
5638        }
5639
5640        clearFocusInternal(focused, false, false);
5641    }
5642
5643    /**
5644     * Returns true if this view has focus itself, or is the ancestor of the
5645     * view that has focus.
5646     *
5647     * @return True if this view has or contains focus, false otherwise.
5648     */
5649    @ViewDebug.ExportedProperty(category = "focus")
5650    public boolean hasFocus() {
5651        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5652    }
5653
5654    /**
5655     * Returns true if this view is focusable or if it contains a reachable View
5656     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5657     * is a View whose parents do not block descendants focus.
5658     *
5659     * Only {@link #VISIBLE} views are considered focusable.
5660     *
5661     * @return True if the view is focusable or if the view contains a focusable
5662     *         View, false otherwise.
5663     *
5664     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5665     * @see ViewGroup#getTouchscreenBlocksFocus()
5666     */
5667    public boolean hasFocusable() {
5668        if (!isFocusableInTouchMode()) {
5669            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5670                final ViewGroup g = (ViewGroup) p;
5671                if (g.shouldBlockFocusForTouchscreen()) {
5672                    return false;
5673                }
5674            }
5675        }
5676        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5677    }
5678
5679    /**
5680     * Called by the view system when the focus state of this view changes.
5681     * When the focus change event is caused by directional navigation, direction
5682     * and previouslyFocusedRect provide insight into where the focus is coming from.
5683     * When overriding, be sure to call up through to the super class so that
5684     * the standard focus handling will occur.
5685     *
5686     * @param gainFocus True if the View has focus; false otherwise.
5687     * @param direction The direction focus has moved when requestFocus()
5688     *                  is called to give this view focus. Values are
5689     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5690     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5691     *                  It may not always apply, in which case use the default.
5692     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5693     *        system, of the previously focused view.  If applicable, this will be
5694     *        passed in as finer grained information about where the focus is coming
5695     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5696     */
5697    @CallSuper
5698    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5699            @Nullable Rect previouslyFocusedRect) {
5700        if (gainFocus) {
5701            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5702        } else {
5703            notifyViewAccessibilityStateChangedIfNeeded(
5704                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5705        }
5706
5707        InputMethodManager imm = InputMethodManager.peekInstance();
5708        if (!gainFocus) {
5709            if (isPressed()) {
5710                setPressed(false);
5711            }
5712            if (imm != null && mAttachInfo != null
5713                    && mAttachInfo.mHasWindowFocus) {
5714                imm.focusOut(this);
5715            }
5716            onFocusLost();
5717        } else if (imm != null && mAttachInfo != null
5718                && mAttachInfo.mHasWindowFocus) {
5719            imm.focusIn(this);
5720        }
5721
5722        invalidate(true);
5723        ListenerInfo li = mListenerInfo;
5724        if (li != null && li.mOnFocusChangeListener != null) {
5725            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5726        }
5727
5728        if (mAttachInfo != null) {
5729            mAttachInfo.mKeyDispatchState.reset(this);
5730        }
5731    }
5732
5733    /**
5734     * Sends an accessibility event of the given type. If accessibility is
5735     * not enabled this method has no effect. The default implementation calls
5736     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5737     * to populate information about the event source (this View), then calls
5738     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5739     * populate the text content of the event source including its descendants,
5740     * and last calls
5741     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5742     * on its parent to request sending of the event to interested parties.
5743     * <p>
5744     * If an {@link AccessibilityDelegate} has been specified via calling
5745     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5746     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5747     * responsible for handling this call.
5748     * </p>
5749     *
5750     * @param eventType The type of the event to send, as defined by several types from
5751     * {@link android.view.accessibility.AccessibilityEvent}, such as
5752     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5753     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5754     *
5755     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5756     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5757     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5758     * @see AccessibilityDelegate
5759     */
5760    public void sendAccessibilityEvent(int eventType) {
5761        if (mAccessibilityDelegate != null) {
5762            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5763        } else {
5764            sendAccessibilityEventInternal(eventType);
5765        }
5766    }
5767
5768    /**
5769     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5770     * {@link AccessibilityEvent} to make an announcement which is related to some
5771     * sort of a context change for which none of the events representing UI transitions
5772     * is a good fit. For example, announcing a new page in a book. If accessibility
5773     * is not enabled this method does nothing.
5774     *
5775     * @param text The announcement text.
5776     */
5777    public void announceForAccessibility(CharSequence text) {
5778        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5779            AccessibilityEvent event = AccessibilityEvent.obtain(
5780                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5781            onInitializeAccessibilityEvent(event);
5782            event.getText().add(text);
5783            event.setContentDescription(null);
5784            mParent.requestSendAccessibilityEvent(this, event);
5785        }
5786    }
5787
5788    /**
5789     * @see #sendAccessibilityEvent(int)
5790     *
5791     * Note: Called from the default {@link AccessibilityDelegate}.
5792     *
5793     * @hide
5794     */
5795    public void sendAccessibilityEventInternal(int eventType) {
5796        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5797            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5798        }
5799    }
5800
5801    /**
5802     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5803     * takes as an argument an empty {@link AccessibilityEvent} and does not
5804     * perform a check whether accessibility is enabled.
5805     * <p>
5806     * If an {@link AccessibilityDelegate} has been specified via calling
5807     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5808     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5809     * is responsible for handling this call.
5810     * </p>
5811     *
5812     * @param event The event to send.
5813     *
5814     * @see #sendAccessibilityEvent(int)
5815     */
5816    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5817        if (mAccessibilityDelegate != null) {
5818            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5819        } else {
5820            sendAccessibilityEventUncheckedInternal(event);
5821        }
5822    }
5823
5824    /**
5825     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5826     *
5827     * Note: Called from the default {@link AccessibilityDelegate}.
5828     *
5829     * @hide
5830     */
5831    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5832        if (!isShown()) {
5833            return;
5834        }
5835        onInitializeAccessibilityEvent(event);
5836        // Only a subset of accessibility events populates text content.
5837        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5838            dispatchPopulateAccessibilityEvent(event);
5839        }
5840        // In the beginning we called #isShown(), so we know that getParent() is not null.
5841        getParent().requestSendAccessibilityEvent(this, event);
5842    }
5843
5844    /**
5845     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5846     * to its children for adding their text content to the event. Note that the
5847     * event text is populated in a separate dispatch path since we add to the
5848     * event not only the text of the source but also the text of all its descendants.
5849     * A typical implementation will call
5850     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5851     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5852     * on each child. Override this method if custom population of the event text
5853     * content is required.
5854     * <p>
5855     * If an {@link AccessibilityDelegate} has been specified via calling
5856     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5857     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5858     * is responsible for handling this call.
5859     * </p>
5860     * <p>
5861     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5862     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5863     * </p>
5864     *
5865     * @param event The event.
5866     *
5867     * @return True if the event population was completed.
5868     */
5869    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5870        if (mAccessibilityDelegate != null) {
5871            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5872        } else {
5873            return dispatchPopulateAccessibilityEventInternal(event);
5874        }
5875    }
5876
5877    /**
5878     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5879     *
5880     * Note: Called from the default {@link AccessibilityDelegate}.
5881     *
5882     * @hide
5883     */
5884    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5885        onPopulateAccessibilityEvent(event);
5886        return false;
5887    }
5888
5889    /**
5890     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5891     * giving a chance to this View to populate the accessibility event with its
5892     * text content. While this method is free to modify event
5893     * attributes other than text content, doing so should normally be performed in
5894     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5895     * <p>
5896     * Example: Adding formatted date string to an accessibility event in addition
5897     *          to the text added by the super implementation:
5898     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5899     *     super.onPopulateAccessibilityEvent(event);
5900     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5901     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5902     *         mCurrentDate.getTimeInMillis(), flags);
5903     *     event.getText().add(selectedDateUtterance);
5904     * }</pre>
5905     * <p>
5906     * If an {@link AccessibilityDelegate} has been specified via calling
5907     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5908     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5909     * is responsible for handling this call.
5910     * </p>
5911     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5912     * information to the event, in case the default implementation has basic information to add.
5913     * </p>
5914     *
5915     * @param event The accessibility event which to populate.
5916     *
5917     * @see #sendAccessibilityEvent(int)
5918     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5919     */
5920    @CallSuper
5921    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5922        if (mAccessibilityDelegate != null) {
5923            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5924        } else {
5925            onPopulateAccessibilityEventInternal(event);
5926        }
5927    }
5928
5929    /**
5930     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5931     *
5932     * Note: Called from the default {@link AccessibilityDelegate}.
5933     *
5934     * @hide
5935     */
5936    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5937    }
5938
5939    /**
5940     * Initializes an {@link AccessibilityEvent} with information about
5941     * this View which is the event source. In other words, the source of
5942     * an accessibility event is the view whose state change triggered firing
5943     * the event.
5944     * <p>
5945     * Example: Setting the password property of an event in addition
5946     *          to properties set by the super implementation:
5947     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5948     *     super.onInitializeAccessibilityEvent(event);
5949     *     event.setPassword(true);
5950     * }</pre>
5951     * <p>
5952     * If an {@link AccessibilityDelegate} has been specified via calling
5953     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5954     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5955     * is responsible for handling this call.
5956     * </p>
5957     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5958     * information to the event, in case the default implementation has basic information to add.
5959     * </p>
5960     * @param event The event to initialize.
5961     *
5962     * @see #sendAccessibilityEvent(int)
5963     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5964     */
5965    @CallSuper
5966    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5967        if (mAccessibilityDelegate != null) {
5968            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5969        } else {
5970            onInitializeAccessibilityEventInternal(event);
5971        }
5972    }
5973
5974    /**
5975     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5976     *
5977     * Note: Called from the default {@link AccessibilityDelegate}.
5978     *
5979     * @hide
5980     */
5981    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5982        event.setSource(this);
5983        event.setClassName(getAccessibilityClassName());
5984        event.setPackageName(getContext().getPackageName());
5985        event.setEnabled(isEnabled());
5986        event.setContentDescription(mContentDescription);
5987
5988        switch (event.getEventType()) {
5989            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5990                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5991                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5992                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5993                event.setItemCount(focusablesTempList.size());
5994                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5995                if (mAttachInfo != null) {
5996                    focusablesTempList.clear();
5997                }
5998            } break;
5999            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6000                CharSequence text = getIterableTextForAccessibility();
6001                if (text != null && text.length() > 0) {
6002                    event.setFromIndex(getAccessibilitySelectionStart());
6003                    event.setToIndex(getAccessibilitySelectionEnd());
6004                    event.setItemCount(text.length());
6005                }
6006            } break;
6007        }
6008    }
6009
6010    /**
6011     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6012     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6013     * This method is responsible for obtaining an accessibility node info from a
6014     * pool of reusable instances and calling
6015     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6016     * initialize the former.
6017     * <p>
6018     * Note: The client is responsible for recycling the obtained instance by calling
6019     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6020     * </p>
6021     *
6022     * @return A populated {@link AccessibilityNodeInfo}.
6023     *
6024     * @see AccessibilityNodeInfo
6025     */
6026    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6027        if (mAccessibilityDelegate != null) {
6028            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6029        } else {
6030            return createAccessibilityNodeInfoInternal();
6031        }
6032    }
6033
6034    /**
6035     * @see #createAccessibilityNodeInfo()
6036     *
6037     * @hide
6038     */
6039    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6040        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6041        if (provider != null) {
6042            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6043        } else {
6044            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6045            onInitializeAccessibilityNodeInfo(info);
6046            return info;
6047        }
6048    }
6049
6050    /**
6051     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6052     * The base implementation sets:
6053     * <ul>
6054     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6055     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6056     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6057     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6058     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6059     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6060     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6061     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6062     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6063     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6064     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6065     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6066     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6067     * </ul>
6068     * <p>
6069     * Subclasses should override this method, call the super implementation,
6070     * and set additional attributes.
6071     * </p>
6072     * <p>
6073     * If an {@link AccessibilityDelegate} has been specified via calling
6074     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6075     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6076     * is responsible for handling this call.
6077     * </p>
6078     *
6079     * @param info The instance to initialize.
6080     */
6081    @CallSuper
6082    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6083        if (mAccessibilityDelegate != null) {
6084            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6085        } else {
6086            onInitializeAccessibilityNodeInfoInternal(info);
6087        }
6088    }
6089
6090    /**
6091     * Gets the location of this view in screen coordinates.
6092     *
6093     * @param outRect The output location
6094     * @hide
6095     */
6096    public void getBoundsOnScreen(Rect outRect) {
6097        getBoundsOnScreen(outRect, false);
6098    }
6099
6100    /**
6101     * Gets the location of this view in screen coordinates.
6102     *
6103     * @param outRect The output location
6104     * @param clipToParent Whether to clip child bounds to the parent ones.
6105     * @hide
6106     */
6107    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6108        if (mAttachInfo == null) {
6109            return;
6110        }
6111
6112        RectF position = mAttachInfo.mTmpTransformRect;
6113        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6114
6115        if (!hasIdentityMatrix()) {
6116            getMatrix().mapRect(position);
6117        }
6118
6119        position.offset(mLeft, mTop);
6120
6121        ViewParent parent = mParent;
6122        while (parent instanceof View) {
6123            View parentView = (View) parent;
6124
6125            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6126
6127            if (clipToParent) {
6128                position.left = Math.max(position.left, 0);
6129                position.top = Math.max(position.top, 0);
6130                position.right = Math.min(position.right, parentView.getWidth());
6131                position.bottom = Math.min(position.bottom, parentView.getHeight());
6132            }
6133
6134            if (!parentView.hasIdentityMatrix()) {
6135                parentView.getMatrix().mapRect(position);
6136            }
6137
6138            position.offset(parentView.mLeft, parentView.mTop);
6139
6140            parent = parentView.mParent;
6141        }
6142
6143        if (parent instanceof ViewRootImpl) {
6144            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6145            position.offset(0, -viewRootImpl.mCurScrollY);
6146        }
6147
6148        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6149
6150        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
6151                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
6152    }
6153
6154    /**
6155     * Return the class name of this object to be used for accessibility purposes.
6156     * Subclasses should only override this if they are implementing something that
6157     * should be seen as a completely new class of view when used by accessibility,
6158     * unrelated to the class it is deriving from.  This is used to fill in
6159     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6160     */
6161    public CharSequence getAccessibilityClassName() {
6162        return View.class.getName();
6163    }
6164
6165    /**
6166     * Called when assist structure is being retrieved from a view as part of
6167     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6168     * @param structure Fill in with structured view data.  The default implementation
6169     * fills in all data that can be inferred from the view itself.
6170     */
6171    public void onProvideStructure(ViewStructure structure) {
6172        final int id = mID;
6173        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6174                && (id&0x0000ffff) != 0) {
6175            String pkg, type, entry;
6176            try {
6177                final Resources res = getResources();
6178                entry = res.getResourceEntryName(id);
6179                type = res.getResourceTypeName(id);
6180                pkg = res.getResourcePackageName(id);
6181            } catch (Resources.NotFoundException e) {
6182                entry = type = pkg = null;
6183            }
6184            structure.setId(id, pkg, type, entry);
6185        } else {
6186            structure.setId(id, null, null, null);
6187        }
6188        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6189        if (!hasIdentityMatrix()) {
6190            structure.setTransformation(getMatrix());
6191        }
6192        structure.setElevation(getZ());
6193        structure.setVisibility(getVisibility());
6194        structure.setEnabled(isEnabled());
6195        if (isClickable()) {
6196            structure.setClickable(true);
6197        }
6198        if (isFocusable()) {
6199            structure.setFocusable(true);
6200        }
6201        if (isFocused()) {
6202            structure.setFocused(true);
6203        }
6204        if (isAccessibilityFocused()) {
6205            structure.setAccessibilityFocused(true);
6206        }
6207        if (isSelected()) {
6208            structure.setSelected(true);
6209        }
6210        if (isActivated()) {
6211            structure.setActivated(true);
6212        }
6213        if (isLongClickable()) {
6214            structure.setLongClickable(true);
6215        }
6216        if (this instanceof Checkable) {
6217            structure.setCheckable(true);
6218            if (((Checkable)this).isChecked()) {
6219                structure.setChecked(true);
6220            }
6221        }
6222        if (isContextClickable()) {
6223            structure.setContextClickable(true);
6224        }
6225        structure.setClassName(getAccessibilityClassName().toString());
6226        structure.setContentDescription(getContentDescription());
6227    }
6228
6229    /**
6230     * Called when assist structure is being retrieved from a view as part of
6231     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6232     * generate additional virtual structure under this view.  The defaullt implementation
6233     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6234     * view's virtual accessibility nodes, if any.  You can override this for a more
6235     * optimal implementation providing this data.
6236     */
6237    public void onProvideVirtualStructure(ViewStructure structure) {
6238        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6239        if (provider != null) {
6240            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6241            structure.setChildCount(1);
6242            ViewStructure root = structure.newChild(0);
6243            populateVirtualStructure(root, provider, info);
6244            info.recycle();
6245        }
6246    }
6247
6248    private void populateVirtualStructure(ViewStructure structure,
6249            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6250        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6251                null, null, null);
6252        Rect rect = structure.getTempRect();
6253        info.getBoundsInParent(rect);
6254        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6255        structure.setVisibility(VISIBLE);
6256        structure.setEnabled(info.isEnabled());
6257        if (info.isClickable()) {
6258            structure.setClickable(true);
6259        }
6260        if (info.isFocusable()) {
6261            structure.setFocusable(true);
6262        }
6263        if (info.isFocused()) {
6264            structure.setFocused(true);
6265        }
6266        if (info.isAccessibilityFocused()) {
6267            structure.setAccessibilityFocused(true);
6268        }
6269        if (info.isSelected()) {
6270            structure.setSelected(true);
6271        }
6272        if (info.isLongClickable()) {
6273            structure.setLongClickable(true);
6274        }
6275        if (info.isCheckable()) {
6276            structure.setCheckable(true);
6277            if (info.isChecked()) {
6278                structure.setChecked(true);
6279            }
6280        }
6281        if (info.isContextClickable()) {
6282            structure.setContextClickable(true);
6283        }
6284        CharSequence cname = info.getClassName();
6285        structure.setClassName(cname != null ? cname.toString() : null);
6286        structure.setContentDescription(info.getContentDescription());
6287        if (info.getText() != null || info.getError() != null) {
6288            structure.setText(info.getText(), info.getTextSelectionStart(),
6289                    info.getTextSelectionEnd());
6290        }
6291        final int NCHILDREN = info.getChildCount();
6292        if (NCHILDREN > 0) {
6293            structure.setChildCount(NCHILDREN);
6294            for (int i=0; i<NCHILDREN; i++) {
6295                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6296                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6297                ViewStructure child = structure.newChild(i);
6298                populateVirtualStructure(child, provider, cinfo);
6299                cinfo.recycle();
6300            }
6301        }
6302    }
6303
6304    /**
6305     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6306     * implementation calls {@link #onProvideStructure} and
6307     * {@link #onProvideVirtualStructure}.
6308     */
6309    public void dispatchProvideStructure(ViewStructure structure) {
6310        if (!isAssistBlocked()) {
6311            onProvideStructure(structure);
6312            onProvideVirtualStructure(structure);
6313        } else {
6314            structure.setClassName(getAccessibilityClassName().toString());
6315            structure.setAssistBlocked(true);
6316        }
6317    }
6318
6319    /**
6320     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6321     *
6322     * Note: Called from the default {@link AccessibilityDelegate}.
6323     *
6324     * @hide
6325     */
6326    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6327        if (mAttachInfo == null) {
6328            return;
6329        }
6330
6331        Rect bounds = mAttachInfo.mTmpInvalRect;
6332
6333        getDrawingRect(bounds);
6334        info.setBoundsInParent(bounds);
6335
6336        getBoundsOnScreen(bounds, true);
6337        info.setBoundsInScreen(bounds);
6338
6339        ViewParent parent = getParentForAccessibility();
6340        if (parent instanceof View) {
6341            info.setParent((View) parent);
6342        }
6343
6344        if (mID != View.NO_ID) {
6345            View rootView = getRootView();
6346            if (rootView == null) {
6347                rootView = this;
6348            }
6349
6350            View label = rootView.findLabelForView(this, mID);
6351            if (label != null) {
6352                info.setLabeledBy(label);
6353            }
6354
6355            if ((mAttachInfo.mAccessibilityFetchFlags
6356                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6357                    && Resources.resourceHasPackage(mID)) {
6358                try {
6359                    String viewId = getResources().getResourceName(mID);
6360                    info.setViewIdResourceName(viewId);
6361                } catch (Resources.NotFoundException nfe) {
6362                    /* ignore */
6363                }
6364            }
6365        }
6366
6367        if (mLabelForId != View.NO_ID) {
6368            View rootView = getRootView();
6369            if (rootView == null) {
6370                rootView = this;
6371            }
6372            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6373            if (labeled != null) {
6374                info.setLabelFor(labeled);
6375            }
6376        }
6377
6378        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6379            View rootView = getRootView();
6380            if (rootView == null) {
6381                rootView = this;
6382            }
6383            View next = rootView.findViewInsideOutShouldExist(this,
6384                    mAccessibilityTraversalBeforeId);
6385            if (next != null && next.includeForAccessibility()) {
6386                info.setTraversalBefore(next);
6387            }
6388        }
6389
6390        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6391            View rootView = getRootView();
6392            if (rootView == null) {
6393                rootView = this;
6394            }
6395            View next = rootView.findViewInsideOutShouldExist(this,
6396                    mAccessibilityTraversalAfterId);
6397            if (next != null && next.includeForAccessibility()) {
6398                info.setTraversalAfter(next);
6399            }
6400        }
6401
6402        info.setVisibleToUser(isVisibleToUser());
6403
6404        info.setPackageName(mContext.getPackageName());
6405        info.setClassName(getAccessibilityClassName());
6406        info.setContentDescription(getContentDescription());
6407
6408        info.setEnabled(isEnabled());
6409        info.setClickable(isClickable());
6410        info.setFocusable(isFocusable());
6411        info.setFocused(isFocused());
6412        info.setAccessibilityFocused(isAccessibilityFocused());
6413        info.setSelected(isSelected());
6414        info.setLongClickable(isLongClickable());
6415        info.setContextClickable(isContextClickable());
6416        info.setLiveRegion(getAccessibilityLiveRegion());
6417
6418        // TODO: These make sense only if we are in an AdapterView but all
6419        // views can be selected. Maybe from accessibility perspective
6420        // we should report as selectable view in an AdapterView.
6421        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6422        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6423
6424        if (isFocusable()) {
6425            if (isFocused()) {
6426                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6427            } else {
6428                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6429            }
6430        }
6431
6432        if (!isAccessibilityFocused()) {
6433            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6434        } else {
6435            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6436        }
6437
6438        if (isClickable() && isEnabled()) {
6439            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6440        }
6441
6442        if (isLongClickable() && isEnabled()) {
6443            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6444        }
6445
6446        if (isContextClickable() && isEnabled()) {
6447            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6448        }
6449
6450        CharSequence text = getIterableTextForAccessibility();
6451        if (text != null && text.length() > 0) {
6452            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6453
6454            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6455            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6456            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6457            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6458                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6459                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6460        }
6461
6462        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6463    }
6464
6465    private View findLabelForView(View view, int labeledId) {
6466        if (mMatchLabelForPredicate == null) {
6467            mMatchLabelForPredicate = new MatchLabelForPredicate();
6468        }
6469        mMatchLabelForPredicate.mLabeledId = labeledId;
6470        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6471    }
6472
6473    /**
6474     * Computes whether this view is visible to the user. Such a view is
6475     * attached, visible, all its predecessors are visible, it is not clipped
6476     * entirely by its predecessors, and has an alpha greater than zero.
6477     *
6478     * @return Whether the view is visible on the screen.
6479     *
6480     * @hide
6481     */
6482    protected boolean isVisibleToUser() {
6483        return isVisibleToUser(null);
6484    }
6485
6486    /**
6487     * Computes whether the given portion of this view is visible to the user.
6488     * Such a view is attached, visible, all its predecessors are visible,
6489     * has an alpha greater than zero, and the specified portion is not
6490     * clipped entirely by its predecessors.
6491     *
6492     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6493     *                    <code>null</code>, and the entire view will be tested in this case.
6494     *                    When <code>true</code> is returned by the function, the actual visible
6495     *                    region will be stored in this parameter; that is, if boundInView is fully
6496     *                    contained within the view, no modification will be made, otherwise regions
6497     *                    outside of the visible area of the view will be clipped.
6498     *
6499     * @return Whether the specified portion of the view is visible on the screen.
6500     *
6501     * @hide
6502     */
6503    protected boolean isVisibleToUser(Rect boundInView) {
6504        if (mAttachInfo != null) {
6505            // Attached to invisible window means this view is not visible.
6506            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
6507                return false;
6508            }
6509            // An invisible predecessor or one with alpha zero means
6510            // that this view is not visible to the user.
6511            Object current = this;
6512            while (current instanceof View) {
6513                View view = (View) current;
6514                // We have attach info so this view is attached and there is no
6515                // need to check whether we reach to ViewRootImpl on the way up.
6516                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
6517                        view.getVisibility() != VISIBLE) {
6518                    return false;
6519                }
6520                current = view.mParent;
6521            }
6522            // Check if the view is entirely covered by its predecessors.
6523            Rect visibleRect = mAttachInfo.mTmpInvalRect;
6524            Point offset = mAttachInfo.mPoint;
6525            if (!getGlobalVisibleRect(visibleRect, offset)) {
6526                return false;
6527            }
6528            // Check if the visible portion intersects the rectangle of interest.
6529            if (boundInView != null) {
6530                visibleRect.offset(-offset.x, -offset.y);
6531                return boundInView.intersect(visibleRect);
6532            }
6533            return true;
6534        }
6535        return false;
6536    }
6537
6538    /**
6539     * Returns the delegate for implementing accessibility support via
6540     * composition. For more details see {@link AccessibilityDelegate}.
6541     *
6542     * @return The delegate, or null if none set.
6543     *
6544     * @hide
6545     */
6546    public AccessibilityDelegate getAccessibilityDelegate() {
6547        return mAccessibilityDelegate;
6548    }
6549
6550    /**
6551     * Sets a delegate for implementing accessibility support via composition as
6552     * opposed to inheritance. The delegate's primary use is for implementing
6553     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
6554     *
6555     * @param delegate The delegate instance.
6556     *
6557     * @see AccessibilityDelegate
6558     */
6559    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
6560        mAccessibilityDelegate = delegate;
6561    }
6562
6563    /**
6564     * Gets the provider for managing a virtual view hierarchy rooted at this View
6565     * and reported to {@link android.accessibilityservice.AccessibilityService}s
6566     * that explore the window content.
6567     * <p>
6568     * If this method returns an instance, this instance is responsible for managing
6569     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
6570     * View including the one representing the View itself. Similarly the returned
6571     * instance is responsible for performing accessibility actions on any virtual
6572     * view or the root view itself.
6573     * </p>
6574     * <p>
6575     * If an {@link AccessibilityDelegate} has been specified via calling
6576     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6577     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
6578     * is responsible for handling this call.
6579     * </p>
6580     *
6581     * @return The provider.
6582     *
6583     * @see AccessibilityNodeProvider
6584     */
6585    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6586        if (mAccessibilityDelegate != null) {
6587            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6588        } else {
6589            return null;
6590        }
6591    }
6592
6593    /**
6594     * Gets the unique identifier of this view on the screen for accessibility purposes.
6595     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6596     *
6597     * @return The view accessibility id.
6598     *
6599     * @hide
6600     */
6601    public int getAccessibilityViewId() {
6602        if (mAccessibilityViewId == NO_ID) {
6603            mAccessibilityViewId = sNextAccessibilityViewId++;
6604        }
6605        return mAccessibilityViewId;
6606    }
6607
6608    /**
6609     * Gets the unique identifier of the window in which this View reseides.
6610     *
6611     * @return The window accessibility id.
6612     *
6613     * @hide
6614     */
6615    public int getAccessibilityWindowId() {
6616        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6617                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6618    }
6619
6620    /**
6621     * Gets the {@link View} description. It briefly describes the view and is
6622     * primarily used for accessibility support. Set this property to enable
6623     * better accessibility support for your application. This is especially
6624     * true for views that do not have textual representation (For example,
6625     * ImageButton).
6626     *
6627     * @return The content description.
6628     *
6629     * @attr ref android.R.styleable#View_contentDescription
6630     */
6631    @ViewDebug.ExportedProperty(category = "accessibility")
6632    public CharSequence getContentDescription() {
6633        return mContentDescription;
6634    }
6635
6636    /**
6637     * Sets the {@link View} description. It briefly describes the view and is
6638     * primarily used for accessibility support. Set this property to enable
6639     * better accessibility support for your application. This is especially
6640     * true for views that do not have textual representation (For example,
6641     * ImageButton).
6642     *
6643     * @param contentDescription The content description.
6644     *
6645     * @attr ref android.R.styleable#View_contentDescription
6646     */
6647    @RemotableViewMethod
6648    public void setContentDescription(CharSequence contentDescription) {
6649        if (mContentDescription == null) {
6650            if (contentDescription == null) {
6651                return;
6652            }
6653        } else if (mContentDescription.equals(contentDescription)) {
6654            return;
6655        }
6656        mContentDescription = contentDescription;
6657        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6658        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6659            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6660            notifySubtreeAccessibilityStateChangedIfNeeded();
6661        } else {
6662            notifyViewAccessibilityStateChangedIfNeeded(
6663                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6664        }
6665    }
6666
6667    /**
6668     * Sets the id of a view before which this one is visited in accessibility traversal.
6669     * A screen-reader must visit the content of this view before the content of the one
6670     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6671     * will traverse the entire content of B before traversing the entire content of A,
6672     * regardles of what traversal strategy it is using.
6673     * <p>
6674     * Views that do not have specified before/after relationships are traversed in order
6675     * determined by the screen-reader.
6676     * </p>
6677     * <p>
6678     * Setting that this view is before a view that is not important for accessibility
6679     * or if this view is not important for accessibility will have no effect as the
6680     * screen-reader is not aware of unimportant views.
6681     * </p>
6682     *
6683     * @param beforeId The id of a view this one precedes in accessibility traversal.
6684     *
6685     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6686     *
6687     * @see #setImportantForAccessibility(int)
6688     */
6689    @RemotableViewMethod
6690    public void setAccessibilityTraversalBefore(int beforeId) {
6691        if (mAccessibilityTraversalBeforeId == beforeId) {
6692            return;
6693        }
6694        mAccessibilityTraversalBeforeId = beforeId;
6695        notifyViewAccessibilityStateChangedIfNeeded(
6696                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6697    }
6698
6699    /**
6700     * Gets the id of a view before which this one is visited in accessibility traversal.
6701     *
6702     * @return The id of a view this one precedes in accessibility traversal if
6703     *         specified, otherwise {@link #NO_ID}.
6704     *
6705     * @see #setAccessibilityTraversalBefore(int)
6706     */
6707    public int getAccessibilityTraversalBefore() {
6708        return mAccessibilityTraversalBeforeId;
6709    }
6710
6711    /**
6712     * Sets the id of a view after which this one is visited in accessibility traversal.
6713     * A screen-reader must visit the content of the other view before the content of this
6714     * one. For example, if view B is set to be after view A, then a screen-reader
6715     * will traverse the entire content of A before traversing the entire content of B,
6716     * regardles of what traversal strategy it is using.
6717     * <p>
6718     * Views that do not have specified before/after relationships are traversed in order
6719     * determined by the screen-reader.
6720     * </p>
6721     * <p>
6722     * Setting that this view is after a view that is not important for accessibility
6723     * or if this view is not important for accessibility will have no effect as the
6724     * screen-reader is not aware of unimportant views.
6725     * </p>
6726     *
6727     * @param afterId The id of a view this one succedees in accessibility traversal.
6728     *
6729     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6730     *
6731     * @see #setImportantForAccessibility(int)
6732     */
6733    @RemotableViewMethod
6734    public void setAccessibilityTraversalAfter(int afterId) {
6735        if (mAccessibilityTraversalAfterId == afterId) {
6736            return;
6737        }
6738        mAccessibilityTraversalAfterId = afterId;
6739        notifyViewAccessibilityStateChangedIfNeeded(
6740                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6741    }
6742
6743    /**
6744     * Gets the id of a view after which this one is visited in accessibility traversal.
6745     *
6746     * @return The id of a view this one succeedes in accessibility traversal if
6747     *         specified, otherwise {@link #NO_ID}.
6748     *
6749     * @see #setAccessibilityTraversalAfter(int)
6750     */
6751    public int getAccessibilityTraversalAfter() {
6752        return mAccessibilityTraversalAfterId;
6753    }
6754
6755    /**
6756     * Gets the id of a view for which this view serves as a label for
6757     * accessibility purposes.
6758     *
6759     * @return The labeled view id.
6760     */
6761    @ViewDebug.ExportedProperty(category = "accessibility")
6762    public int getLabelFor() {
6763        return mLabelForId;
6764    }
6765
6766    /**
6767     * Sets the id of a view for which this view serves as a label for
6768     * accessibility purposes.
6769     *
6770     * @param id The labeled view id.
6771     */
6772    @RemotableViewMethod
6773    public void setLabelFor(@IdRes int id) {
6774        if (mLabelForId == id) {
6775            return;
6776        }
6777        mLabelForId = id;
6778        if (mLabelForId != View.NO_ID
6779                && mID == View.NO_ID) {
6780            mID = generateViewId();
6781        }
6782        notifyViewAccessibilityStateChangedIfNeeded(
6783                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6784    }
6785
6786    /**
6787     * Invoked whenever this view loses focus, either by losing window focus or by losing
6788     * focus within its window. This method can be used to clear any state tied to the
6789     * focus. For instance, if a button is held pressed with the trackball and the window
6790     * loses focus, this method can be used to cancel the press.
6791     *
6792     * Subclasses of View overriding this method should always call super.onFocusLost().
6793     *
6794     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6795     * @see #onWindowFocusChanged(boolean)
6796     *
6797     * @hide pending API council approval
6798     */
6799    @CallSuper
6800    protected void onFocusLost() {
6801        resetPressedState();
6802    }
6803
6804    private void resetPressedState() {
6805        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6806            return;
6807        }
6808
6809        if (isPressed()) {
6810            setPressed(false);
6811
6812            if (!mHasPerformedLongPress) {
6813                removeLongPressCallback();
6814            }
6815        }
6816    }
6817
6818    /**
6819     * Returns true if this view has focus
6820     *
6821     * @return True if this view has focus, false otherwise.
6822     */
6823    @ViewDebug.ExportedProperty(category = "focus")
6824    public boolean isFocused() {
6825        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6826    }
6827
6828    /**
6829     * Find the view in the hierarchy rooted at this view that currently has
6830     * focus.
6831     *
6832     * @return The view that currently has focus, or null if no focused view can
6833     *         be found.
6834     */
6835    public View findFocus() {
6836        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6837    }
6838
6839    /**
6840     * Indicates whether this view is one of the set of scrollable containers in
6841     * its window.
6842     *
6843     * @return whether this view is one of the set of scrollable containers in
6844     * its window
6845     *
6846     * @attr ref android.R.styleable#View_isScrollContainer
6847     */
6848    public boolean isScrollContainer() {
6849        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6850    }
6851
6852    /**
6853     * Change whether this view is one of the set of scrollable containers in
6854     * its window.  This will be used to determine whether the window can
6855     * resize or must pan when a soft input area is open -- scrollable
6856     * containers allow the window to use resize mode since the container
6857     * will appropriately shrink.
6858     *
6859     * @attr ref android.R.styleable#View_isScrollContainer
6860     */
6861    public void setScrollContainer(boolean isScrollContainer) {
6862        if (isScrollContainer) {
6863            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6864                mAttachInfo.mScrollContainers.add(this);
6865                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6866            }
6867            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6868        } else {
6869            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6870                mAttachInfo.mScrollContainers.remove(this);
6871            }
6872            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6873        }
6874    }
6875
6876    /**
6877     * Returns the quality of the drawing cache.
6878     *
6879     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6880     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6881     *
6882     * @see #setDrawingCacheQuality(int)
6883     * @see #setDrawingCacheEnabled(boolean)
6884     * @see #isDrawingCacheEnabled()
6885     *
6886     * @attr ref android.R.styleable#View_drawingCacheQuality
6887     */
6888    @DrawingCacheQuality
6889    public int getDrawingCacheQuality() {
6890        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6891    }
6892
6893    /**
6894     * Set the drawing cache quality of this view. This value is used only when the
6895     * drawing cache is enabled
6896     *
6897     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6898     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6899     *
6900     * @see #getDrawingCacheQuality()
6901     * @see #setDrawingCacheEnabled(boolean)
6902     * @see #isDrawingCacheEnabled()
6903     *
6904     * @attr ref android.R.styleable#View_drawingCacheQuality
6905     */
6906    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6907        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6908    }
6909
6910    /**
6911     * Returns whether the screen should remain on, corresponding to the current
6912     * value of {@link #KEEP_SCREEN_ON}.
6913     *
6914     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6915     *
6916     * @see #setKeepScreenOn(boolean)
6917     *
6918     * @attr ref android.R.styleable#View_keepScreenOn
6919     */
6920    public boolean getKeepScreenOn() {
6921        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6922    }
6923
6924    /**
6925     * Controls whether the screen should remain on, modifying the
6926     * value of {@link #KEEP_SCREEN_ON}.
6927     *
6928     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6929     *
6930     * @see #getKeepScreenOn()
6931     *
6932     * @attr ref android.R.styleable#View_keepScreenOn
6933     */
6934    public void setKeepScreenOn(boolean keepScreenOn) {
6935        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6936    }
6937
6938    /**
6939     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6940     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6941     *
6942     * @attr ref android.R.styleable#View_nextFocusLeft
6943     */
6944    public int getNextFocusLeftId() {
6945        return mNextFocusLeftId;
6946    }
6947
6948    /**
6949     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6950     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6951     * decide automatically.
6952     *
6953     * @attr ref android.R.styleable#View_nextFocusLeft
6954     */
6955    public void setNextFocusLeftId(int nextFocusLeftId) {
6956        mNextFocusLeftId = nextFocusLeftId;
6957    }
6958
6959    /**
6960     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6961     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6962     *
6963     * @attr ref android.R.styleable#View_nextFocusRight
6964     */
6965    public int getNextFocusRightId() {
6966        return mNextFocusRightId;
6967    }
6968
6969    /**
6970     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6971     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6972     * decide automatically.
6973     *
6974     * @attr ref android.R.styleable#View_nextFocusRight
6975     */
6976    public void setNextFocusRightId(int nextFocusRightId) {
6977        mNextFocusRightId = nextFocusRightId;
6978    }
6979
6980    /**
6981     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6982     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6983     *
6984     * @attr ref android.R.styleable#View_nextFocusUp
6985     */
6986    public int getNextFocusUpId() {
6987        return mNextFocusUpId;
6988    }
6989
6990    /**
6991     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6992     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6993     * decide automatically.
6994     *
6995     * @attr ref android.R.styleable#View_nextFocusUp
6996     */
6997    public void setNextFocusUpId(int nextFocusUpId) {
6998        mNextFocusUpId = nextFocusUpId;
6999    }
7000
7001    /**
7002     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7003     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7004     *
7005     * @attr ref android.R.styleable#View_nextFocusDown
7006     */
7007    public int getNextFocusDownId() {
7008        return mNextFocusDownId;
7009    }
7010
7011    /**
7012     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7013     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7014     * decide automatically.
7015     *
7016     * @attr ref android.R.styleable#View_nextFocusDown
7017     */
7018    public void setNextFocusDownId(int nextFocusDownId) {
7019        mNextFocusDownId = nextFocusDownId;
7020    }
7021
7022    /**
7023     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7024     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7025     *
7026     * @attr ref android.R.styleable#View_nextFocusForward
7027     */
7028    public int getNextFocusForwardId() {
7029        return mNextFocusForwardId;
7030    }
7031
7032    /**
7033     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7034     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7035     * decide automatically.
7036     *
7037     * @attr ref android.R.styleable#View_nextFocusForward
7038     */
7039    public void setNextFocusForwardId(int nextFocusForwardId) {
7040        mNextFocusForwardId = nextFocusForwardId;
7041    }
7042
7043    /**
7044     * Returns the visibility of this view and all of its ancestors
7045     *
7046     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7047     */
7048    public boolean isShown() {
7049        View current = this;
7050        //noinspection ConstantConditions
7051        do {
7052            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7053                return false;
7054            }
7055            ViewParent parent = current.mParent;
7056            if (parent == null) {
7057                return false; // We are not attached to the view root
7058            }
7059            if (!(parent instanceof View)) {
7060                return true;
7061            }
7062            current = (View) parent;
7063        } while (current != null);
7064
7065        return false;
7066    }
7067
7068    /**
7069     * Called by the view hierarchy when the content insets for a window have
7070     * changed, to allow it to adjust its content to fit within those windows.
7071     * The content insets tell you the space that the status bar, input method,
7072     * and other system windows infringe on the application's window.
7073     *
7074     * <p>You do not normally need to deal with this function, since the default
7075     * window decoration given to applications takes care of applying it to the
7076     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7077     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7078     * and your content can be placed under those system elements.  You can then
7079     * use this method within your view hierarchy if you have parts of your UI
7080     * which you would like to ensure are not being covered.
7081     *
7082     * <p>The default implementation of this method simply applies the content
7083     * insets to the view's padding, consuming that content (modifying the
7084     * insets to be 0), and returning true.  This behavior is off by default, but can
7085     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7086     *
7087     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7088     * insets object is propagated down the hierarchy, so any changes made to it will
7089     * be seen by all following views (including potentially ones above in
7090     * the hierarchy since this is a depth-first traversal).  The first view
7091     * that returns true will abort the entire traversal.
7092     *
7093     * <p>The default implementation works well for a situation where it is
7094     * used with a container that covers the entire window, allowing it to
7095     * apply the appropriate insets to its content on all edges.  If you need
7096     * a more complicated layout (such as two different views fitting system
7097     * windows, one on the top of the window, and one on the bottom),
7098     * you can override the method and handle the insets however you would like.
7099     * Note that the insets provided by the framework are always relative to the
7100     * far edges of the window, not accounting for the location of the called view
7101     * within that window.  (In fact when this method is called you do not yet know
7102     * where the layout will place the view, as it is done before layout happens.)
7103     *
7104     * <p>Note: unlike many View methods, there is no dispatch phase to this
7105     * call.  If you are overriding it in a ViewGroup and want to allow the
7106     * call to continue to your children, you must be sure to call the super
7107     * implementation.
7108     *
7109     * <p>Here is a sample layout that makes use of fitting system windows
7110     * to have controls for a video view placed inside of the window decorations
7111     * that it hides and shows.  This can be used with code like the second
7112     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7113     *
7114     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7115     *
7116     * @param insets Current content insets of the window.  Prior to
7117     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7118     * the insets or else you and Android will be unhappy.
7119     *
7120     * @return {@code true} if this view applied the insets and it should not
7121     * continue propagating further down the hierarchy, {@code false} otherwise.
7122     * @see #getFitsSystemWindows()
7123     * @see #setFitsSystemWindows(boolean)
7124     * @see #setSystemUiVisibility(int)
7125     *
7126     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7127     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7128     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7129     * to implement handling their own insets.
7130     */
7131    protected boolean fitSystemWindows(Rect insets) {
7132        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7133            if (insets == null) {
7134                // Null insets by definition have already been consumed.
7135                // This call cannot apply insets since there are none to apply,
7136                // so return false.
7137                return false;
7138            }
7139            // If we're not in the process of dispatching the newer apply insets call,
7140            // that means we're not in the compatibility path. Dispatch into the newer
7141            // apply insets path and take things from there.
7142            try {
7143                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7144                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7145            } finally {
7146                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7147            }
7148        } else {
7149            // We're being called from the newer apply insets path.
7150            // Perform the standard fallback behavior.
7151            return fitSystemWindowsInt(insets);
7152        }
7153    }
7154
7155    private boolean fitSystemWindowsInt(Rect insets) {
7156        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7157            mUserPaddingStart = UNDEFINED_PADDING;
7158            mUserPaddingEnd = UNDEFINED_PADDING;
7159            Rect localInsets = sThreadLocal.get();
7160            if (localInsets == null) {
7161                localInsets = new Rect();
7162                sThreadLocal.set(localInsets);
7163            }
7164            boolean res = computeFitSystemWindows(insets, localInsets);
7165            mUserPaddingLeftInitial = localInsets.left;
7166            mUserPaddingRightInitial = localInsets.right;
7167            internalSetPadding(localInsets.left, localInsets.top,
7168                    localInsets.right, localInsets.bottom);
7169            return res;
7170        }
7171        return false;
7172    }
7173
7174    /**
7175     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7176     *
7177     * <p>This method should be overridden by views that wish to apply a policy different from or
7178     * in addition to the default behavior. Clients that wish to force a view subtree
7179     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7180     *
7181     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7182     * it will be called during dispatch instead of this method. The listener may optionally
7183     * call this method from its own implementation if it wishes to apply the view's default
7184     * insets policy in addition to its own.</p>
7185     *
7186     * <p>Implementations of this method should either return the insets parameter unchanged
7187     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7188     * that this view applied itself. This allows new inset types added in future platform
7189     * versions to pass through existing implementations unchanged without being erroneously
7190     * consumed.</p>
7191     *
7192     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7193     * property is set then the view will consume the system window insets and apply them
7194     * as padding for the view.</p>
7195     *
7196     * @param insets Insets to apply
7197     * @return The supplied insets with any applied insets consumed
7198     */
7199    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7200        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7201            // We weren't called from within a direct call to fitSystemWindows,
7202            // call into it as a fallback in case we're in a class that overrides it
7203            // and has logic to perform.
7204            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7205                return insets.consumeSystemWindowInsets();
7206            }
7207        } else {
7208            // We were called from within a direct call to fitSystemWindows.
7209            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7210                return insets.consumeSystemWindowInsets();
7211            }
7212        }
7213        return insets;
7214    }
7215
7216    /**
7217     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7218     * window insets to this view. The listener's
7219     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7220     * method will be called instead of the view's
7221     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7222     *
7223     * @param listener Listener to set
7224     *
7225     * @see #onApplyWindowInsets(WindowInsets)
7226     */
7227    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7228        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7229    }
7230
7231    /**
7232     * Request to apply the given window insets to this view or another view in its subtree.
7233     *
7234     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7235     * obscured by window decorations or overlays. This can include the status and navigation bars,
7236     * action bars, input methods and more. New inset categories may be added in the future.
7237     * The method returns the insets provided minus any that were applied by this view or its
7238     * children.</p>
7239     *
7240     * <p>Clients wishing to provide custom behavior should override the
7241     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7242     * {@link OnApplyWindowInsetsListener} via the
7243     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7244     * method.</p>
7245     *
7246     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7247     * </p>
7248     *
7249     * @param insets Insets to apply
7250     * @return The provided insets minus the insets that were consumed
7251     */
7252    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7253        try {
7254            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7255            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7256                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7257            } else {
7258                return onApplyWindowInsets(insets);
7259            }
7260        } finally {
7261            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7262        }
7263    }
7264
7265    /**
7266     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7267     * only available if the view is attached.
7268     *
7269     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7270     */
7271    public WindowInsets getRootWindowInsets() {
7272        if (mAttachInfo != null) {
7273            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7274        }
7275        return null;
7276    }
7277
7278    /**
7279     * @hide Compute the insets that should be consumed by this view and the ones
7280     * that should propagate to those under it.
7281     */
7282    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7283        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7284                || mAttachInfo == null
7285                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7286                        && !mAttachInfo.mOverscanRequested)) {
7287            outLocalInsets.set(inoutInsets);
7288            inoutInsets.set(0, 0, 0, 0);
7289            return true;
7290        } else {
7291            // The application wants to take care of fitting system window for
7292            // the content...  however we still need to take care of any overscan here.
7293            final Rect overscan = mAttachInfo.mOverscanInsets;
7294            outLocalInsets.set(overscan);
7295            inoutInsets.left -= overscan.left;
7296            inoutInsets.top -= overscan.top;
7297            inoutInsets.right -= overscan.right;
7298            inoutInsets.bottom -= overscan.bottom;
7299            return false;
7300        }
7301    }
7302
7303    /**
7304     * Compute insets that should be consumed by this view and the ones that should propagate
7305     * to those under it.
7306     *
7307     * @param in Insets currently being processed by this View, likely received as a parameter
7308     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7309     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7310     *                       by this view
7311     * @return Insets that should be passed along to views under this one
7312     */
7313    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7314        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7315                || mAttachInfo == null
7316                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7317            outLocalInsets.set(in.getSystemWindowInsets());
7318            return in.consumeSystemWindowInsets();
7319        } else {
7320            outLocalInsets.set(0, 0, 0, 0);
7321            return in;
7322        }
7323    }
7324
7325    /**
7326     * Sets whether or not this view should account for system screen decorations
7327     * such as the status bar and inset its content; that is, controlling whether
7328     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7329     * executed.  See that method for more details.
7330     *
7331     * <p>Note that if you are providing your own implementation of
7332     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7333     * flag to true -- your implementation will be overriding the default
7334     * implementation that checks this flag.
7335     *
7336     * @param fitSystemWindows If true, then the default implementation of
7337     * {@link #fitSystemWindows(Rect)} will be executed.
7338     *
7339     * @attr ref android.R.styleable#View_fitsSystemWindows
7340     * @see #getFitsSystemWindows()
7341     * @see #fitSystemWindows(Rect)
7342     * @see #setSystemUiVisibility(int)
7343     */
7344    public void setFitsSystemWindows(boolean fitSystemWindows) {
7345        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7346    }
7347
7348    /**
7349     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7350     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7351     * will be executed.
7352     *
7353     * @return {@code true} if the default implementation of
7354     * {@link #fitSystemWindows(Rect)} will be executed.
7355     *
7356     * @attr ref android.R.styleable#View_fitsSystemWindows
7357     * @see #setFitsSystemWindows(boolean)
7358     * @see #fitSystemWindows(Rect)
7359     * @see #setSystemUiVisibility(int)
7360     */
7361    @ViewDebug.ExportedProperty
7362    public boolean getFitsSystemWindows() {
7363        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7364    }
7365
7366    /** @hide */
7367    public boolean fitsSystemWindows() {
7368        return getFitsSystemWindows();
7369    }
7370
7371    /**
7372     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7373     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7374     */
7375    public void requestFitSystemWindows() {
7376        if (mParent != null) {
7377            mParent.requestFitSystemWindows();
7378        }
7379    }
7380
7381    /**
7382     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7383     */
7384    public void requestApplyInsets() {
7385        requestFitSystemWindows();
7386    }
7387
7388    /**
7389     * For use by PhoneWindow to make its own system window fitting optional.
7390     * @hide
7391     */
7392    public void makeOptionalFitsSystemWindows() {
7393        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7394    }
7395
7396    /**
7397     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7398     * treat them as such.
7399     * @hide
7400     */
7401    public void getOutsets(Rect outOutsetRect) {
7402        if (mAttachInfo != null) {
7403            outOutsetRect.set(mAttachInfo.mOutsets);
7404        } else {
7405            outOutsetRect.setEmpty();
7406        }
7407    }
7408
7409    /**
7410     * Returns the visibility status for this view.
7411     *
7412     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7413     * @attr ref android.R.styleable#View_visibility
7414     */
7415    @ViewDebug.ExportedProperty(mapping = {
7416        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7417        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7418        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7419    })
7420    @Visibility
7421    public int getVisibility() {
7422        return mViewFlags & VISIBILITY_MASK;
7423    }
7424
7425    /**
7426     * Set the enabled state of this view.
7427     *
7428     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7429     * @attr ref android.R.styleable#View_visibility
7430     */
7431    @RemotableViewMethod
7432    public void setVisibility(@Visibility int visibility) {
7433        setFlags(visibility, VISIBILITY_MASK);
7434    }
7435
7436    /**
7437     * Returns the enabled status for this view. The interpretation of the
7438     * enabled state varies by subclass.
7439     *
7440     * @return True if this view is enabled, false otherwise.
7441     */
7442    @ViewDebug.ExportedProperty
7443    public boolean isEnabled() {
7444        return (mViewFlags & ENABLED_MASK) == ENABLED;
7445    }
7446
7447    /**
7448     * Set the enabled state of this view. The interpretation of the enabled
7449     * state varies by subclass.
7450     *
7451     * @param enabled True if this view is enabled, false otherwise.
7452     */
7453    @RemotableViewMethod
7454    public void setEnabled(boolean enabled) {
7455        if (enabled == isEnabled()) return;
7456
7457        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7458
7459        /*
7460         * The View most likely has to change its appearance, so refresh
7461         * the drawable state.
7462         */
7463        refreshDrawableState();
7464
7465        // Invalidate too, since the default behavior for views is to be
7466        // be drawn at 50% alpha rather than to change the drawable.
7467        invalidate(true);
7468
7469        if (!enabled) {
7470            cancelPendingInputEvents();
7471        }
7472    }
7473
7474    /**
7475     * Set whether this view can receive the focus.
7476     *
7477     * Setting this to false will also ensure that this view is not focusable
7478     * in touch mode.
7479     *
7480     * @param focusable If true, this view can receive the focus.
7481     *
7482     * @see #setFocusableInTouchMode(boolean)
7483     * @attr ref android.R.styleable#View_focusable
7484     */
7485    public void setFocusable(boolean focusable) {
7486        if (!focusable) {
7487            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
7488        }
7489        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
7490    }
7491
7492    /**
7493     * Set whether this view can receive focus while in touch mode.
7494     *
7495     * Setting this to true will also ensure that this view is focusable.
7496     *
7497     * @param focusableInTouchMode If true, this view can receive the focus while
7498     *   in touch mode.
7499     *
7500     * @see #setFocusable(boolean)
7501     * @attr ref android.R.styleable#View_focusableInTouchMode
7502     */
7503    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
7504        // Focusable in touch mode should always be set before the focusable flag
7505        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
7506        // which, in touch mode, will not successfully request focus on this view
7507        // because the focusable in touch mode flag is not set
7508        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
7509        if (focusableInTouchMode) {
7510            setFlags(FOCUSABLE, FOCUSABLE_MASK);
7511        }
7512    }
7513
7514    /**
7515     * Set whether this view should have sound effects enabled for events such as
7516     * clicking and touching.
7517     *
7518     * <p>You may wish to disable sound effects for a view if you already play sounds,
7519     * for instance, a dial key that plays dtmf tones.
7520     *
7521     * @param soundEffectsEnabled whether sound effects are enabled for this view.
7522     * @see #isSoundEffectsEnabled()
7523     * @see #playSoundEffect(int)
7524     * @attr ref android.R.styleable#View_soundEffectsEnabled
7525     */
7526    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
7527        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
7528    }
7529
7530    /**
7531     * @return whether this view should have sound effects enabled for events such as
7532     *     clicking and touching.
7533     *
7534     * @see #setSoundEffectsEnabled(boolean)
7535     * @see #playSoundEffect(int)
7536     * @attr ref android.R.styleable#View_soundEffectsEnabled
7537     */
7538    @ViewDebug.ExportedProperty
7539    public boolean isSoundEffectsEnabled() {
7540        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
7541    }
7542
7543    /**
7544     * Set whether this view should have haptic feedback for events such as
7545     * long presses.
7546     *
7547     * <p>You may wish to disable haptic feedback if your view already controls
7548     * its own haptic feedback.
7549     *
7550     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
7551     * @see #isHapticFeedbackEnabled()
7552     * @see #performHapticFeedback(int)
7553     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7554     */
7555    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
7556        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
7557    }
7558
7559    /**
7560     * @return whether this view should have haptic feedback enabled for events
7561     * long presses.
7562     *
7563     * @see #setHapticFeedbackEnabled(boolean)
7564     * @see #performHapticFeedback(int)
7565     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7566     */
7567    @ViewDebug.ExportedProperty
7568    public boolean isHapticFeedbackEnabled() {
7569        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
7570    }
7571
7572    /**
7573     * Returns the layout direction for this view.
7574     *
7575     * @return One of {@link #LAYOUT_DIRECTION_LTR},
7576     *   {@link #LAYOUT_DIRECTION_RTL},
7577     *   {@link #LAYOUT_DIRECTION_INHERIT} or
7578     *   {@link #LAYOUT_DIRECTION_LOCALE}.
7579     *
7580     * @attr ref android.R.styleable#View_layoutDirection
7581     *
7582     * @hide
7583     */
7584    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7585        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
7586        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
7587        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
7588        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
7589    })
7590    @LayoutDir
7591    public int getRawLayoutDirection() {
7592        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
7593    }
7594
7595    /**
7596     * Set the layout direction for this view. This will propagate a reset of layout direction
7597     * resolution to the view's children and resolve layout direction for this view.
7598     *
7599     * @param layoutDirection the layout direction to set. Should be one of:
7600     *
7601     * {@link #LAYOUT_DIRECTION_LTR},
7602     * {@link #LAYOUT_DIRECTION_RTL},
7603     * {@link #LAYOUT_DIRECTION_INHERIT},
7604     * {@link #LAYOUT_DIRECTION_LOCALE}.
7605     *
7606     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7607     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7608     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7609     *
7610     * @attr ref android.R.styleable#View_layoutDirection
7611     */
7612    @RemotableViewMethod
7613    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7614        if (getRawLayoutDirection() != layoutDirection) {
7615            // Reset the current layout direction and the resolved one
7616            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7617            resetRtlProperties();
7618            // Set the new layout direction (filtered)
7619            mPrivateFlags2 |=
7620                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7621            // We need to resolve all RTL properties as they all depend on layout direction
7622            resolveRtlPropertiesIfNeeded();
7623            requestLayout();
7624            invalidate(true);
7625        }
7626    }
7627
7628    /**
7629     * Returns the resolved layout direction for this view.
7630     *
7631     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7632     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7633     *
7634     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7635     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7636     *
7637     * @attr ref android.R.styleable#View_layoutDirection
7638     */
7639    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7640        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7641        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7642    })
7643    @ResolvedLayoutDir
7644    public int getLayoutDirection() {
7645        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7646        if (targetSdkVersion < JELLY_BEAN_MR1) {
7647            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7648            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7649        }
7650        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7651                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7652    }
7653
7654    /**
7655     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7656     * layout attribute and/or the inherited value from the parent
7657     *
7658     * @return true if the layout is right-to-left.
7659     *
7660     * @hide
7661     */
7662    @ViewDebug.ExportedProperty(category = "layout")
7663    public boolean isLayoutRtl() {
7664        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7665    }
7666
7667    /**
7668     * Indicates whether the view is currently tracking transient state that the
7669     * app should not need to concern itself with saving and restoring, but that
7670     * the framework should take special note to preserve when possible.
7671     *
7672     * <p>A view with transient state cannot be trivially rebound from an external
7673     * data source, such as an adapter binding item views in a list. This may be
7674     * because the view is performing an animation, tracking user selection
7675     * of content, or similar.</p>
7676     *
7677     * @return true if the view has transient state
7678     */
7679    @ViewDebug.ExportedProperty(category = "layout")
7680    public boolean hasTransientState() {
7681        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7682    }
7683
7684    /**
7685     * Set whether this view is currently tracking transient state that the
7686     * framework should attempt to preserve when possible. This flag is reference counted,
7687     * so every call to setHasTransientState(true) should be paired with a later call
7688     * to setHasTransientState(false).
7689     *
7690     * <p>A view with transient state cannot be trivially rebound from an external
7691     * data source, such as an adapter binding item views in a list. This may be
7692     * because the view is performing an animation, tracking user selection
7693     * of content, or similar.</p>
7694     *
7695     * @param hasTransientState true if this view has transient state
7696     */
7697    public void setHasTransientState(boolean hasTransientState) {
7698        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7699                mTransientStateCount - 1;
7700        if (mTransientStateCount < 0) {
7701            mTransientStateCount = 0;
7702            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7703                    "unmatched pair of setHasTransientState calls");
7704        } else if ((hasTransientState && mTransientStateCount == 1) ||
7705                (!hasTransientState && mTransientStateCount == 0)) {
7706            // update flag if we've just incremented up from 0 or decremented down to 0
7707            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7708                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7709            if (mParent != null) {
7710                try {
7711                    mParent.childHasTransientStateChanged(this, hasTransientState);
7712                } catch (AbstractMethodError e) {
7713                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7714                            " does not fully implement ViewParent", e);
7715                }
7716            }
7717        }
7718    }
7719
7720    /**
7721     * Returns true if this view is currently attached to a window.
7722     */
7723    public boolean isAttachedToWindow() {
7724        return mAttachInfo != null;
7725    }
7726
7727    /**
7728     * Returns true if this view has been through at least one layout since it
7729     * was last attached to or detached from a window.
7730     */
7731    public boolean isLaidOut() {
7732        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7733    }
7734
7735    /**
7736     * If this view doesn't do any drawing on its own, set this flag to
7737     * allow further optimizations. By default, this flag is not set on
7738     * View, but could be set on some View subclasses such as ViewGroup.
7739     *
7740     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7741     * you should clear this flag.
7742     *
7743     * @param willNotDraw whether or not this View draw on its own
7744     */
7745    public void setWillNotDraw(boolean willNotDraw) {
7746        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7747    }
7748
7749    /**
7750     * Returns whether or not this View draws on its own.
7751     *
7752     * @return true if this view has nothing to draw, false otherwise
7753     */
7754    @ViewDebug.ExportedProperty(category = "drawing")
7755    public boolean willNotDraw() {
7756        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7757    }
7758
7759    /**
7760     * When a View's drawing cache is enabled, drawing is redirected to an
7761     * offscreen bitmap. Some views, like an ImageView, must be able to
7762     * bypass this mechanism if they already draw a single bitmap, to avoid
7763     * unnecessary usage of the memory.
7764     *
7765     * @param willNotCacheDrawing true if this view does not cache its
7766     *        drawing, false otherwise
7767     */
7768    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7769        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7770    }
7771
7772    /**
7773     * Returns whether or not this View can cache its drawing or not.
7774     *
7775     * @return true if this view does not cache its drawing, false otherwise
7776     */
7777    @ViewDebug.ExportedProperty(category = "drawing")
7778    public boolean willNotCacheDrawing() {
7779        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7780    }
7781
7782    /**
7783     * Indicates whether this view reacts to click events or not.
7784     *
7785     * @return true if the view is clickable, false otherwise
7786     *
7787     * @see #setClickable(boolean)
7788     * @attr ref android.R.styleable#View_clickable
7789     */
7790    @ViewDebug.ExportedProperty
7791    public boolean isClickable() {
7792        return (mViewFlags & CLICKABLE) == CLICKABLE;
7793    }
7794
7795    /**
7796     * Enables or disables click events for this view. When a view
7797     * is clickable it will change its state to "pressed" on every click.
7798     * Subclasses should set the view clickable to visually react to
7799     * user's clicks.
7800     *
7801     * @param clickable true to make the view clickable, false otherwise
7802     *
7803     * @see #isClickable()
7804     * @attr ref android.R.styleable#View_clickable
7805     */
7806    public void setClickable(boolean clickable) {
7807        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7808    }
7809
7810    /**
7811     * Indicates whether this view reacts to long click events or not.
7812     *
7813     * @return true if the view is long clickable, false otherwise
7814     *
7815     * @see #setLongClickable(boolean)
7816     * @attr ref android.R.styleable#View_longClickable
7817     */
7818    public boolean isLongClickable() {
7819        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7820    }
7821
7822    /**
7823     * Enables or disables long click events for this view. When a view is long
7824     * clickable it reacts to the user holding down the button for a longer
7825     * duration than a tap. This event can either launch the listener or a
7826     * context menu.
7827     *
7828     * @param longClickable true to make the view long clickable, false otherwise
7829     * @see #isLongClickable()
7830     * @attr ref android.R.styleable#View_longClickable
7831     */
7832    public void setLongClickable(boolean longClickable) {
7833        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7834    }
7835
7836    /**
7837     * Indicates whether this view reacts to context clicks or not.
7838     *
7839     * @return true if the view is context clickable, false otherwise
7840     * @see #setContextClickable(boolean)
7841     * @attr ref android.R.styleable#View_contextClickable
7842     */
7843    public boolean isContextClickable() {
7844        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
7845    }
7846
7847    /**
7848     * Enables or disables context clicking for this view. This event can launch the listener.
7849     *
7850     * @param contextClickable true to make the view react to a context click, false otherwise
7851     * @see #isContextClickable()
7852     * @attr ref android.R.styleable#View_contextClickable
7853     */
7854    public void setContextClickable(boolean contextClickable) {
7855        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
7856    }
7857
7858    /**
7859     * Sets the pressed state for this view and provides a touch coordinate for
7860     * animation hinting.
7861     *
7862     * @param pressed Pass true to set the View's internal state to "pressed",
7863     *            or false to reverts the View's internal state from a
7864     *            previously set "pressed" state.
7865     * @param x The x coordinate of the touch that caused the press
7866     * @param y The y coordinate of the touch that caused the press
7867     */
7868    private void setPressed(boolean pressed, float x, float y) {
7869        if (pressed) {
7870            drawableHotspotChanged(x, y);
7871        }
7872
7873        setPressed(pressed);
7874    }
7875
7876    /**
7877     * Sets the pressed state for this view.
7878     *
7879     * @see #isClickable()
7880     * @see #setClickable(boolean)
7881     *
7882     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7883     *        the View's internal state from a previously set "pressed" state.
7884     */
7885    public void setPressed(boolean pressed) {
7886        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7887
7888        if (pressed) {
7889            mPrivateFlags |= PFLAG_PRESSED;
7890        } else {
7891            mPrivateFlags &= ~PFLAG_PRESSED;
7892        }
7893
7894        if (needsRefresh) {
7895            refreshDrawableState();
7896        }
7897        dispatchSetPressed(pressed);
7898    }
7899
7900    /**
7901     * Dispatch setPressed to all of this View's children.
7902     *
7903     * @see #setPressed(boolean)
7904     *
7905     * @param pressed The new pressed state
7906     */
7907    protected void dispatchSetPressed(boolean pressed) {
7908    }
7909
7910    /**
7911     * Indicates whether the view is currently in pressed state. Unless
7912     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7913     * the pressed state.
7914     *
7915     * @see #setPressed(boolean)
7916     * @see #isClickable()
7917     * @see #setClickable(boolean)
7918     *
7919     * @return true if the view is currently pressed, false otherwise
7920     */
7921    @ViewDebug.ExportedProperty
7922    public boolean isPressed() {
7923        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7924    }
7925
7926    /**
7927     * @hide
7928     * Indicates whether this view will participate in data collection through
7929     * {@link ViewStructure}.  If true, it will not provide any data
7930     * for itself or its children.  If false, the normal data collection will be allowed.
7931     *
7932     * @return Returns false if assist data collection is not blocked, else true.
7933     *
7934     * @see #setAssistBlocked(boolean)
7935     * @attr ref android.R.styleable#View_assistBlocked
7936     */
7937    public boolean isAssistBlocked() {
7938        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
7939    }
7940
7941    /**
7942     * @hide
7943     * Controls whether assist data collection from this view and its children is enabled
7944     * (that is, whether {@link #onProvideStructure} and
7945     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
7946     * allowing normal assist collection.  Setting this to false will disable assist collection.
7947     *
7948     * @param enabled Set to true to <em>disable</em> assist data collection, or false
7949     * (the default) to allow it.
7950     *
7951     * @see #isAssistBlocked()
7952     * @see #onProvideStructure
7953     * @see #onProvideVirtualStructure
7954     * @attr ref android.R.styleable#View_assistBlocked
7955     */
7956    public void setAssistBlocked(boolean enabled) {
7957        if (enabled) {
7958            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
7959        } else {
7960            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
7961        }
7962    }
7963
7964    /**
7965     * Indicates whether this view will save its state (that is,
7966     * whether its {@link #onSaveInstanceState} method will be called).
7967     *
7968     * @return Returns true if the view state saving is enabled, else false.
7969     *
7970     * @see #setSaveEnabled(boolean)
7971     * @attr ref android.R.styleable#View_saveEnabled
7972     */
7973    public boolean isSaveEnabled() {
7974        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7975    }
7976
7977    /**
7978     * Controls whether the saving of this view's state is
7979     * enabled (that is, whether its {@link #onSaveInstanceState} method
7980     * will be called).  Note that even if freezing is enabled, the
7981     * view still must have an id assigned to it (via {@link #setId(int)})
7982     * for its state to be saved.  This flag can only disable the
7983     * saving of this view; any child views may still have their state saved.
7984     *
7985     * @param enabled Set to false to <em>disable</em> state saving, or true
7986     * (the default) to allow it.
7987     *
7988     * @see #isSaveEnabled()
7989     * @see #setId(int)
7990     * @see #onSaveInstanceState()
7991     * @attr ref android.R.styleable#View_saveEnabled
7992     */
7993    public void setSaveEnabled(boolean enabled) {
7994        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7995    }
7996
7997    /**
7998     * Gets whether the framework should discard touches when the view's
7999     * window is obscured by another visible window.
8000     * Refer to the {@link View} security documentation for more details.
8001     *
8002     * @return True if touch filtering is enabled.
8003     *
8004     * @see #setFilterTouchesWhenObscured(boolean)
8005     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8006     */
8007    @ViewDebug.ExportedProperty
8008    public boolean getFilterTouchesWhenObscured() {
8009        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8010    }
8011
8012    /**
8013     * Sets whether the framework should discard touches when the view's
8014     * window is obscured by another visible window.
8015     * Refer to the {@link View} security documentation for more details.
8016     *
8017     * @param enabled True if touch filtering should be enabled.
8018     *
8019     * @see #getFilterTouchesWhenObscured
8020     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8021     */
8022    public void setFilterTouchesWhenObscured(boolean enabled) {
8023        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8024                FILTER_TOUCHES_WHEN_OBSCURED);
8025    }
8026
8027    /**
8028     * Indicates whether the entire hierarchy under this view will save its
8029     * state when a state saving traversal occurs from its parent.  The default
8030     * is true; if false, these views will not be saved unless
8031     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8032     *
8033     * @return Returns true if the view state saving from parent is enabled, else false.
8034     *
8035     * @see #setSaveFromParentEnabled(boolean)
8036     */
8037    public boolean isSaveFromParentEnabled() {
8038        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8039    }
8040
8041    /**
8042     * Controls whether the entire hierarchy under this view will save its
8043     * state when a state saving traversal occurs from its parent.  The default
8044     * is true; if false, these views will not be saved unless
8045     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8046     *
8047     * @param enabled Set to false to <em>disable</em> state saving, or true
8048     * (the default) to allow it.
8049     *
8050     * @see #isSaveFromParentEnabled()
8051     * @see #setId(int)
8052     * @see #onSaveInstanceState()
8053     */
8054    public void setSaveFromParentEnabled(boolean enabled) {
8055        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8056    }
8057
8058
8059    /**
8060     * Returns whether this View is able to take focus.
8061     *
8062     * @return True if this view can take focus, or false otherwise.
8063     * @attr ref android.R.styleable#View_focusable
8064     */
8065    @ViewDebug.ExportedProperty(category = "focus")
8066    public final boolean isFocusable() {
8067        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8068    }
8069
8070    /**
8071     * When a view is focusable, it may not want to take focus when in touch mode.
8072     * For example, a button would like focus when the user is navigating via a D-pad
8073     * so that the user can click on it, but once the user starts touching the screen,
8074     * the button shouldn't take focus
8075     * @return Whether the view is focusable in touch mode.
8076     * @attr ref android.R.styleable#View_focusableInTouchMode
8077     */
8078    @ViewDebug.ExportedProperty
8079    public final boolean isFocusableInTouchMode() {
8080        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8081    }
8082
8083    /**
8084     * Find the nearest view in the specified direction that can take focus.
8085     * This does not actually give focus to that view.
8086     *
8087     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8088     *
8089     * @return The nearest focusable in the specified direction, or null if none
8090     *         can be found.
8091     */
8092    public View focusSearch(@FocusRealDirection int direction) {
8093        if (mParent != null) {
8094            return mParent.focusSearch(this, direction);
8095        } else {
8096            return null;
8097        }
8098    }
8099
8100    /**
8101     * This method is the last chance for the focused view and its ancestors to
8102     * respond to an arrow key. This is called when the focused view did not
8103     * consume the key internally, nor could the view system find a new view in
8104     * the requested direction to give focus to.
8105     *
8106     * @param focused The currently focused view.
8107     * @param direction The direction focus wants to move. One of FOCUS_UP,
8108     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8109     * @return True if the this view consumed this unhandled move.
8110     */
8111    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8112        return false;
8113    }
8114
8115    /**
8116     * If a user manually specified the next view id for a particular direction,
8117     * use the root to look up the view.
8118     * @param root The root view of the hierarchy containing this view.
8119     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8120     * or FOCUS_BACKWARD.
8121     * @return The user specified next view, or null if there is none.
8122     */
8123    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8124        switch (direction) {
8125            case FOCUS_LEFT:
8126                if (mNextFocusLeftId == View.NO_ID) return null;
8127                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8128            case FOCUS_RIGHT:
8129                if (mNextFocusRightId == View.NO_ID) return null;
8130                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8131            case FOCUS_UP:
8132                if (mNextFocusUpId == View.NO_ID) return null;
8133                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8134            case FOCUS_DOWN:
8135                if (mNextFocusDownId == View.NO_ID) return null;
8136                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8137            case FOCUS_FORWARD:
8138                if (mNextFocusForwardId == View.NO_ID) return null;
8139                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8140            case FOCUS_BACKWARD: {
8141                if (mID == View.NO_ID) return null;
8142                final int id = mID;
8143                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8144                    @Override
8145                    public boolean apply(View t) {
8146                        return t.mNextFocusForwardId == id;
8147                    }
8148                });
8149            }
8150        }
8151        return null;
8152    }
8153
8154    private View findViewInsideOutShouldExist(View root, int id) {
8155        if (mMatchIdPredicate == null) {
8156            mMatchIdPredicate = new MatchIdPredicate();
8157        }
8158        mMatchIdPredicate.mId = id;
8159        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8160        if (result == null) {
8161            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8162        }
8163        return result;
8164    }
8165
8166    /**
8167     * Find and return all focusable views that are descendants of this view,
8168     * possibly including this view if it is focusable itself.
8169     *
8170     * @param direction The direction of the focus
8171     * @return A list of focusable views
8172     */
8173    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8174        ArrayList<View> result = new ArrayList<View>(24);
8175        addFocusables(result, direction);
8176        return result;
8177    }
8178
8179    /**
8180     * Add any focusable views that are descendants of this view (possibly
8181     * including this view if it is focusable itself) to views.  If we are in touch mode,
8182     * only add views that are also focusable in touch mode.
8183     *
8184     * @param views Focusable views found so far
8185     * @param direction The direction of the focus
8186     */
8187    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8188        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
8189    }
8190
8191    /**
8192     * Adds any focusable views that are descendants of this view (possibly
8193     * including this view if it is focusable itself) to views. This method
8194     * adds all focusable views regardless if we are in touch mode or
8195     * only views focusable in touch mode if we are in touch mode or
8196     * only views that can take accessibility focus if accessibility is enabled
8197     * depending on the focusable mode parameter.
8198     *
8199     * @param views Focusable views found so far or null if all we are interested is
8200     *        the number of focusables.
8201     * @param direction The direction of the focus.
8202     * @param focusableMode The type of focusables to be added.
8203     *
8204     * @see #FOCUSABLES_ALL
8205     * @see #FOCUSABLES_TOUCH_MODE
8206     */
8207    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8208            @FocusableMode int focusableMode) {
8209        if (views == null) {
8210            return;
8211        }
8212        if (!isFocusable()) {
8213            return;
8214        }
8215        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8216                && isInTouchMode() && !isFocusableInTouchMode()) {
8217            return;
8218        }
8219        views.add(this);
8220    }
8221
8222    /**
8223     * Finds the Views that contain given text. The containment is case insensitive.
8224     * The search is performed by either the text that the View renders or the content
8225     * description that describes the view for accessibility purposes and the view does
8226     * not render or both. Clients can specify how the search is to be performed via
8227     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8228     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8229     *
8230     * @param outViews The output list of matching Views.
8231     * @param searched The text to match against.
8232     *
8233     * @see #FIND_VIEWS_WITH_TEXT
8234     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8235     * @see #setContentDescription(CharSequence)
8236     */
8237    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8238            @FindViewFlags int flags) {
8239        if (getAccessibilityNodeProvider() != null) {
8240            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8241                outViews.add(this);
8242            }
8243        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8244                && (searched != null && searched.length() > 0)
8245                && (mContentDescription != null && mContentDescription.length() > 0)) {
8246            String searchedLowerCase = searched.toString().toLowerCase();
8247            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8248            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8249                outViews.add(this);
8250            }
8251        }
8252    }
8253
8254    /**
8255     * Find and return all touchable views that are descendants of this view,
8256     * possibly including this view if it is touchable itself.
8257     *
8258     * @return A list of touchable views
8259     */
8260    public ArrayList<View> getTouchables() {
8261        ArrayList<View> result = new ArrayList<View>();
8262        addTouchables(result);
8263        return result;
8264    }
8265
8266    /**
8267     * Add any touchable views that are descendants of this view (possibly
8268     * including this view if it is touchable itself) to views.
8269     *
8270     * @param views Touchable views found so far
8271     */
8272    public void addTouchables(ArrayList<View> views) {
8273        final int viewFlags = mViewFlags;
8274
8275        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8276                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8277                && (viewFlags & ENABLED_MASK) == ENABLED) {
8278            views.add(this);
8279        }
8280    }
8281
8282    /**
8283     * Returns whether this View is accessibility focused.
8284     *
8285     * @return True if this View is accessibility focused.
8286     */
8287    public boolean isAccessibilityFocused() {
8288        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8289    }
8290
8291    /**
8292     * Call this to try to give accessibility focus to this view.
8293     *
8294     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8295     * returns false or the view is no visible or the view already has accessibility
8296     * focus.
8297     *
8298     * See also {@link #focusSearch(int)}, which is what you call to say that you
8299     * have focus, and you want your parent to look for the next one.
8300     *
8301     * @return Whether this view actually took accessibility focus.
8302     *
8303     * @hide
8304     */
8305    public boolean requestAccessibilityFocus() {
8306        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8307        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8308            return false;
8309        }
8310        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8311            return false;
8312        }
8313        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8314            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8315            ViewRootImpl viewRootImpl = getViewRootImpl();
8316            if (viewRootImpl != null) {
8317                viewRootImpl.setAccessibilityFocus(this, null);
8318            }
8319            invalidate();
8320            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8321            return true;
8322        }
8323        return false;
8324    }
8325
8326    /**
8327     * Call this to try to clear accessibility focus of this view.
8328     *
8329     * See also {@link #focusSearch(int)}, which is what you call to say that you
8330     * have focus, and you want your parent to look for the next one.
8331     *
8332     * @hide
8333     */
8334    public void clearAccessibilityFocus() {
8335        clearAccessibilityFocusNoCallbacks();
8336        // Clear the global reference of accessibility focus if this
8337        // view or any of its descendants had accessibility focus.
8338        ViewRootImpl viewRootImpl = getViewRootImpl();
8339        if (viewRootImpl != null) {
8340            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8341            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8342                viewRootImpl.setAccessibilityFocus(null, null);
8343            }
8344        }
8345    }
8346
8347    private void sendAccessibilityHoverEvent(int eventType) {
8348        // Since we are not delivering to a client accessibility events from not
8349        // important views (unless the clinet request that) we need to fire the
8350        // event from the deepest view exposed to the client. As a consequence if
8351        // the user crosses a not exposed view the client will see enter and exit
8352        // of the exposed predecessor followed by and enter and exit of that same
8353        // predecessor when entering and exiting the not exposed descendant. This
8354        // is fine since the client has a clear idea which view is hovered at the
8355        // price of a couple more events being sent. This is a simple and
8356        // working solution.
8357        View source = this;
8358        while (true) {
8359            if (source.includeForAccessibility()) {
8360                source.sendAccessibilityEvent(eventType);
8361                return;
8362            }
8363            ViewParent parent = source.getParent();
8364            if (parent instanceof View) {
8365                source = (View) parent;
8366            } else {
8367                return;
8368            }
8369        }
8370    }
8371
8372    /**
8373     * Clears accessibility focus without calling any callback methods
8374     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8375     * is used for clearing accessibility focus when giving this focus to
8376     * another view.
8377     */
8378    void clearAccessibilityFocusNoCallbacks() {
8379        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8380            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8381            invalidate();
8382            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8383        }
8384    }
8385
8386    /**
8387     * Call this to try to give focus to a specific view or to one of its
8388     * descendants.
8389     *
8390     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8391     * false), or if it is focusable and it is not focusable in touch mode
8392     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8393     *
8394     * See also {@link #focusSearch(int)}, which is what you call to say that you
8395     * have focus, and you want your parent to look for the next one.
8396     *
8397     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8398     * {@link #FOCUS_DOWN} and <code>null</code>.
8399     *
8400     * @return Whether this view or one of its descendants actually took focus.
8401     */
8402    public final boolean requestFocus() {
8403        return requestFocus(View.FOCUS_DOWN);
8404    }
8405
8406    /**
8407     * Call this to try to give focus to a specific view or to one of its
8408     * descendants and give it a hint about what direction focus is heading.
8409     *
8410     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8411     * false), or if it is focusable and it is not focusable in touch mode
8412     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8413     *
8414     * See also {@link #focusSearch(int)}, which is what you call to say that you
8415     * have focus, and you want your parent to look for the next one.
8416     *
8417     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8418     * <code>null</code> set for the previously focused rectangle.
8419     *
8420     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8421     * @return Whether this view or one of its descendants actually took focus.
8422     */
8423    public final boolean requestFocus(int direction) {
8424        return requestFocus(direction, null);
8425    }
8426
8427    /**
8428     * Call this to try to give focus to a specific view or to one of its descendants
8429     * and give it hints about the direction and a specific rectangle that the focus
8430     * is coming from.  The rectangle can help give larger views a finer grained hint
8431     * about where focus is coming from, and therefore, where to show selection, or
8432     * forward focus change internally.
8433     *
8434     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8435     * false), or if it is focusable and it is not focusable in touch mode
8436     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8437     *
8438     * A View will not take focus if it is not visible.
8439     *
8440     * A View will not take focus if one of its parents has
8441     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
8442     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
8443     *
8444     * See also {@link #focusSearch(int)}, which is what you call to say that you
8445     * have focus, and you want your parent to look for the next one.
8446     *
8447     * You may wish to override this method if your custom {@link View} has an internal
8448     * {@link View} that it wishes to forward the request to.
8449     *
8450     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8451     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8452     *        to give a finer grained hint about where focus is coming from.  May be null
8453     *        if there is no hint.
8454     * @return Whether this view or one of its descendants actually took focus.
8455     */
8456    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8457        return requestFocusNoSearch(direction, previouslyFocusedRect);
8458    }
8459
8460    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8461        // need to be focusable
8462        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
8463                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8464            return false;
8465        }
8466
8467        // need to be focusable in touch mode if in touch mode
8468        if (isInTouchMode() &&
8469            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
8470               return false;
8471        }
8472
8473        // need to not have any parents blocking us
8474        if (hasAncestorThatBlocksDescendantFocus()) {
8475            return false;
8476        }
8477
8478        handleFocusGainInternal(direction, previouslyFocusedRect);
8479        return true;
8480    }
8481
8482    /**
8483     * Call this to try to give focus to a specific view or to one of its descendants. This is a
8484     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
8485     * touch mode to request focus when they are touched.
8486     *
8487     * @return Whether this view or one of its descendants actually took focus.
8488     *
8489     * @see #isInTouchMode()
8490     *
8491     */
8492    public final boolean requestFocusFromTouch() {
8493        // Leave touch mode if we need to
8494        if (isInTouchMode()) {
8495            ViewRootImpl viewRoot = getViewRootImpl();
8496            if (viewRoot != null) {
8497                viewRoot.ensureTouchMode(false);
8498            }
8499        }
8500        return requestFocus(View.FOCUS_DOWN);
8501    }
8502
8503    /**
8504     * @return Whether any ancestor of this view blocks descendant focus.
8505     */
8506    private boolean hasAncestorThatBlocksDescendantFocus() {
8507        final boolean focusableInTouchMode = isFocusableInTouchMode();
8508        ViewParent ancestor = mParent;
8509        while (ancestor instanceof ViewGroup) {
8510            final ViewGroup vgAncestor = (ViewGroup) ancestor;
8511            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
8512                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
8513                return true;
8514            } else {
8515                ancestor = vgAncestor.getParent();
8516            }
8517        }
8518        return false;
8519    }
8520
8521    /**
8522     * Gets the mode for determining whether this View is important for accessibility
8523     * which is if it fires accessibility events and if it is reported to
8524     * accessibility services that query the screen.
8525     *
8526     * @return The mode for determining whether a View is important for accessibility.
8527     *
8528     * @attr ref android.R.styleable#View_importantForAccessibility
8529     *
8530     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8531     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8532     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8533     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8534     */
8535    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
8536            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
8537            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
8538            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
8539            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
8540                    to = "noHideDescendants")
8541        })
8542    public int getImportantForAccessibility() {
8543        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8544                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8545    }
8546
8547    /**
8548     * Sets the live region mode for this view. This indicates to accessibility
8549     * services whether they should automatically notify the user about changes
8550     * to the view's content description or text, or to the content descriptions
8551     * or text of the view's children (where applicable).
8552     * <p>
8553     * For example, in a login screen with a TextView that displays an "incorrect
8554     * password" notification, that view should be marked as a live region with
8555     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8556     * <p>
8557     * To disable change notifications for this view, use
8558     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
8559     * mode for most views.
8560     * <p>
8561     * To indicate that the user should be notified of changes, use
8562     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8563     * <p>
8564     * If the view's changes should interrupt ongoing speech and notify the user
8565     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
8566     *
8567     * @param mode The live region mode for this view, one of:
8568     *        <ul>
8569     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
8570     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
8571     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
8572     *        </ul>
8573     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8574     */
8575    public void setAccessibilityLiveRegion(int mode) {
8576        if (mode != getAccessibilityLiveRegion()) {
8577            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8578            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
8579                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8580            notifyViewAccessibilityStateChangedIfNeeded(
8581                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8582        }
8583    }
8584
8585    /**
8586     * Gets the live region mode for this View.
8587     *
8588     * @return The live region mode for the view.
8589     *
8590     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8591     *
8592     * @see #setAccessibilityLiveRegion(int)
8593     */
8594    public int getAccessibilityLiveRegion() {
8595        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
8596                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
8597    }
8598
8599    /**
8600     * Sets how to determine whether this view is important for accessibility
8601     * which is if it fires accessibility events and if it is reported to
8602     * accessibility services that query the screen.
8603     *
8604     * @param mode How to determine whether this view is important for accessibility.
8605     *
8606     * @attr ref android.R.styleable#View_importantForAccessibility
8607     *
8608     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8609     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8610     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8611     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8612     */
8613    public void setImportantForAccessibility(int mode) {
8614        final int oldMode = getImportantForAccessibility();
8615        if (mode != oldMode) {
8616            // If we're moving between AUTO and another state, we might not need
8617            // to send a subtree changed notification. We'll store the computed
8618            // importance, since we'll need to check it later to make sure.
8619            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
8620                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8621            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
8622            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8623            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
8624                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8625            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
8626                notifySubtreeAccessibilityStateChangedIfNeeded();
8627            } else {
8628                notifyViewAccessibilityStateChangedIfNeeded(
8629                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8630            }
8631        }
8632    }
8633
8634    /**
8635     * Computes whether this view should be exposed for accessibility. In
8636     * general, views that are interactive or provide information are exposed
8637     * while views that serve only as containers are hidden.
8638     * <p>
8639     * If an ancestor of this view has importance
8640     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
8641     * returns <code>false</code>.
8642     * <p>
8643     * Otherwise, the value is computed according to the view's
8644     * {@link #getImportantForAccessibility()} value:
8645     * <ol>
8646     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
8647     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
8648     * </code>
8649     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
8650     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
8651     * view satisfies any of the following:
8652     * <ul>
8653     * <li>Is actionable, e.g. {@link #isClickable()},
8654     * {@link #isLongClickable()}, or {@link #isFocusable()}
8655     * <li>Has an {@link AccessibilityDelegate}
8656     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
8657     * {@link OnKeyListener}, etc.
8658     * <li>Is an accessibility live region, e.g.
8659     * {@link #getAccessibilityLiveRegion()} is not
8660     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
8661     * </ul>
8662     * </ol>
8663     *
8664     * @return Whether the view is exposed for accessibility.
8665     * @see #setImportantForAccessibility(int)
8666     * @see #getImportantForAccessibility()
8667     */
8668    public boolean isImportantForAccessibility() {
8669        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8670                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8671        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8672                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8673            return false;
8674        }
8675
8676        // Check parent mode to ensure we're not hidden.
8677        ViewParent parent = mParent;
8678        while (parent instanceof View) {
8679            if (((View) parent).getImportantForAccessibility()
8680                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8681                return false;
8682            }
8683            parent = parent.getParent();
8684        }
8685
8686        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8687                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8688                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8689    }
8690
8691    /**
8692     * Gets the parent for accessibility purposes. Note that the parent for
8693     * accessibility is not necessary the immediate parent. It is the first
8694     * predecessor that is important for accessibility.
8695     *
8696     * @return The parent for accessibility purposes.
8697     */
8698    public ViewParent getParentForAccessibility() {
8699        if (mParent instanceof View) {
8700            View parentView = (View) mParent;
8701            if (parentView.includeForAccessibility()) {
8702                return mParent;
8703            } else {
8704                return mParent.getParentForAccessibility();
8705            }
8706        }
8707        return null;
8708    }
8709
8710    /**
8711     * Adds the children of this View relevant for accessibility to the given list
8712     * as output. Since some Views are not important for accessibility the added
8713     * child views are not necessarily direct children of this view, rather they are
8714     * the first level of descendants important for accessibility.
8715     *
8716     * @param outChildren The output list that will receive children for accessibility.
8717     */
8718    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
8719
8720    }
8721
8722    /**
8723     * Whether to regard this view for accessibility. A view is regarded for
8724     * accessibility if it is important for accessibility or the querying
8725     * accessibility service has explicitly requested that view not
8726     * important for accessibility are regarded.
8727     *
8728     * @return Whether to regard the view for accessibility.
8729     *
8730     * @hide
8731     */
8732    public boolean includeForAccessibility() {
8733        if (mAttachInfo != null) {
8734            return (mAttachInfo.mAccessibilityFetchFlags
8735                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8736                    || isImportantForAccessibility();
8737        }
8738        return false;
8739    }
8740
8741    /**
8742     * Returns whether the View is considered actionable from
8743     * accessibility perspective. Such view are important for
8744     * accessibility.
8745     *
8746     * @return True if the view is actionable for accessibility.
8747     *
8748     * @hide
8749     */
8750    public boolean isActionableForAccessibility() {
8751        return (isClickable() || isLongClickable() || isFocusable());
8752    }
8753
8754    /**
8755     * Returns whether the View has registered callbacks which makes it
8756     * important for accessibility.
8757     *
8758     * @return True if the view is actionable for accessibility.
8759     */
8760    private boolean hasListenersForAccessibility() {
8761        ListenerInfo info = getListenerInfo();
8762        return mTouchDelegate != null || info.mOnKeyListener != null
8763                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8764                || info.mOnHoverListener != null || info.mOnDragListener != null;
8765    }
8766
8767    /**
8768     * Notifies that the accessibility state of this view changed. The change
8769     * is local to this view and does not represent structural changes such
8770     * as children and parent. For example, the view became focusable. The
8771     * notification is at at most once every
8772     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8773     * to avoid unnecessary load to the system. Also once a view has a pending
8774     * notification this method is a NOP until the notification has been sent.
8775     *
8776     * @hide
8777     */
8778    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8779        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
8780            return;
8781        }
8782        if (mSendViewStateChangedAccessibilityEvent == null) {
8783            mSendViewStateChangedAccessibilityEvent =
8784                    new SendViewStateChangedAccessibilityEvent();
8785        }
8786        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8787    }
8788
8789    /**
8790     * Notifies that the accessibility state of this view changed. The change
8791     * is *not* local to this view and does represent structural changes such
8792     * as children and parent. For example, the view size changed. The
8793     * notification is at at most once every
8794     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8795     * to avoid unnecessary load to the system. Also once a view has a pending
8796     * notification this method is a NOP until the notification has been sent.
8797     *
8798     * @hide
8799     */
8800    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8801        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
8802            return;
8803        }
8804        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8805            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8806            if (mParent != null) {
8807                try {
8808                    mParent.notifySubtreeAccessibilityStateChanged(
8809                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8810                } catch (AbstractMethodError e) {
8811                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8812                            " does not fully implement ViewParent", e);
8813                }
8814            }
8815        }
8816    }
8817
8818    /**
8819     * Change the visibility of the View without triggering any other changes. This is
8820     * important for transitions, where visibility changes should not adjust focus or
8821     * trigger a new layout. This is only used when the visibility has already been changed
8822     * and we need a transient value during an animation. When the animation completes,
8823     * the original visibility value is always restored.
8824     *
8825     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8826     * @hide
8827     */
8828    public void setTransitionVisibility(@Visibility int visibility) {
8829        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
8830    }
8831
8832    /**
8833     * Reset the flag indicating the accessibility state of the subtree rooted
8834     * at this view changed.
8835     */
8836    void resetSubtreeAccessibilityStateChanged() {
8837        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8838    }
8839
8840    /**
8841     * Report an accessibility action to this view's parents for delegated processing.
8842     *
8843     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8844     * call this method to delegate an accessibility action to a supporting parent. If the parent
8845     * returns true from its
8846     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8847     * method this method will return true to signify that the action was consumed.</p>
8848     *
8849     * <p>This method is useful for implementing nested scrolling child views. If
8850     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8851     * a custom view implementation may invoke this method to allow a parent to consume the
8852     * scroll first. If this method returns true the custom view should skip its own scrolling
8853     * behavior.</p>
8854     *
8855     * @param action Accessibility action to delegate
8856     * @param arguments Optional action arguments
8857     * @return true if the action was consumed by a parent
8858     */
8859    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8860        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8861            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8862                return true;
8863            }
8864        }
8865        return false;
8866    }
8867
8868    /**
8869     * Performs the specified accessibility action on the view. For
8870     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8871     * <p>
8872     * If an {@link AccessibilityDelegate} has been specified via calling
8873     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8874     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8875     * is responsible for handling this call.
8876     * </p>
8877     *
8878     * <p>The default implementation will delegate
8879     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8880     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8881     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8882     *
8883     * @param action The action to perform.
8884     * @param arguments Optional action arguments.
8885     * @return Whether the action was performed.
8886     */
8887    public boolean performAccessibilityAction(int action, Bundle arguments) {
8888      if (mAccessibilityDelegate != null) {
8889          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8890      } else {
8891          return performAccessibilityActionInternal(action, arguments);
8892      }
8893    }
8894
8895   /**
8896    * @see #performAccessibilityAction(int, Bundle)
8897    *
8898    * Note: Called from the default {@link AccessibilityDelegate}.
8899    *
8900    * @hide
8901    */
8902    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8903        if (isNestedScrollingEnabled()
8904                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8905                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
8906                || action == R.id.accessibilityActionScrollUp
8907                || action == R.id.accessibilityActionScrollLeft
8908                || action == R.id.accessibilityActionScrollDown
8909                || action == R.id.accessibilityActionScrollRight)) {
8910            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8911                return true;
8912            }
8913        }
8914
8915        switch (action) {
8916            case AccessibilityNodeInfo.ACTION_CLICK: {
8917                if (isClickable()) {
8918                    performClick();
8919                    return true;
8920                }
8921            } break;
8922            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8923                if (isLongClickable()) {
8924                    performLongClick();
8925                    return true;
8926                }
8927            } break;
8928            case AccessibilityNodeInfo.ACTION_FOCUS: {
8929                if (!hasFocus()) {
8930                    // Get out of touch mode since accessibility
8931                    // wants to move focus around.
8932                    getViewRootImpl().ensureTouchMode(false);
8933                    return requestFocus();
8934                }
8935            } break;
8936            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8937                if (hasFocus()) {
8938                    clearFocus();
8939                    return !isFocused();
8940                }
8941            } break;
8942            case AccessibilityNodeInfo.ACTION_SELECT: {
8943                if (!isSelected()) {
8944                    setSelected(true);
8945                    return isSelected();
8946                }
8947            } break;
8948            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8949                if (isSelected()) {
8950                    setSelected(false);
8951                    return !isSelected();
8952                }
8953            } break;
8954            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8955                if (!isAccessibilityFocused()) {
8956                    return requestAccessibilityFocus();
8957                }
8958            } break;
8959            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8960                if (isAccessibilityFocused()) {
8961                    clearAccessibilityFocus();
8962                    return true;
8963                }
8964            } break;
8965            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8966                if (arguments != null) {
8967                    final int granularity = arguments.getInt(
8968                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8969                    final boolean extendSelection = arguments.getBoolean(
8970                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8971                    return traverseAtGranularity(granularity, true, extendSelection);
8972                }
8973            } break;
8974            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8975                if (arguments != null) {
8976                    final int granularity = arguments.getInt(
8977                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8978                    final boolean extendSelection = arguments.getBoolean(
8979                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8980                    return traverseAtGranularity(granularity, false, extendSelection);
8981                }
8982            } break;
8983            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8984                CharSequence text = getIterableTextForAccessibility();
8985                if (text == null) {
8986                    return false;
8987                }
8988                final int start = (arguments != null) ? arguments.getInt(
8989                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8990                final int end = (arguments != null) ? arguments.getInt(
8991                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8992                // Only cursor position can be specified (selection length == 0)
8993                if ((getAccessibilitySelectionStart() != start
8994                        || getAccessibilitySelectionEnd() != end)
8995                        && (start == end)) {
8996                    setAccessibilitySelection(start, end);
8997                    notifyViewAccessibilityStateChangedIfNeeded(
8998                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8999                    return true;
9000                }
9001            } break;
9002            case R.id.accessibilityActionShowOnScreen: {
9003                if (mAttachInfo != null) {
9004                    final Rect r = mAttachInfo.mTmpInvalRect;
9005                    getDrawingRect(r);
9006                    return requestRectangleOnScreen(r, true);
9007                }
9008            } break;
9009            case R.id.accessibilityActionContextClick: {
9010                if (isContextClickable()) {
9011                    performContextClick();
9012                    return true;
9013                }
9014            } break;
9015        }
9016        return false;
9017    }
9018
9019    private boolean traverseAtGranularity(int granularity, boolean forward,
9020            boolean extendSelection) {
9021        CharSequence text = getIterableTextForAccessibility();
9022        if (text == null || text.length() == 0) {
9023            return false;
9024        }
9025        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9026        if (iterator == null) {
9027            return false;
9028        }
9029        int current = getAccessibilitySelectionEnd();
9030        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9031            current = forward ? 0 : text.length();
9032        }
9033        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9034        if (range == null) {
9035            return false;
9036        }
9037        final int segmentStart = range[0];
9038        final int segmentEnd = range[1];
9039        int selectionStart;
9040        int selectionEnd;
9041        if (extendSelection && isAccessibilitySelectionExtendable()) {
9042            selectionStart = getAccessibilitySelectionStart();
9043            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9044                selectionStart = forward ? segmentStart : segmentEnd;
9045            }
9046            selectionEnd = forward ? segmentEnd : segmentStart;
9047        } else {
9048            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9049        }
9050        setAccessibilitySelection(selectionStart, selectionEnd);
9051        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9052                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9053        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9054        return true;
9055    }
9056
9057    /**
9058     * Gets the text reported for accessibility purposes.
9059     *
9060     * @return The accessibility text.
9061     *
9062     * @hide
9063     */
9064    public CharSequence getIterableTextForAccessibility() {
9065        return getContentDescription();
9066    }
9067
9068    /**
9069     * Gets whether accessibility selection can be extended.
9070     *
9071     * @return If selection is extensible.
9072     *
9073     * @hide
9074     */
9075    public boolean isAccessibilitySelectionExtendable() {
9076        return false;
9077    }
9078
9079    /**
9080     * @hide
9081     */
9082    public int getAccessibilitySelectionStart() {
9083        return mAccessibilityCursorPosition;
9084    }
9085
9086    /**
9087     * @hide
9088     */
9089    public int getAccessibilitySelectionEnd() {
9090        return getAccessibilitySelectionStart();
9091    }
9092
9093    /**
9094     * @hide
9095     */
9096    public void setAccessibilitySelection(int start, int end) {
9097        if (start ==  end && end == mAccessibilityCursorPosition) {
9098            return;
9099        }
9100        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9101            mAccessibilityCursorPosition = start;
9102        } else {
9103            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9104        }
9105        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9106    }
9107
9108    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9109            int fromIndex, int toIndex) {
9110        if (mParent == null) {
9111            return;
9112        }
9113        AccessibilityEvent event = AccessibilityEvent.obtain(
9114                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9115        onInitializeAccessibilityEvent(event);
9116        onPopulateAccessibilityEvent(event);
9117        event.setFromIndex(fromIndex);
9118        event.setToIndex(toIndex);
9119        event.setAction(action);
9120        event.setMovementGranularity(granularity);
9121        mParent.requestSendAccessibilityEvent(this, event);
9122    }
9123
9124    /**
9125     * @hide
9126     */
9127    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9128        switch (granularity) {
9129            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9130                CharSequence text = getIterableTextForAccessibility();
9131                if (text != null && text.length() > 0) {
9132                    CharacterTextSegmentIterator iterator =
9133                        CharacterTextSegmentIterator.getInstance(
9134                                mContext.getResources().getConfiguration().locale);
9135                    iterator.initialize(text.toString());
9136                    return iterator;
9137                }
9138            } break;
9139            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9140                CharSequence text = getIterableTextForAccessibility();
9141                if (text != null && text.length() > 0) {
9142                    WordTextSegmentIterator iterator =
9143                        WordTextSegmentIterator.getInstance(
9144                                mContext.getResources().getConfiguration().locale);
9145                    iterator.initialize(text.toString());
9146                    return iterator;
9147                }
9148            } break;
9149            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9150                CharSequence text = getIterableTextForAccessibility();
9151                if (text != null && text.length() > 0) {
9152                    ParagraphTextSegmentIterator iterator =
9153                        ParagraphTextSegmentIterator.getInstance();
9154                    iterator.initialize(text.toString());
9155                    return iterator;
9156                }
9157            } break;
9158        }
9159        return null;
9160    }
9161
9162    /**
9163     * @hide
9164     */
9165    public void dispatchStartTemporaryDetach() {
9166        onStartTemporaryDetach();
9167    }
9168
9169    /**
9170     * This is called when a container is going to temporarily detach a child, with
9171     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9172     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9173     * {@link #onDetachedFromWindow()} when the container is done.
9174     */
9175    public void onStartTemporaryDetach() {
9176        removeUnsetPressCallback();
9177        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9178    }
9179
9180    /**
9181     * @hide
9182     */
9183    public void dispatchFinishTemporaryDetach() {
9184        onFinishTemporaryDetach();
9185    }
9186
9187    /**
9188     * Called after {@link #onStartTemporaryDetach} when the container is done
9189     * changing the view.
9190     */
9191    public void onFinishTemporaryDetach() {
9192    }
9193
9194    /**
9195     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9196     * for this view's window.  Returns null if the view is not currently attached
9197     * to the window.  Normally you will not need to use this directly, but
9198     * just use the standard high-level event callbacks like
9199     * {@link #onKeyDown(int, KeyEvent)}.
9200     */
9201    public KeyEvent.DispatcherState getKeyDispatcherState() {
9202        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9203    }
9204
9205    /**
9206     * Dispatch a key event before it is processed by any input method
9207     * associated with the view hierarchy.  This can be used to intercept
9208     * key events in special situations before the IME consumes them; a
9209     * typical example would be handling the BACK key to update the application's
9210     * UI instead of allowing the IME to see it and close itself.
9211     *
9212     * @param event The key event to be dispatched.
9213     * @return True if the event was handled, false otherwise.
9214     */
9215    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9216        return onKeyPreIme(event.getKeyCode(), event);
9217    }
9218
9219    /**
9220     * Dispatch a key event to the next view on the focus path. This path runs
9221     * from the top of the view tree down to the currently focused view. If this
9222     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9223     * the next node down the focus path. This method also fires any key
9224     * listeners.
9225     *
9226     * @param event The key event to be dispatched.
9227     * @return True if the event was handled, false otherwise.
9228     */
9229    public boolean dispatchKeyEvent(KeyEvent event) {
9230        if (mInputEventConsistencyVerifier != null) {
9231            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9232        }
9233
9234        // Give any attached key listener a first crack at the event.
9235        //noinspection SimplifiableIfStatement
9236        ListenerInfo li = mListenerInfo;
9237        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9238                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9239            return true;
9240        }
9241
9242        if (event.dispatch(this, mAttachInfo != null
9243                ? mAttachInfo.mKeyDispatchState : null, this)) {
9244            return true;
9245        }
9246
9247        if (mInputEventConsistencyVerifier != null) {
9248            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9249        }
9250        return false;
9251    }
9252
9253    /**
9254     * Dispatches a key shortcut event.
9255     *
9256     * @param event The key event to be dispatched.
9257     * @return True if the event was handled by the view, false otherwise.
9258     */
9259    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9260        return onKeyShortcut(event.getKeyCode(), event);
9261    }
9262
9263    /**
9264     * Pass the touch screen motion event down to the target view, or this
9265     * view if it is the target.
9266     *
9267     * @param event The motion event to be dispatched.
9268     * @return True if the event was handled by the view, false otherwise.
9269     */
9270    public boolean dispatchTouchEvent(MotionEvent event) {
9271        // If the event should be handled by accessibility focus first.
9272        if (event.isTargetAccessibilityFocus()) {
9273            // We don't have focus or no virtual descendant has it, do not handle the event.
9274            if (!isAccessibilityFocusedViewOrHost()) {
9275                return false;
9276            }
9277            // We have focus and got the event, then use normal event dispatch.
9278            event.setTargetAccessibilityFocus(false);
9279        }
9280
9281        boolean result = false;
9282
9283        if (mInputEventConsistencyVerifier != null) {
9284            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9285        }
9286
9287        final int actionMasked = event.getActionMasked();
9288        if (actionMasked == MotionEvent.ACTION_DOWN) {
9289            // Defensive cleanup for new gesture
9290            stopNestedScroll();
9291        }
9292
9293        if (onFilterTouchEventForSecurity(event)) {
9294            //noinspection SimplifiableIfStatement
9295            ListenerInfo li = mListenerInfo;
9296            if (li != null && li.mOnTouchListener != null
9297                    && (mViewFlags & ENABLED_MASK) == ENABLED
9298                    && li.mOnTouchListener.onTouch(this, event)) {
9299                result = true;
9300            }
9301
9302            if (!result && onTouchEvent(event)) {
9303                result = true;
9304            }
9305        }
9306
9307        if (!result && mInputEventConsistencyVerifier != null) {
9308            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9309        }
9310
9311        // Clean up after nested scrolls if this is the end of a gesture;
9312        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9313        // of the gesture.
9314        if (actionMasked == MotionEvent.ACTION_UP ||
9315                actionMasked == MotionEvent.ACTION_CANCEL ||
9316                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9317            stopNestedScroll();
9318        }
9319
9320        return result;
9321    }
9322
9323    boolean isAccessibilityFocusedViewOrHost() {
9324        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9325                .getAccessibilityFocusedHost() == this);
9326    }
9327
9328    /**
9329     * Filter the touch event to apply security policies.
9330     *
9331     * @param event The motion event to be filtered.
9332     * @return True if the event should be dispatched, false if the event should be dropped.
9333     *
9334     * @see #getFilterTouchesWhenObscured
9335     */
9336    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9337        //noinspection RedundantIfStatement
9338        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9339                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9340            // Window is obscured, drop this touch.
9341            return false;
9342        }
9343        return true;
9344    }
9345
9346    /**
9347     * Pass a trackball motion event down to the focused view.
9348     *
9349     * @param event The motion event to be dispatched.
9350     * @return True if the event was handled by the view, false otherwise.
9351     */
9352    public boolean dispatchTrackballEvent(MotionEvent event) {
9353        if (mInputEventConsistencyVerifier != null) {
9354            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9355        }
9356
9357        return onTrackballEvent(event);
9358    }
9359
9360    /**
9361     * Dispatch a generic motion event.
9362     * <p>
9363     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9364     * are delivered to the view under the pointer.  All other generic motion events are
9365     * delivered to the focused view.  Hover events are handled specially and are delivered
9366     * to {@link #onHoverEvent(MotionEvent)}.
9367     * </p>
9368     *
9369     * @param event The motion event to be dispatched.
9370     * @return True if the event was handled by the view, false otherwise.
9371     */
9372    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9373        if (mInputEventConsistencyVerifier != null) {
9374            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
9375        }
9376
9377        final int source = event.getSource();
9378        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
9379            final int action = event.getAction();
9380            if (action == MotionEvent.ACTION_HOVER_ENTER
9381                    || action == MotionEvent.ACTION_HOVER_MOVE
9382                    || action == MotionEvent.ACTION_HOVER_EXIT) {
9383                if (dispatchHoverEvent(event)) {
9384                    return true;
9385                }
9386            } else if (dispatchGenericPointerEvent(event)) {
9387                return true;
9388            }
9389        } else if (dispatchGenericFocusedEvent(event)) {
9390            return true;
9391        }
9392
9393        if (dispatchGenericMotionEventInternal(event)) {
9394            return true;
9395        }
9396
9397        if (mInputEventConsistencyVerifier != null) {
9398            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9399        }
9400        return false;
9401    }
9402
9403    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
9404        //noinspection SimplifiableIfStatement
9405        ListenerInfo li = mListenerInfo;
9406        if (li != null && li.mOnGenericMotionListener != null
9407                && (mViewFlags & ENABLED_MASK) == ENABLED
9408                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
9409            return true;
9410        }
9411
9412        if (onGenericMotionEvent(event)) {
9413            return true;
9414        }
9415
9416        final int actionButton = event.getActionButton();
9417        switch (event.getActionMasked()) {
9418            case MotionEvent.ACTION_BUTTON_PRESS:
9419                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
9420                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
9421                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
9422                    if (performContextClick()) {
9423                        mInContextButtonPress = true;
9424                        setPressed(true, event.getX(), event.getY());
9425                        removeTapCallback();
9426                        removeLongPressCallback();
9427                        return true;
9428                    }
9429                }
9430                break;
9431
9432            case MotionEvent.ACTION_BUTTON_RELEASE:
9433                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
9434                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
9435                    mInContextButtonPress = false;
9436                    mIgnoreNextUpEvent = true;
9437                }
9438                break;
9439        }
9440
9441        if (mInputEventConsistencyVerifier != null) {
9442            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9443        }
9444        return false;
9445    }
9446
9447    /**
9448     * Dispatch a hover event.
9449     * <p>
9450     * Do not call this method directly.
9451     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9452     * </p>
9453     *
9454     * @param event The motion event to be dispatched.
9455     * @return True if the event was handled by the view, false otherwise.
9456     */
9457    protected boolean dispatchHoverEvent(MotionEvent event) {
9458        ListenerInfo li = mListenerInfo;
9459        //noinspection SimplifiableIfStatement
9460        if (li != null && li.mOnHoverListener != null
9461                && (mViewFlags & ENABLED_MASK) == ENABLED
9462                && li.mOnHoverListener.onHover(this, event)) {
9463            return true;
9464        }
9465
9466        return onHoverEvent(event);
9467    }
9468
9469    /**
9470     * Returns true if the view has a child to which it has recently sent
9471     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
9472     * it does not have a hovered child, then it must be the innermost hovered view.
9473     * @hide
9474     */
9475    protected boolean hasHoveredChild() {
9476        return false;
9477    }
9478
9479    /**
9480     * Dispatch a generic motion event to the view under the first pointer.
9481     * <p>
9482     * Do not call this method directly.
9483     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9484     * </p>
9485     *
9486     * @param event The motion event to be dispatched.
9487     * @return True if the event was handled by the view, false otherwise.
9488     */
9489    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
9490        return false;
9491    }
9492
9493    /**
9494     * Dispatch a generic motion event to the currently focused view.
9495     * <p>
9496     * Do not call this method directly.
9497     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9498     * </p>
9499     *
9500     * @param event The motion event to be dispatched.
9501     * @return True if the event was handled by the view, false otherwise.
9502     */
9503    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
9504        return false;
9505    }
9506
9507    /**
9508     * Dispatch a pointer event.
9509     * <p>
9510     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
9511     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
9512     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
9513     * and should not be expected to handle other pointing device features.
9514     * </p>
9515     *
9516     * @param event The motion event to be dispatched.
9517     * @return True if the event was handled by the view, false otherwise.
9518     * @hide
9519     */
9520    public final boolean dispatchPointerEvent(MotionEvent event) {
9521        if (event.isTouchEvent()) {
9522            return dispatchTouchEvent(event);
9523        } else {
9524            return dispatchGenericMotionEvent(event);
9525        }
9526    }
9527
9528    /**
9529     * Called when the window containing this view gains or loses window focus.
9530     * ViewGroups should override to route to their children.
9531     *
9532     * @param hasFocus True if the window containing this view now has focus,
9533     *        false otherwise.
9534     */
9535    public void dispatchWindowFocusChanged(boolean hasFocus) {
9536        onWindowFocusChanged(hasFocus);
9537    }
9538
9539    /**
9540     * Called when the window containing this view gains or loses focus.  Note
9541     * that this is separate from view focus: to receive key events, both
9542     * your view and its window must have focus.  If a window is displayed
9543     * on top of yours that takes input focus, then your own window will lose
9544     * focus but the view focus will remain unchanged.
9545     *
9546     * @param hasWindowFocus True if the window containing this view now has
9547     *        focus, false otherwise.
9548     */
9549    public void onWindowFocusChanged(boolean hasWindowFocus) {
9550        InputMethodManager imm = InputMethodManager.peekInstance();
9551        if (!hasWindowFocus) {
9552            if (isPressed()) {
9553                setPressed(false);
9554            }
9555            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9556                imm.focusOut(this);
9557            }
9558            removeLongPressCallback();
9559            removeTapCallback();
9560            onFocusLost();
9561        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9562            imm.focusIn(this);
9563        }
9564        refreshDrawableState();
9565    }
9566
9567    /**
9568     * Returns true if this view is in a window that currently has window focus.
9569     * Note that this is not the same as the view itself having focus.
9570     *
9571     * @return True if this view is in a window that currently has window focus.
9572     */
9573    public boolean hasWindowFocus() {
9574        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
9575    }
9576
9577    /**
9578     * Dispatch a view visibility change down the view hierarchy.
9579     * ViewGroups should override to route to their children.
9580     * @param changedView The view whose visibility changed. Could be 'this' or
9581     * an ancestor view.
9582     * @param visibility The new visibility of changedView: {@link #VISIBLE},
9583     * {@link #INVISIBLE} or {@link #GONE}.
9584     */
9585    protected void dispatchVisibilityChanged(@NonNull View changedView,
9586            @Visibility int visibility) {
9587        onVisibilityChanged(changedView, visibility);
9588    }
9589
9590    /**
9591     * Called when the visibility of the view or an ancestor of the view has
9592     * changed.
9593     *
9594     * @param changedView The view whose visibility changed. May be
9595     *                    {@code this} or an ancestor view.
9596     * @param visibility The new visibility, one of {@link #VISIBLE},
9597     *                   {@link #INVISIBLE} or {@link #GONE}.
9598     */
9599    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
9600        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
9601        if (visible && mAttachInfo != null) {
9602            initialAwakenScrollBars();
9603        }
9604
9605        final Drawable dr = mBackground;
9606        if (dr != null && visible != dr.isVisible()) {
9607            dr.setVisible(visible, false);
9608        }
9609        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
9610        if (fg != null && visible != fg.isVisible()) {
9611            fg.setVisible(visible, false);
9612        }
9613    }
9614
9615    /**
9616     * Dispatch a hint about whether this view is displayed. For instance, when
9617     * a View moves out of the screen, it might receives a display hint indicating
9618     * the view is not displayed. Applications should not <em>rely</em> on this hint
9619     * as there is no guarantee that they will receive one.
9620     *
9621     * @param hint A hint about whether or not this view is displayed:
9622     * {@link #VISIBLE} or {@link #INVISIBLE}.
9623     */
9624    public void dispatchDisplayHint(@Visibility int hint) {
9625        onDisplayHint(hint);
9626    }
9627
9628    /**
9629     * Gives this view a hint about whether is displayed or not. For instance, when
9630     * a View moves out of the screen, it might receives a display hint indicating
9631     * the view is not displayed. Applications should not <em>rely</em> on this hint
9632     * as there is no guarantee that they will receive one.
9633     *
9634     * @param hint A hint about whether or not this view is displayed:
9635     * {@link #VISIBLE} or {@link #INVISIBLE}.
9636     */
9637    protected void onDisplayHint(@Visibility int hint) {
9638    }
9639
9640    /**
9641     * Dispatch a window visibility change down the view hierarchy.
9642     * ViewGroups should override to route to their children.
9643     *
9644     * @param visibility The new visibility of the window.
9645     *
9646     * @see #onWindowVisibilityChanged(int)
9647     */
9648    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
9649        onWindowVisibilityChanged(visibility);
9650    }
9651
9652    /**
9653     * Called when the window containing has change its visibility
9654     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
9655     * that this tells you whether or not your window is being made visible
9656     * to the window manager; this does <em>not</em> tell you whether or not
9657     * your window is obscured by other windows on the screen, even if it
9658     * is itself visible.
9659     *
9660     * @param visibility The new visibility of the window.
9661     */
9662    protected void onWindowVisibilityChanged(@Visibility int visibility) {
9663        if (visibility == VISIBLE) {
9664            initialAwakenScrollBars();
9665        }
9666    }
9667
9668    /**
9669     * Returns the current visibility of the window this view is attached to
9670     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
9671     *
9672     * @return Returns the current visibility of the view's window.
9673     */
9674    @Visibility
9675    public int getWindowVisibility() {
9676        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
9677    }
9678
9679    /**
9680     * Retrieve the overall visible display size in which the window this view is
9681     * attached to has been positioned in.  This takes into account screen
9682     * decorations above the window, for both cases where the window itself
9683     * is being position inside of them or the window is being placed under
9684     * then and covered insets are used for the window to position its content
9685     * inside.  In effect, this tells you the available area where content can
9686     * be placed and remain visible to users.
9687     *
9688     * <p>This function requires an IPC back to the window manager to retrieve
9689     * the requested information, so should not be used in performance critical
9690     * code like drawing.
9691     *
9692     * @param outRect Filled in with the visible display frame.  If the view
9693     * is not attached to a window, this is simply the raw display size.
9694     */
9695    public void getWindowVisibleDisplayFrame(Rect outRect) {
9696        if (mAttachInfo != null) {
9697            try {
9698                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
9699            } catch (RemoteException e) {
9700                return;
9701            }
9702            // XXX This is really broken, and probably all needs to be done
9703            // in the window manager, and we need to know more about whether
9704            // we want the area behind or in front of the IME.
9705            final Rect insets = mAttachInfo.mVisibleInsets;
9706            outRect.left += insets.left;
9707            outRect.top += insets.top;
9708            outRect.right -= insets.right;
9709            outRect.bottom -= insets.bottom;
9710            return;
9711        }
9712        // The view is not attached to a display so we don't have a context.
9713        // Make a best guess about the display size.
9714        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
9715        d.getRectSize(outRect);
9716    }
9717
9718    /**
9719     * Dispatch a notification about a resource configuration change down
9720     * the view hierarchy.
9721     * ViewGroups should override to route to their children.
9722     *
9723     * @param newConfig The new resource configuration.
9724     *
9725     * @see #onConfigurationChanged(android.content.res.Configuration)
9726     */
9727    public void dispatchConfigurationChanged(Configuration newConfig) {
9728        onConfigurationChanged(newConfig);
9729    }
9730
9731    /**
9732     * Called when the current configuration of the resources being used
9733     * by the application have changed.  You can use this to decide when
9734     * to reload resources that can changed based on orientation and other
9735     * configuration characteristics.  You only need to use this if you are
9736     * not relying on the normal {@link android.app.Activity} mechanism of
9737     * recreating the activity instance upon a configuration change.
9738     *
9739     * @param newConfig The new resource configuration.
9740     */
9741    protected void onConfigurationChanged(Configuration newConfig) {
9742    }
9743
9744    /**
9745     * Private function to aggregate all per-view attributes in to the view
9746     * root.
9747     */
9748    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9749        performCollectViewAttributes(attachInfo, visibility);
9750    }
9751
9752    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9753        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
9754            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
9755                attachInfo.mKeepScreenOn = true;
9756            }
9757            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
9758            ListenerInfo li = mListenerInfo;
9759            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
9760                attachInfo.mHasSystemUiListeners = true;
9761            }
9762        }
9763    }
9764
9765    void needGlobalAttributesUpdate(boolean force) {
9766        final AttachInfo ai = mAttachInfo;
9767        if (ai != null && !ai.mRecomputeGlobalAttributes) {
9768            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
9769                    || ai.mHasSystemUiListeners) {
9770                ai.mRecomputeGlobalAttributes = true;
9771            }
9772        }
9773    }
9774
9775    /**
9776     * Returns whether the device is currently in touch mode.  Touch mode is entered
9777     * once the user begins interacting with the device by touch, and affects various
9778     * things like whether focus is always visible to the user.
9779     *
9780     * @return Whether the device is in touch mode.
9781     */
9782    @ViewDebug.ExportedProperty
9783    public boolean isInTouchMode() {
9784        if (mAttachInfo != null) {
9785            return mAttachInfo.mInTouchMode;
9786        } else {
9787            return ViewRootImpl.isInTouchMode();
9788        }
9789    }
9790
9791    /**
9792     * Returns the context the view is running in, through which it can
9793     * access the current theme, resources, etc.
9794     *
9795     * @return The view's Context.
9796     */
9797    @ViewDebug.CapturedViewProperty
9798    public final Context getContext() {
9799        return mContext;
9800    }
9801
9802    /**
9803     * Handle a key event before it is processed by any input method
9804     * associated with the view hierarchy.  This can be used to intercept
9805     * key events in special situations before the IME consumes them; a
9806     * typical example would be handling the BACK key to update the application's
9807     * UI instead of allowing the IME to see it and close itself.
9808     *
9809     * @param keyCode The value in event.getKeyCode().
9810     * @param event Description of the key event.
9811     * @return If you handled the event, return true. If you want to allow the
9812     *         event to be handled by the next receiver, return false.
9813     */
9814    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9815        return false;
9816    }
9817
9818    /**
9819     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9820     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9821     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9822     * is released, if the view is enabled and clickable.
9823     *
9824     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9825     * although some may elect to do so in some situations. Do not rely on this to
9826     * catch software key presses.
9827     *
9828     * @param keyCode A key code that represents the button pressed, from
9829     *                {@link android.view.KeyEvent}.
9830     * @param event   The KeyEvent object that defines the button action.
9831     */
9832    public boolean onKeyDown(int keyCode, KeyEvent event) {
9833        boolean result = false;
9834
9835        if (KeyEvent.isConfirmKey(keyCode)) {
9836            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9837                return true;
9838            }
9839            // Long clickable items don't necessarily have to be clickable
9840            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9841                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9842                    (event.getRepeatCount() == 0)) {
9843                setPressed(true);
9844                checkForLongClick(0);
9845                return true;
9846            }
9847        }
9848        return result;
9849    }
9850
9851    /**
9852     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9853     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9854     * the event).
9855     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9856     * although some may elect to do so in some situations. Do not rely on this to
9857     * catch software key presses.
9858     */
9859    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9860        return false;
9861    }
9862
9863    /**
9864     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9865     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9866     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9867     * {@link KeyEvent#KEYCODE_ENTER} is released.
9868     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9869     * although some may elect to do so in some situations. Do not rely on this to
9870     * catch software key presses.
9871     *
9872     * @param keyCode A key code that represents the button pressed, from
9873     *                {@link android.view.KeyEvent}.
9874     * @param event   The KeyEvent object that defines the button action.
9875     */
9876    public boolean onKeyUp(int keyCode, KeyEvent event) {
9877        if (KeyEvent.isConfirmKey(keyCode)) {
9878            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9879                return true;
9880            }
9881            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9882                setPressed(false);
9883
9884                if (!mHasPerformedLongPress) {
9885                    // This is a tap, so remove the longpress check
9886                    removeLongPressCallback();
9887                    return performClick();
9888                }
9889            }
9890        }
9891        return false;
9892    }
9893
9894    /**
9895     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9896     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9897     * the event).
9898     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9899     * although some may elect to do so in some situations. Do not rely on this to
9900     * catch software key presses.
9901     *
9902     * @param keyCode     A key code that represents the button pressed, from
9903     *                    {@link android.view.KeyEvent}.
9904     * @param repeatCount The number of times the action was made.
9905     * @param event       The KeyEvent object that defines the button action.
9906     */
9907    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9908        return false;
9909    }
9910
9911    /**
9912     * Called on the focused view when a key shortcut event is not handled.
9913     * Override this method to implement local key shortcuts for the View.
9914     * Key shortcuts can also be implemented by setting the
9915     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9916     *
9917     * @param keyCode The value in event.getKeyCode().
9918     * @param event Description of the key event.
9919     * @return If you handled the event, return true. If you want to allow the
9920     *         event to be handled by the next receiver, return false.
9921     */
9922    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9923        return false;
9924    }
9925
9926    /**
9927     * Check whether the called view is a text editor, in which case it
9928     * would make sense to automatically display a soft input window for
9929     * it.  Subclasses should override this if they implement
9930     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9931     * a call on that method would return a non-null InputConnection, and
9932     * they are really a first-class editor that the user would normally
9933     * start typing on when the go into a window containing your view.
9934     *
9935     * <p>The default implementation always returns false.  This does
9936     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9937     * will not be called or the user can not otherwise perform edits on your
9938     * view; it is just a hint to the system that this is not the primary
9939     * purpose of this view.
9940     *
9941     * @return Returns true if this view is a text editor, else false.
9942     */
9943    public boolean onCheckIsTextEditor() {
9944        return false;
9945    }
9946
9947    /**
9948     * Create a new InputConnection for an InputMethod to interact
9949     * with the view.  The default implementation returns null, since it doesn't
9950     * support input methods.  You can override this to implement such support.
9951     * This is only needed for views that take focus and text input.
9952     *
9953     * <p>When implementing this, you probably also want to implement
9954     * {@link #onCheckIsTextEditor()} to indicate you will return a
9955     * non-null InputConnection.</p>
9956     *
9957     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9958     * object correctly and in its entirety, so that the connected IME can rely
9959     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9960     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9961     * must be filled in with the correct cursor position for IMEs to work correctly
9962     * with your application.</p>
9963     *
9964     * @param outAttrs Fill in with attribute information about the connection.
9965     */
9966    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9967        return null;
9968    }
9969
9970    /**
9971     * Called by the {@link android.view.inputmethod.InputMethodManager}
9972     * when a view who is not the current
9973     * input connection target is trying to make a call on the manager.  The
9974     * default implementation returns false; you can override this to return
9975     * true for certain views if you are performing InputConnection proxying
9976     * to them.
9977     * @param view The View that is making the InputMethodManager call.
9978     * @return Return true to allow the call, false to reject.
9979     */
9980    public boolean checkInputConnectionProxy(View view) {
9981        return false;
9982    }
9983
9984    /**
9985     * Show the context menu for this view. It is not safe to hold on to the
9986     * menu after returning from this method.
9987     *
9988     * You should normally not overload this method. Overload
9989     * {@link #onCreateContextMenu(ContextMenu)} or define an
9990     * {@link OnCreateContextMenuListener} to add items to the context menu.
9991     *
9992     * @param menu The context menu to populate
9993     */
9994    public void createContextMenu(ContextMenu menu) {
9995        ContextMenuInfo menuInfo = getContextMenuInfo();
9996
9997        // Sets the current menu info so all items added to menu will have
9998        // my extra info set.
9999        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10000
10001        onCreateContextMenu(menu);
10002        ListenerInfo li = mListenerInfo;
10003        if (li != null && li.mOnCreateContextMenuListener != null) {
10004            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10005        }
10006
10007        // Clear the extra information so subsequent items that aren't mine don't
10008        // have my extra info.
10009        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10010
10011        if (mParent != null) {
10012            mParent.createContextMenu(menu);
10013        }
10014    }
10015
10016    /**
10017     * Views should implement this if they have extra information to associate
10018     * with the context menu. The return result is supplied as a parameter to
10019     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10020     * callback.
10021     *
10022     * @return Extra information about the item for which the context menu
10023     *         should be shown. This information will vary across different
10024     *         subclasses of View.
10025     */
10026    protected ContextMenuInfo getContextMenuInfo() {
10027        return null;
10028    }
10029
10030    /**
10031     * Views should implement this if the view itself is going to add items to
10032     * the context menu.
10033     *
10034     * @param menu the context menu to populate
10035     */
10036    protected void onCreateContextMenu(ContextMenu menu) {
10037    }
10038
10039    /**
10040     * Implement this method to handle trackball motion events.  The
10041     * <em>relative</em> movement of the trackball since the last event
10042     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10043     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10044     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10045     * they will often be fractional values, representing the more fine-grained
10046     * movement information available from a trackball).
10047     *
10048     * @param event The motion event.
10049     * @return True if the event was handled, false otherwise.
10050     */
10051    public boolean onTrackballEvent(MotionEvent event) {
10052        return false;
10053    }
10054
10055    /**
10056     * Implement this method to handle generic motion events.
10057     * <p>
10058     * Generic motion events describe joystick movements, mouse hovers, track pad
10059     * touches, scroll wheel movements and other input events.  The
10060     * {@link MotionEvent#getSource() source} of the motion event specifies
10061     * the class of input that was received.  Implementations of this method
10062     * must examine the bits in the source before processing the event.
10063     * The following code example shows how this is done.
10064     * </p><p>
10065     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10066     * are delivered to the view under the pointer.  All other generic motion events are
10067     * delivered to the focused view.
10068     * </p>
10069     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10070     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10071     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10072     *             // process the joystick movement...
10073     *             return true;
10074     *         }
10075     *     }
10076     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10077     *         switch (event.getAction()) {
10078     *             case MotionEvent.ACTION_HOVER_MOVE:
10079     *                 // process the mouse hover movement...
10080     *                 return true;
10081     *             case MotionEvent.ACTION_SCROLL:
10082     *                 // process the scroll wheel movement...
10083     *                 return true;
10084     *         }
10085     *     }
10086     *     return super.onGenericMotionEvent(event);
10087     * }</pre>
10088     *
10089     * @param event The generic motion event being processed.
10090     * @return True if the event was handled, false otherwise.
10091     */
10092    public boolean onGenericMotionEvent(MotionEvent event) {
10093        return false;
10094    }
10095
10096    /**
10097     * Implement this method to handle hover events.
10098     * <p>
10099     * This method is called whenever a pointer is hovering into, over, or out of the
10100     * bounds of a view and the view is not currently being touched.
10101     * Hover events are represented as pointer events with action
10102     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10103     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10104     * </p>
10105     * <ul>
10106     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10107     * when the pointer enters the bounds of the view.</li>
10108     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10109     * when the pointer has already entered the bounds of the view and has moved.</li>
10110     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10111     * when the pointer has exited the bounds of the view or when the pointer is
10112     * about to go down due to a button click, tap, or similar user action that
10113     * causes the view to be touched.</li>
10114     * </ul>
10115     * <p>
10116     * The view should implement this method to return true to indicate that it is
10117     * handling the hover event, such as by changing its drawable state.
10118     * </p><p>
10119     * The default implementation calls {@link #setHovered} to update the hovered state
10120     * of the view when a hover enter or hover exit event is received, if the view
10121     * is enabled and is clickable.  The default implementation also sends hover
10122     * accessibility events.
10123     * </p>
10124     *
10125     * @param event The motion event that describes the hover.
10126     * @return True if the view handled the hover event.
10127     *
10128     * @see #isHovered
10129     * @see #setHovered
10130     * @see #onHoverChanged
10131     */
10132    public boolean onHoverEvent(MotionEvent event) {
10133        // The root view may receive hover (or touch) events that are outside the bounds of
10134        // the window.  This code ensures that we only send accessibility events for
10135        // hovers that are actually within the bounds of the root view.
10136        final int action = event.getActionMasked();
10137        if (!mSendingHoverAccessibilityEvents) {
10138            if ((action == MotionEvent.ACTION_HOVER_ENTER
10139                    || action == MotionEvent.ACTION_HOVER_MOVE)
10140                    && !hasHoveredChild()
10141                    && pointInView(event.getX(), event.getY())) {
10142                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10143                mSendingHoverAccessibilityEvents = true;
10144            }
10145        } else {
10146            if (action == MotionEvent.ACTION_HOVER_EXIT
10147                    || (action == MotionEvent.ACTION_MOVE
10148                            && !pointInView(event.getX(), event.getY()))) {
10149                mSendingHoverAccessibilityEvents = false;
10150                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10151            }
10152        }
10153
10154        if (isHoverable()) {
10155            switch (action) {
10156                case MotionEvent.ACTION_HOVER_ENTER:
10157                    setHovered(true);
10158                    break;
10159                case MotionEvent.ACTION_HOVER_EXIT:
10160                    setHovered(false);
10161                    break;
10162            }
10163
10164            // Dispatch the event to onGenericMotionEvent before returning true.
10165            // This is to provide compatibility with existing applications that
10166            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10167            // break because of the new default handling for hoverable views
10168            // in onHoverEvent.
10169            // Note that onGenericMotionEvent will be called by default when
10170            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10171            dispatchGenericMotionEventInternal(event);
10172            // The event was already handled by calling setHovered(), so always
10173            // return true.
10174            return true;
10175        }
10176
10177        return false;
10178    }
10179
10180    /**
10181     * Returns true if the view should handle {@link #onHoverEvent}
10182     * by calling {@link #setHovered} to change its hovered state.
10183     *
10184     * @return True if the view is hoverable.
10185     */
10186    private boolean isHoverable() {
10187        final int viewFlags = mViewFlags;
10188        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10189            return false;
10190        }
10191
10192        return (viewFlags & CLICKABLE) == CLICKABLE
10193                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10194                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10195    }
10196
10197    /**
10198     * Returns true if the view is currently hovered.
10199     *
10200     * @return True if the view is currently hovered.
10201     *
10202     * @see #setHovered
10203     * @see #onHoverChanged
10204     */
10205    @ViewDebug.ExportedProperty
10206    public boolean isHovered() {
10207        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10208    }
10209
10210    /**
10211     * Sets whether the view is currently hovered.
10212     * <p>
10213     * Calling this method also changes the drawable state of the view.  This
10214     * enables the view to react to hover by using different drawable resources
10215     * to change its appearance.
10216     * </p><p>
10217     * The {@link #onHoverChanged} method is called when the hovered state changes.
10218     * </p>
10219     *
10220     * @param hovered True if the view is hovered.
10221     *
10222     * @see #isHovered
10223     * @see #onHoverChanged
10224     */
10225    public void setHovered(boolean hovered) {
10226        if (hovered) {
10227            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10228                mPrivateFlags |= PFLAG_HOVERED;
10229                refreshDrawableState();
10230                onHoverChanged(true);
10231            }
10232        } else {
10233            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10234                mPrivateFlags &= ~PFLAG_HOVERED;
10235                refreshDrawableState();
10236                onHoverChanged(false);
10237            }
10238        }
10239    }
10240
10241    /**
10242     * Implement this method to handle hover state changes.
10243     * <p>
10244     * This method is called whenever the hover state changes as a result of a
10245     * call to {@link #setHovered}.
10246     * </p>
10247     *
10248     * @param hovered The current hover state, as returned by {@link #isHovered}.
10249     *
10250     * @see #isHovered
10251     * @see #setHovered
10252     */
10253    public void onHoverChanged(boolean hovered) {
10254    }
10255
10256    /**
10257     * Implement this method to handle touch screen motion events.
10258     * <p>
10259     * If this method is used to detect click actions, it is recommended that
10260     * the actions be performed by implementing and calling
10261     * {@link #performClick()}. This will ensure consistent system behavior,
10262     * including:
10263     * <ul>
10264     * <li>obeying click sound preferences
10265     * <li>dispatching OnClickListener calls
10266     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
10267     * accessibility features are enabled
10268     * </ul>
10269     *
10270     * @param event The motion event.
10271     * @return True if the event was handled, false otherwise.
10272     */
10273    public boolean onTouchEvent(MotionEvent event) {
10274        final float x = event.getX();
10275        final float y = event.getY();
10276        final int viewFlags = mViewFlags;
10277        final int action = event.getAction();
10278
10279        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10280            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
10281                setPressed(false);
10282            }
10283            // A disabled view that is clickable still consumes the touch
10284            // events, it just doesn't respond to them.
10285            return (((viewFlags & CLICKABLE) == CLICKABLE
10286                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10287                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
10288        }
10289
10290        if (mTouchDelegate != null) {
10291            if (mTouchDelegate.onTouchEvent(event)) {
10292                return true;
10293            }
10294        }
10295
10296        if (((viewFlags & CLICKABLE) == CLICKABLE ||
10297                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
10298                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
10299            switch (action) {
10300                case MotionEvent.ACTION_UP:
10301                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
10302                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
10303                        // take focus if we don't have it already and we should in
10304                        // touch mode.
10305                        boolean focusTaken = false;
10306                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
10307                            focusTaken = requestFocus();
10308                        }
10309
10310                        if (prepressed) {
10311                            // The button is being released before we actually
10312                            // showed it as pressed.  Make it show the pressed
10313                            // state now (before scheduling the click) to ensure
10314                            // the user sees it.
10315                            setPressed(true, x, y);
10316                       }
10317
10318                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
10319                            // This is a tap, so remove the longpress check
10320                            removeLongPressCallback();
10321
10322                            // Only perform take click actions if we were in the pressed state
10323                            if (!focusTaken) {
10324                                // Use a Runnable and post this rather than calling
10325                                // performClick directly. This lets other visual state
10326                                // of the view update before click actions start.
10327                                if (mPerformClick == null) {
10328                                    mPerformClick = new PerformClick();
10329                                }
10330                                if (!post(mPerformClick)) {
10331                                    performClick();
10332                                }
10333                            }
10334                        }
10335
10336                        if (mUnsetPressedState == null) {
10337                            mUnsetPressedState = new UnsetPressedState();
10338                        }
10339
10340                        if (prepressed) {
10341                            postDelayed(mUnsetPressedState,
10342                                    ViewConfiguration.getPressedStateDuration());
10343                        } else if (!post(mUnsetPressedState)) {
10344                            // If the post failed, unpress right now
10345                            mUnsetPressedState.run();
10346                        }
10347
10348                        removeTapCallback();
10349                    }
10350                    mIgnoreNextUpEvent = false;
10351                    break;
10352
10353                case MotionEvent.ACTION_DOWN:
10354                    mHasPerformedLongPress = false;
10355
10356                    if (performButtonActionOnTouchDown(event)) {
10357                        break;
10358                    }
10359
10360                    // Walk up the hierarchy to determine if we're inside a scrolling container.
10361                    boolean isInScrollingContainer = isInScrollingContainer();
10362
10363                    // For views inside a scrolling container, delay the pressed feedback for
10364                    // a short period in case this is a scroll.
10365                    if (isInScrollingContainer) {
10366                        mPrivateFlags |= PFLAG_PREPRESSED;
10367                        if (mPendingCheckForTap == null) {
10368                            mPendingCheckForTap = new CheckForTap();
10369                        }
10370                        mPendingCheckForTap.x = event.getX();
10371                        mPendingCheckForTap.y = event.getY();
10372                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
10373                    } else {
10374                        // Not inside a scrolling container, so show the feedback right away
10375                        setPressed(true, x, y);
10376                        checkForLongClick(0);
10377                    }
10378                    break;
10379
10380                case MotionEvent.ACTION_CANCEL:
10381                    setPressed(false);
10382                    removeTapCallback();
10383                    removeLongPressCallback();
10384                    mInContextButtonPress = false;
10385                    mHasPerformedLongPress = false;
10386                    mIgnoreNextUpEvent = false;
10387                    break;
10388
10389                case MotionEvent.ACTION_MOVE:
10390                    drawableHotspotChanged(x, y);
10391
10392                    // Be lenient about moving outside of buttons
10393                    if (!pointInView(x, y, mTouchSlop)) {
10394                        // Outside button
10395                        removeTapCallback();
10396                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
10397                            // Remove any future long press/tap checks
10398                            removeLongPressCallback();
10399
10400                            setPressed(false);
10401                        }
10402                    }
10403                    break;
10404            }
10405
10406            return true;
10407        }
10408
10409        return false;
10410    }
10411
10412    /**
10413     * @hide
10414     */
10415    public boolean isInScrollingContainer() {
10416        ViewParent p = getParent();
10417        while (p != null && p instanceof ViewGroup) {
10418            if (((ViewGroup) p).shouldDelayChildPressedState()) {
10419                return true;
10420            }
10421            p = p.getParent();
10422        }
10423        return false;
10424    }
10425
10426    /**
10427     * Remove the longpress detection timer.
10428     */
10429    private void removeLongPressCallback() {
10430        if (mPendingCheckForLongPress != null) {
10431          removeCallbacks(mPendingCheckForLongPress);
10432        }
10433    }
10434
10435    /**
10436     * Remove the pending click action
10437     */
10438    private void removePerformClickCallback() {
10439        if (mPerformClick != null) {
10440            removeCallbacks(mPerformClick);
10441        }
10442    }
10443
10444    /**
10445     * Remove the prepress detection timer.
10446     */
10447    private void removeUnsetPressCallback() {
10448        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
10449            setPressed(false);
10450            removeCallbacks(mUnsetPressedState);
10451        }
10452    }
10453
10454    /**
10455     * Remove the tap detection timer.
10456     */
10457    private void removeTapCallback() {
10458        if (mPendingCheckForTap != null) {
10459            mPrivateFlags &= ~PFLAG_PREPRESSED;
10460            removeCallbacks(mPendingCheckForTap);
10461        }
10462    }
10463
10464    /**
10465     * Cancels a pending long press.  Your subclass can use this if you
10466     * want the context menu to come up if the user presses and holds
10467     * at the same place, but you don't want it to come up if they press
10468     * and then move around enough to cause scrolling.
10469     */
10470    public void cancelLongPress() {
10471        removeLongPressCallback();
10472
10473        /*
10474         * The prepressed state handled by the tap callback is a display
10475         * construct, but the tap callback will post a long press callback
10476         * less its own timeout. Remove it here.
10477         */
10478        removeTapCallback();
10479    }
10480
10481    /**
10482     * Remove the pending callback for sending a
10483     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
10484     */
10485    private void removeSendViewScrolledAccessibilityEventCallback() {
10486        if (mSendViewScrolledAccessibilityEvent != null) {
10487            removeCallbacks(mSendViewScrolledAccessibilityEvent);
10488            mSendViewScrolledAccessibilityEvent.mIsPending = false;
10489        }
10490    }
10491
10492    /**
10493     * Sets the TouchDelegate for this View.
10494     */
10495    public void setTouchDelegate(TouchDelegate delegate) {
10496        mTouchDelegate = delegate;
10497    }
10498
10499    /**
10500     * Gets the TouchDelegate for this View.
10501     */
10502    public TouchDelegate getTouchDelegate() {
10503        return mTouchDelegate;
10504    }
10505
10506    /**
10507     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
10508     *
10509     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
10510     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
10511     * available. This method should only be called for touch events.
10512     *
10513     * <p class="note">This api is not intended for most applications. Buffered dispatch
10514     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
10515     * streams will not improve your input latency. Side effects include: increased latency,
10516     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
10517     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
10518     * you.</p>
10519     */
10520    public final void requestUnbufferedDispatch(MotionEvent event) {
10521        final int action = event.getAction();
10522        if (mAttachInfo == null
10523                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
10524                || !event.isTouchEvent()) {
10525            return;
10526        }
10527        mAttachInfo.mUnbufferedDispatchRequested = true;
10528    }
10529
10530    /**
10531     * Set flags controlling behavior of this view.
10532     *
10533     * @param flags Constant indicating the value which should be set
10534     * @param mask Constant indicating the bit range that should be changed
10535     */
10536    void setFlags(int flags, int mask) {
10537        final boolean accessibilityEnabled =
10538                AccessibilityManager.getInstance(mContext).isEnabled();
10539        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
10540
10541        int old = mViewFlags;
10542        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
10543
10544        int changed = mViewFlags ^ old;
10545        if (changed == 0) {
10546            return;
10547        }
10548        int privateFlags = mPrivateFlags;
10549
10550        /* Check if the FOCUSABLE bit has changed */
10551        if (((changed & FOCUSABLE_MASK) != 0) &&
10552                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
10553            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
10554                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
10555                /* Give up focus if we are no longer focusable */
10556                clearFocus();
10557            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
10558                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
10559                /*
10560                 * Tell the view system that we are now available to take focus
10561                 * if no one else already has it.
10562                 */
10563                if (mParent != null) mParent.focusableViewAvailable(this);
10564            }
10565        }
10566
10567        final int newVisibility = flags & VISIBILITY_MASK;
10568        if (newVisibility == VISIBLE) {
10569            if ((changed & VISIBILITY_MASK) != 0) {
10570                /*
10571                 * If this view is becoming visible, invalidate it in case it changed while
10572                 * it was not visible. Marking it drawn ensures that the invalidation will
10573                 * go through.
10574                 */
10575                mPrivateFlags |= PFLAG_DRAWN;
10576                invalidate(true);
10577
10578                needGlobalAttributesUpdate(true);
10579
10580                // a view becoming visible is worth notifying the parent
10581                // about in case nothing has focus.  even if this specific view
10582                // isn't focusable, it may contain something that is, so let
10583                // the root view try to give this focus if nothing else does.
10584                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
10585                    mParent.focusableViewAvailable(this);
10586                }
10587            }
10588        }
10589
10590        /* Check if the GONE bit has changed */
10591        if ((changed & GONE) != 0) {
10592            needGlobalAttributesUpdate(false);
10593            requestLayout();
10594
10595            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
10596                if (hasFocus()) clearFocus();
10597                clearAccessibilityFocus();
10598                destroyDrawingCache();
10599                if (mParent instanceof View) {
10600                    // GONE views noop invalidation, so invalidate the parent
10601                    ((View) mParent).invalidate(true);
10602                }
10603                // Mark the view drawn to ensure that it gets invalidated properly the next
10604                // time it is visible and gets invalidated
10605                mPrivateFlags |= PFLAG_DRAWN;
10606            }
10607            if (mAttachInfo != null) {
10608                mAttachInfo.mViewVisibilityChanged = true;
10609            }
10610        }
10611
10612        /* Check if the VISIBLE bit has changed */
10613        if ((changed & INVISIBLE) != 0) {
10614            needGlobalAttributesUpdate(false);
10615            /*
10616             * If this view is becoming invisible, set the DRAWN flag so that
10617             * the next invalidate() will not be skipped.
10618             */
10619            mPrivateFlags |= PFLAG_DRAWN;
10620
10621            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
10622                // root view becoming invisible shouldn't clear focus and accessibility focus
10623                if (getRootView() != this) {
10624                    if (hasFocus()) clearFocus();
10625                    clearAccessibilityFocus();
10626                }
10627            }
10628            if (mAttachInfo != null) {
10629                mAttachInfo.mViewVisibilityChanged = true;
10630            }
10631        }
10632
10633        if ((changed & VISIBILITY_MASK) != 0) {
10634            // If the view is invisible, cleanup its display list to free up resources
10635            if (newVisibility != VISIBLE && mAttachInfo != null) {
10636                cleanupDraw();
10637            }
10638
10639            if (mParent instanceof ViewGroup) {
10640                ((ViewGroup) mParent).onChildVisibilityChanged(this,
10641                        (changed & VISIBILITY_MASK), newVisibility);
10642                ((View) mParent).invalidate(true);
10643            } else if (mParent != null) {
10644                mParent.invalidateChild(this, null);
10645            }
10646
10647            if (mAttachInfo != null) {
10648                dispatchVisibilityChanged(this, newVisibility);
10649                notifySubtreeAccessibilityStateChangedIfNeeded();
10650            }
10651        }
10652
10653        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
10654            destroyDrawingCache();
10655        }
10656
10657        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
10658            destroyDrawingCache();
10659            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10660            invalidateParentCaches();
10661        }
10662
10663        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
10664            destroyDrawingCache();
10665            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10666        }
10667
10668        if ((changed & DRAW_MASK) != 0) {
10669            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
10670                if (mBackground != null
10671                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
10672                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10673                } else {
10674                    mPrivateFlags |= PFLAG_SKIP_DRAW;
10675                }
10676            } else {
10677                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10678            }
10679            requestLayout();
10680            invalidate(true);
10681        }
10682
10683        if ((changed & KEEP_SCREEN_ON) != 0) {
10684            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10685                mParent.recomputeViewAttributes(this);
10686            }
10687        }
10688
10689        if (accessibilityEnabled) {
10690            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
10691                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
10692                    || (changed & CONTEXT_CLICKABLE) != 0) {
10693                if (oldIncludeForAccessibility != includeForAccessibility()) {
10694                    notifySubtreeAccessibilityStateChangedIfNeeded();
10695                } else {
10696                    notifyViewAccessibilityStateChangedIfNeeded(
10697                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10698                }
10699            } else if ((changed & ENABLED_MASK) != 0) {
10700                notifyViewAccessibilityStateChangedIfNeeded(
10701                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10702            }
10703        }
10704    }
10705
10706    /**
10707     * Change the view's z order in the tree, so it's on top of other sibling
10708     * views. This ordering change may affect layout, if the parent container
10709     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
10710     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
10711     * method should be followed by calls to {@link #requestLayout()} and
10712     * {@link View#invalidate()} on the view's parent to force the parent to redraw
10713     * with the new child ordering.
10714     *
10715     * @see ViewGroup#bringChildToFront(View)
10716     */
10717    public void bringToFront() {
10718        if (mParent != null) {
10719            mParent.bringChildToFront(this);
10720        }
10721    }
10722
10723    /**
10724     * This is called in response to an internal scroll in this view (i.e., the
10725     * view scrolled its own contents). This is typically as a result of
10726     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
10727     * called.
10728     *
10729     * @param l Current horizontal scroll origin.
10730     * @param t Current vertical scroll origin.
10731     * @param oldl Previous horizontal scroll origin.
10732     * @param oldt Previous vertical scroll origin.
10733     */
10734    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
10735        notifySubtreeAccessibilityStateChangedIfNeeded();
10736
10737        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10738            postSendViewScrolledAccessibilityEventCallback();
10739        }
10740
10741        mBackgroundSizeChanged = true;
10742        if (mForegroundInfo != null) {
10743            mForegroundInfo.mBoundsChanged = true;
10744        }
10745
10746        final AttachInfo ai = mAttachInfo;
10747        if (ai != null) {
10748            ai.mViewScrollChanged = true;
10749        }
10750
10751        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
10752            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
10753        }
10754    }
10755
10756    /**
10757     * Interface definition for a callback to be invoked when the scroll
10758     * X or Y positions of a view change.
10759     * <p>
10760     * <b>Note:</b> Some views handle scrolling independently from View and may
10761     * have their own separate listeners for scroll-type events. For example,
10762     * {@link android.widget.ListView ListView} allows clients to register an
10763     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
10764     * to listen for changes in list scroll position.
10765     *
10766     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
10767     */
10768    public interface OnScrollChangeListener {
10769        /**
10770         * Called when the scroll position of a view changes.
10771         *
10772         * @param v The view whose scroll position has changed.
10773         * @param scrollX Current horizontal scroll origin.
10774         * @param scrollY Current vertical scroll origin.
10775         * @param oldScrollX Previous horizontal scroll origin.
10776         * @param oldScrollY Previous vertical scroll origin.
10777         */
10778        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
10779    }
10780
10781    /**
10782     * Interface definition for a callback to be invoked when the layout bounds of a view
10783     * changes due to layout processing.
10784     */
10785    public interface OnLayoutChangeListener {
10786        /**
10787         * Called when the layout bounds of a view changes due to layout processing.
10788         *
10789         * @param v The view whose bounds have changed.
10790         * @param left The new value of the view's left property.
10791         * @param top The new value of the view's top property.
10792         * @param right The new value of the view's right property.
10793         * @param bottom The new value of the view's bottom property.
10794         * @param oldLeft The previous value of the view's left property.
10795         * @param oldTop The previous value of the view's top property.
10796         * @param oldRight The previous value of the view's right property.
10797         * @param oldBottom The previous value of the view's bottom property.
10798         */
10799        void onLayoutChange(View v, int left, int top, int right, int bottom,
10800            int oldLeft, int oldTop, int oldRight, int oldBottom);
10801    }
10802
10803    /**
10804     * This is called during layout when the size of this view has changed. If
10805     * you were just added to the view hierarchy, you're called with the old
10806     * values of 0.
10807     *
10808     * @param w Current width of this view.
10809     * @param h Current height of this view.
10810     * @param oldw Old width of this view.
10811     * @param oldh Old height of this view.
10812     */
10813    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10814    }
10815
10816    /**
10817     * Called by draw to draw the child views. This may be overridden
10818     * by derived classes to gain control just before its children are drawn
10819     * (but after its own view has been drawn).
10820     * @param canvas the canvas on which to draw the view
10821     */
10822    protected void dispatchDraw(Canvas canvas) {
10823
10824    }
10825
10826    /**
10827     * Gets the parent of this view. Note that the parent is a
10828     * ViewParent and not necessarily a View.
10829     *
10830     * @return Parent of this view.
10831     */
10832    public final ViewParent getParent() {
10833        return mParent;
10834    }
10835
10836    /**
10837     * Set the horizontal scrolled position of your view. This will cause a call to
10838     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10839     * invalidated.
10840     * @param value the x position to scroll to
10841     */
10842    public void setScrollX(int value) {
10843        scrollTo(value, mScrollY);
10844    }
10845
10846    /**
10847     * Set the vertical scrolled position of your view. This will cause a call to
10848     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10849     * invalidated.
10850     * @param value the y position to scroll to
10851     */
10852    public void setScrollY(int value) {
10853        scrollTo(mScrollX, value);
10854    }
10855
10856    /**
10857     * Return the scrolled left position of this view. This is the left edge of
10858     * the displayed part of your view. You do not need to draw any pixels
10859     * farther left, since those are outside of the frame of your view on
10860     * screen.
10861     *
10862     * @return The left edge of the displayed part of your view, in pixels.
10863     */
10864    public final int getScrollX() {
10865        return mScrollX;
10866    }
10867
10868    /**
10869     * Return the scrolled top position of this view. This is the top edge of
10870     * the displayed part of your view. You do not need to draw any pixels above
10871     * it, since those are outside of the frame of your view on screen.
10872     *
10873     * @return The top edge of the displayed part of your view, in pixels.
10874     */
10875    public final int getScrollY() {
10876        return mScrollY;
10877    }
10878
10879    /**
10880     * Return the width of the your view.
10881     *
10882     * @return The width of your view, in pixels.
10883     */
10884    @ViewDebug.ExportedProperty(category = "layout")
10885    public final int getWidth() {
10886        return mRight - mLeft;
10887    }
10888
10889    /**
10890     * Return the height of your view.
10891     *
10892     * @return The height of your view, in pixels.
10893     */
10894    @ViewDebug.ExportedProperty(category = "layout")
10895    public final int getHeight() {
10896        return mBottom - mTop;
10897    }
10898
10899    /**
10900     * Return the visible drawing bounds of your view. Fills in the output
10901     * rectangle with the values from getScrollX(), getScrollY(),
10902     * getWidth(), and getHeight(). These bounds do not account for any
10903     * transformation properties currently set on the view, such as
10904     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10905     *
10906     * @param outRect The (scrolled) drawing bounds of the view.
10907     */
10908    public void getDrawingRect(Rect outRect) {
10909        outRect.left = mScrollX;
10910        outRect.top = mScrollY;
10911        outRect.right = mScrollX + (mRight - mLeft);
10912        outRect.bottom = mScrollY + (mBottom - mTop);
10913    }
10914
10915    /**
10916     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10917     * raw width component (that is the result is masked by
10918     * {@link #MEASURED_SIZE_MASK}).
10919     *
10920     * @return The raw measured width of this view.
10921     */
10922    public final int getMeasuredWidth() {
10923        return mMeasuredWidth & MEASURED_SIZE_MASK;
10924    }
10925
10926    /**
10927     * Return the full width measurement information for this view as computed
10928     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10929     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10930     * This should be used during measurement and layout calculations only. Use
10931     * {@link #getWidth()} to see how wide a view is after layout.
10932     *
10933     * @return The measured width of this view as a bit mask.
10934     */
10935    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10936            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10937                    name = "MEASURED_STATE_TOO_SMALL"),
10938    })
10939    public final int getMeasuredWidthAndState() {
10940        return mMeasuredWidth;
10941    }
10942
10943    /**
10944     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10945     * raw width component (that is the result is masked by
10946     * {@link #MEASURED_SIZE_MASK}).
10947     *
10948     * @return The raw measured height of this view.
10949     */
10950    public final int getMeasuredHeight() {
10951        return mMeasuredHeight & MEASURED_SIZE_MASK;
10952    }
10953
10954    /**
10955     * Return the full height measurement information for this view as computed
10956     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10957     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10958     * This should be used during measurement and layout calculations only. Use
10959     * {@link #getHeight()} to see how wide a view is after layout.
10960     *
10961     * @return The measured width of this view as a bit mask.
10962     */
10963    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10964            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10965                    name = "MEASURED_STATE_TOO_SMALL"),
10966    })
10967    public final int getMeasuredHeightAndState() {
10968        return mMeasuredHeight;
10969    }
10970
10971    /**
10972     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10973     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10974     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10975     * and the height component is at the shifted bits
10976     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10977     */
10978    public final int getMeasuredState() {
10979        return (mMeasuredWidth&MEASURED_STATE_MASK)
10980                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10981                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10982    }
10983
10984    /**
10985     * The transform matrix of this view, which is calculated based on the current
10986     * rotation, scale, and pivot properties.
10987     *
10988     * @see #getRotation()
10989     * @see #getScaleX()
10990     * @see #getScaleY()
10991     * @see #getPivotX()
10992     * @see #getPivotY()
10993     * @return The current transform matrix for the view
10994     */
10995    public Matrix getMatrix() {
10996        ensureTransformationInfo();
10997        final Matrix matrix = mTransformationInfo.mMatrix;
10998        mRenderNode.getMatrix(matrix);
10999        return matrix;
11000    }
11001
11002    /**
11003     * Returns true if the transform matrix is the identity matrix.
11004     * Recomputes the matrix if necessary.
11005     *
11006     * @return True if the transform matrix is the identity matrix, false otherwise.
11007     */
11008    final boolean hasIdentityMatrix() {
11009        return mRenderNode.hasIdentityMatrix();
11010    }
11011
11012    void ensureTransformationInfo() {
11013        if (mTransformationInfo == null) {
11014            mTransformationInfo = new TransformationInfo();
11015        }
11016    }
11017
11018   /**
11019     * Utility method to retrieve the inverse of the current mMatrix property.
11020     * We cache the matrix to avoid recalculating it when transform properties
11021     * have not changed.
11022     *
11023     * @return The inverse of the current matrix of this view.
11024     * @hide
11025     */
11026    public final Matrix getInverseMatrix() {
11027        ensureTransformationInfo();
11028        if (mTransformationInfo.mInverseMatrix == null) {
11029            mTransformationInfo.mInverseMatrix = new Matrix();
11030        }
11031        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11032        mRenderNode.getInverseMatrix(matrix);
11033        return matrix;
11034    }
11035
11036    /**
11037     * Gets the distance along the Z axis from the camera to this view.
11038     *
11039     * @see #setCameraDistance(float)
11040     *
11041     * @return The distance along the Z axis.
11042     */
11043    public float getCameraDistance() {
11044        final float dpi = mResources.getDisplayMetrics().densityDpi;
11045        return -(mRenderNode.getCameraDistance() * dpi);
11046    }
11047
11048    /**
11049     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11050     * views are drawn) from the camera to this view. The camera's distance
11051     * affects 3D transformations, for instance rotations around the X and Y
11052     * axis. If the rotationX or rotationY properties are changed and this view is
11053     * large (more than half the size of the screen), it is recommended to always
11054     * use a camera distance that's greater than the height (X axis rotation) or
11055     * the width (Y axis rotation) of this view.</p>
11056     *
11057     * <p>The distance of the camera from the view plane can have an affect on the
11058     * perspective distortion of the view when it is rotated around the x or y axis.
11059     * For example, a large distance will result in a large viewing angle, and there
11060     * will not be much perspective distortion of the view as it rotates. A short
11061     * distance may cause much more perspective distortion upon rotation, and can
11062     * also result in some drawing artifacts if the rotated view ends up partially
11063     * behind the camera (which is why the recommendation is to use a distance at
11064     * least as far as the size of the view, if the view is to be rotated.)</p>
11065     *
11066     * <p>The distance is expressed in "depth pixels." The default distance depends
11067     * on the screen density. For instance, on a medium density display, the
11068     * default distance is 1280. On a high density display, the default distance
11069     * is 1920.</p>
11070     *
11071     * <p>If you want to specify a distance that leads to visually consistent
11072     * results across various densities, use the following formula:</p>
11073     * <pre>
11074     * float scale = context.getResources().getDisplayMetrics().density;
11075     * view.setCameraDistance(distance * scale);
11076     * </pre>
11077     *
11078     * <p>The density scale factor of a high density display is 1.5,
11079     * and 1920 = 1280 * 1.5.</p>
11080     *
11081     * @param distance The distance in "depth pixels", if negative the opposite
11082     *        value is used
11083     *
11084     * @see #setRotationX(float)
11085     * @see #setRotationY(float)
11086     */
11087    public void setCameraDistance(float distance) {
11088        final float dpi = mResources.getDisplayMetrics().densityDpi;
11089
11090        invalidateViewProperty(true, false);
11091        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11092        invalidateViewProperty(false, false);
11093
11094        invalidateParentIfNeededAndWasQuickRejected();
11095    }
11096
11097    /**
11098     * The degrees that the view is rotated around the pivot point.
11099     *
11100     * @see #setRotation(float)
11101     * @see #getPivotX()
11102     * @see #getPivotY()
11103     *
11104     * @return The degrees of rotation.
11105     */
11106    @ViewDebug.ExportedProperty(category = "drawing")
11107    public float getRotation() {
11108        return mRenderNode.getRotation();
11109    }
11110
11111    /**
11112     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11113     * result in clockwise rotation.
11114     *
11115     * @param rotation The degrees of rotation.
11116     *
11117     * @see #getRotation()
11118     * @see #getPivotX()
11119     * @see #getPivotY()
11120     * @see #setRotationX(float)
11121     * @see #setRotationY(float)
11122     *
11123     * @attr ref android.R.styleable#View_rotation
11124     */
11125    public void setRotation(float rotation) {
11126        if (rotation != getRotation()) {
11127            // Double-invalidation is necessary to capture view's old and new areas
11128            invalidateViewProperty(true, false);
11129            mRenderNode.setRotation(rotation);
11130            invalidateViewProperty(false, true);
11131
11132            invalidateParentIfNeededAndWasQuickRejected();
11133            notifySubtreeAccessibilityStateChangedIfNeeded();
11134        }
11135    }
11136
11137    /**
11138     * The degrees that the view is rotated around the vertical axis through the pivot point.
11139     *
11140     * @see #getPivotX()
11141     * @see #getPivotY()
11142     * @see #setRotationY(float)
11143     *
11144     * @return The degrees of Y rotation.
11145     */
11146    @ViewDebug.ExportedProperty(category = "drawing")
11147    public float getRotationY() {
11148        return mRenderNode.getRotationY();
11149    }
11150
11151    /**
11152     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11153     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11154     * down the y axis.
11155     *
11156     * When rotating large views, it is recommended to adjust the camera distance
11157     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11158     *
11159     * @param rotationY The degrees of Y rotation.
11160     *
11161     * @see #getRotationY()
11162     * @see #getPivotX()
11163     * @see #getPivotY()
11164     * @see #setRotation(float)
11165     * @see #setRotationX(float)
11166     * @see #setCameraDistance(float)
11167     *
11168     * @attr ref android.R.styleable#View_rotationY
11169     */
11170    public void setRotationY(float rotationY) {
11171        if (rotationY != getRotationY()) {
11172            invalidateViewProperty(true, false);
11173            mRenderNode.setRotationY(rotationY);
11174            invalidateViewProperty(false, true);
11175
11176            invalidateParentIfNeededAndWasQuickRejected();
11177            notifySubtreeAccessibilityStateChangedIfNeeded();
11178        }
11179    }
11180
11181    /**
11182     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11183     *
11184     * @see #getPivotX()
11185     * @see #getPivotY()
11186     * @see #setRotationX(float)
11187     *
11188     * @return The degrees of X rotation.
11189     */
11190    @ViewDebug.ExportedProperty(category = "drawing")
11191    public float getRotationX() {
11192        return mRenderNode.getRotationX();
11193    }
11194
11195    /**
11196     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
11197     * Increasing values result in clockwise rotation from the viewpoint of looking down the
11198     * x axis.
11199     *
11200     * When rotating large views, it is recommended to adjust the camera distance
11201     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11202     *
11203     * @param rotationX The degrees of X rotation.
11204     *
11205     * @see #getRotationX()
11206     * @see #getPivotX()
11207     * @see #getPivotY()
11208     * @see #setRotation(float)
11209     * @see #setRotationY(float)
11210     * @see #setCameraDistance(float)
11211     *
11212     * @attr ref android.R.styleable#View_rotationX
11213     */
11214    public void setRotationX(float rotationX) {
11215        if (rotationX != getRotationX()) {
11216            invalidateViewProperty(true, false);
11217            mRenderNode.setRotationX(rotationX);
11218            invalidateViewProperty(false, true);
11219
11220            invalidateParentIfNeededAndWasQuickRejected();
11221            notifySubtreeAccessibilityStateChangedIfNeeded();
11222        }
11223    }
11224
11225    /**
11226     * The amount that the view is scaled in x around the pivot point, as a proportion of
11227     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
11228     *
11229     * <p>By default, this is 1.0f.
11230     *
11231     * @see #getPivotX()
11232     * @see #getPivotY()
11233     * @return The scaling factor.
11234     */
11235    @ViewDebug.ExportedProperty(category = "drawing")
11236    public float getScaleX() {
11237        return mRenderNode.getScaleX();
11238    }
11239
11240    /**
11241     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
11242     * the view's unscaled width. A value of 1 means that no scaling is applied.
11243     *
11244     * @param scaleX The scaling factor.
11245     * @see #getPivotX()
11246     * @see #getPivotY()
11247     *
11248     * @attr ref android.R.styleable#View_scaleX
11249     */
11250    public void setScaleX(float scaleX) {
11251        if (scaleX != getScaleX()) {
11252            invalidateViewProperty(true, false);
11253            mRenderNode.setScaleX(scaleX);
11254            invalidateViewProperty(false, true);
11255
11256            invalidateParentIfNeededAndWasQuickRejected();
11257            notifySubtreeAccessibilityStateChangedIfNeeded();
11258        }
11259    }
11260
11261    /**
11262     * The amount that the view is scaled in y around the pivot point, as a proportion of
11263     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
11264     *
11265     * <p>By default, this is 1.0f.
11266     *
11267     * @see #getPivotX()
11268     * @see #getPivotY()
11269     * @return The scaling factor.
11270     */
11271    @ViewDebug.ExportedProperty(category = "drawing")
11272    public float getScaleY() {
11273        return mRenderNode.getScaleY();
11274    }
11275
11276    /**
11277     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
11278     * the view's unscaled width. A value of 1 means that no scaling is applied.
11279     *
11280     * @param scaleY The scaling factor.
11281     * @see #getPivotX()
11282     * @see #getPivotY()
11283     *
11284     * @attr ref android.R.styleable#View_scaleY
11285     */
11286    public void setScaleY(float scaleY) {
11287        if (scaleY != getScaleY()) {
11288            invalidateViewProperty(true, false);
11289            mRenderNode.setScaleY(scaleY);
11290            invalidateViewProperty(false, true);
11291
11292            invalidateParentIfNeededAndWasQuickRejected();
11293            notifySubtreeAccessibilityStateChangedIfNeeded();
11294        }
11295    }
11296
11297    /**
11298     * The x location of the point around which the view is {@link #setRotation(float) rotated}
11299     * and {@link #setScaleX(float) scaled}.
11300     *
11301     * @see #getRotation()
11302     * @see #getScaleX()
11303     * @see #getScaleY()
11304     * @see #getPivotY()
11305     * @return The x location of the pivot point.
11306     *
11307     * @attr ref android.R.styleable#View_transformPivotX
11308     */
11309    @ViewDebug.ExportedProperty(category = "drawing")
11310    public float getPivotX() {
11311        return mRenderNode.getPivotX();
11312    }
11313
11314    /**
11315     * Sets the x location of the point around which the view is
11316     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
11317     * By default, the pivot point is centered on the object.
11318     * Setting this property disables this behavior and causes the view to use only the
11319     * explicitly set pivotX and pivotY values.
11320     *
11321     * @param pivotX The x location of the pivot point.
11322     * @see #getRotation()
11323     * @see #getScaleX()
11324     * @see #getScaleY()
11325     * @see #getPivotY()
11326     *
11327     * @attr ref android.R.styleable#View_transformPivotX
11328     */
11329    public void setPivotX(float pivotX) {
11330        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
11331            invalidateViewProperty(true, false);
11332            mRenderNode.setPivotX(pivotX);
11333            invalidateViewProperty(false, true);
11334
11335            invalidateParentIfNeededAndWasQuickRejected();
11336        }
11337    }
11338
11339    /**
11340     * The y location of the point around which the view is {@link #setRotation(float) rotated}
11341     * and {@link #setScaleY(float) scaled}.
11342     *
11343     * @see #getRotation()
11344     * @see #getScaleX()
11345     * @see #getScaleY()
11346     * @see #getPivotY()
11347     * @return The y location of the pivot point.
11348     *
11349     * @attr ref android.R.styleable#View_transformPivotY
11350     */
11351    @ViewDebug.ExportedProperty(category = "drawing")
11352    public float getPivotY() {
11353        return mRenderNode.getPivotY();
11354    }
11355
11356    /**
11357     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
11358     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
11359     * Setting this property disables this behavior and causes the view to use only the
11360     * explicitly set pivotX and pivotY values.
11361     *
11362     * @param pivotY The y location of the pivot point.
11363     * @see #getRotation()
11364     * @see #getScaleX()
11365     * @see #getScaleY()
11366     * @see #getPivotY()
11367     *
11368     * @attr ref android.R.styleable#View_transformPivotY
11369     */
11370    public void setPivotY(float pivotY) {
11371        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
11372            invalidateViewProperty(true, false);
11373            mRenderNode.setPivotY(pivotY);
11374            invalidateViewProperty(false, true);
11375
11376            invalidateParentIfNeededAndWasQuickRejected();
11377        }
11378    }
11379
11380    /**
11381     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
11382     * completely transparent and 1 means the view is completely opaque.
11383     *
11384     * <p>By default this is 1.0f.
11385     * @return The opacity of the view.
11386     */
11387    @ViewDebug.ExportedProperty(category = "drawing")
11388    public float getAlpha() {
11389        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
11390    }
11391
11392    /**
11393     * Returns whether this View has content which overlaps.
11394     *
11395     * <p>This function, intended to be overridden by specific View types, is an optimization when
11396     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
11397     * an offscreen buffer and then composited into place, which can be expensive. If the view has
11398     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
11399     * directly. An example of overlapping rendering is a TextView with a background image, such as
11400     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
11401     * ImageView with only the foreground image. The default implementation returns true; subclasses
11402     * should override if they have cases which can be optimized.</p>
11403     *
11404     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
11405     * necessitates that a View return true if it uses the methods internally without passing the
11406     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
11407     *
11408     * @return true if the content in this view might overlap, false otherwise.
11409     */
11410    @ViewDebug.ExportedProperty(category = "drawing")
11411    public boolean hasOverlappingRendering() {
11412        return true;
11413    }
11414
11415    /**
11416     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
11417     * completely transparent and 1 means the view is completely opaque.
11418     *
11419     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
11420     * can have significant performance implications, especially for large views. It is best to use
11421     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
11422     *
11423     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
11424     * strongly recommended for performance reasons to either override
11425     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
11426     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
11427     * of the animation. On versions {@link android.os.Build.VERSION_CODES#MNC} and below,
11428     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
11429     * of rendering cost, even for simple or small views. Starting with
11430     * {@link android.os.Build.VERSION_CODES#MNC}, {@link #LAYER_TYPE_HARDWARE} is automatically
11431     * applied to the view at the rendering level.</p>
11432     *
11433     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
11434     * responsible for applying the opacity itself.</p>
11435     *
11436     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
11437     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
11438     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
11439     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
11440     *
11441     * <p>Starting with {@link android.os.Build.VERSION_CODES#MNC}, setting a translucent alpha
11442     * value will clip a View to its bounds, unless the View returns <code>false</code> from
11443     * {@link #hasOverlappingRendering}.</p>
11444     *
11445     * @param alpha The opacity of the view.
11446     *
11447     * @see #hasOverlappingRendering()
11448     * @see #setLayerType(int, android.graphics.Paint)
11449     *
11450     * @attr ref android.R.styleable#View_alpha
11451     */
11452    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
11453        ensureTransformationInfo();
11454        if (mTransformationInfo.mAlpha != alpha) {
11455            mTransformationInfo.mAlpha = alpha;
11456            if (onSetAlpha((int) (alpha * 255))) {
11457                mPrivateFlags |= PFLAG_ALPHA_SET;
11458                // subclass is handling alpha - don't optimize rendering cache invalidation
11459                invalidateParentCaches();
11460                invalidate(true);
11461            } else {
11462                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11463                invalidateViewProperty(true, false);
11464                mRenderNode.setAlpha(getFinalAlpha());
11465                notifyViewAccessibilityStateChangedIfNeeded(
11466                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11467            }
11468        }
11469    }
11470
11471    /**
11472     * Faster version of setAlpha() which performs the same steps except there are
11473     * no calls to invalidate(). The caller of this function should perform proper invalidation
11474     * on the parent and this object. The return value indicates whether the subclass handles
11475     * alpha (the return value for onSetAlpha()).
11476     *
11477     * @param alpha The new value for the alpha property
11478     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
11479     *         the new value for the alpha property is different from the old value
11480     */
11481    boolean setAlphaNoInvalidation(float alpha) {
11482        ensureTransformationInfo();
11483        if (mTransformationInfo.mAlpha != alpha) {
11484            mTransformationInfo.mAlpha = alpha;
11485            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
11486            if (subclassHandlesAlpha) {
11487                mPrivateFlags |= PFLAG_ALPHA_SET;
11488                return true;
11489            } else {
11490                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11491                mRenderNode.setAlpha(getFinalAlpha());
11492            }
11493        }
11494        return false;
11495    }
11496
11497    /**
11498     * This property is hidden and intended only for use by the Fade transition, which
11499     * animates it to produce a visual translucency that does not side-effect (or get
11500     * affected by) the real alpha property. This value is composited with the other
11501     * alpha value (and the AlphaAnimation value, when that is present) to produce
11502     * a final visual translucency result, which is what is passed into the DisplayList.
11503     *
11504     * @hide
11505     */
11506    public void setTransitionAlpha(float alpha) {
11507        ensureTransformationInfo();
11508        if (mTransformationInfo.mTransitionAlpha != alpha) {
11509            mTransformationInfo.mTransitionAlpha = alpha;
11510            mPrivateFlags &= ~PFLAG_ALPHA_SET;
11511            invalidateViewProperty(true, false);
11512            mRenderNode.setAlpha(getFinalAlpha());
11513        }
11514    }
11515
11516    /**
11517     * Calculates the visual alpha of this view, which is a combination of the actual
11518     * alpha value and the transitionAlpha value (if set).
11519     */
11520    private float getFinalAlpha() {
11521        if (mTransformationInfo != null) {
11522            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
11523        }
11524        return 1;
11525    }
11526
11527    /**
11528     * This property is hidden and intended only for use by the Fade transition, which
11529     * animates it to produce a visual translucency that does not side-effect (or get
11530     * affected by) the real alpha property. This value is composited with the other
11531     * alpha value (and the AlphaAnimation value, when that is present) to produce
11532     * a final visual translucency result, which is what is passed into the DisplayList.
11533     *
11534     * @hide
11535     */
11536    @ViewDebug.ExportedProperty(category = "drawing")
11537    public float getTransitionAlpha() {
11538        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
11539    }
11540
11541    /**
11542     * Top position of this view relative to its parent.
11543     *
11544     * @return The top of this view, in pixels.
11545     */
11546    @ViewDebug.CapturedViewProperty
11547    public final int getTop() {
11548        return mTop;
11549    }
11550
11551    /**
11552     * Sets the top position of this view relative to its parent. This method is meant to be called
11553     * by the layout system and should not generally be called otherwise, because the property
11554     * may be changed at any time by the layout.
11555     *
11556     * @param top The top of this view, in pixels.
11557     */
11558    public final void setTop(int top) {
11559        if (top != mTop) {
11560            final boolean matrixIsIdentity = hasIdentityMatrix();
11561            if (matrixIsIdentity) {
11562                if (mAttachInfo != null) {
11563                    int minTop;
11564                    int yLoc;
11565                    if (top < mTop) {
11566                        minTop = top;
11567                        yLoc = top - mTop;
11568                    } else {
11569                        minTop = mTop;
11570                        yLoc = 0;
11571                    }
11572                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11573                }
11574            } else {
11575                // Double-invalidation is necessary to capture view's old and new areas
11576                invalidate(true);
11577            }
11578
11579            int width = mRight - mLeft;
11580            int oldHeight = mBottom - mTop;
11581
11582            mTop = top;
11583            mRenderNode.setTop(mTop);
11584
11585            sizeChange(width, mBottom - mTop, width, oldHeight);
11586
11587            if (!matrixIsIdentity) {
11588                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11589                invalidate(true);
11590            }
11591            mBackgroundSizeChanged = true;
11592            if (mForegroundInfo != null) {
11593                mForegroundInfo.mBoundsChanged = true;
11594            }
11595            invalidateParentIfNeeded();
11596            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11597                // View was rejected last time it was drawn by its parent; this may have changed
11598                invalidateParentIfNeeded();
11599            }
11600        }
11601    }
11602
11603    /**
11604     * Bottom position of this view relative to its parent.
11605     *
11606     * @return The bottom of this view, in pixels.
11607     */
11608    @ViewDebug.CapturedViewProperty
11609    public final int getBottom() {
11610        return mBottom;
11611    }
11612
11613    /**
11614     * True if this view has changed since the last time being drawn.
11615     *
11616     * @return The dirty state of this view.
11617     */
11618    public boolean isDirty() {
11619        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11620    }
11621
11622    /**
11623     * Sets the bottom position of this view relative to its parent. This method is meant to be
11624     * called by the layout system and should not generally be called otherwise, because the
11625     * property may be changed at any time by the layout.
11626     *
11627     * @param bottom The bottom of this view, in pixels.
11628     */
11629    public final void setBottom(int bottom) {
11630        if (bottom != mBottom) {
11631            final boolean matrixIsIdentity = hasIdentityMatrix();
11632            if (matrixIsIdentity) {
11633                if (mAttachInfo != null) {
11634                    int maxBottom;
11635                    if (bottom < mBottom) {
11636                        maxBottom = mBottom;
11637                    } else {
11638                        maxBottom = bottom;
11639                    }
11640                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11641                }
11642            } else {
11643                // Double-invalidation is necessary to capture view's old and new areas
11644                invalidate(true);
11645            }
11646
11647            int width = mRight - mLeft;
11648            int oldHeight = mBottom - mTop;
11649
11650            mBottom = bottom;
11651            mRenderNode.setBottom(mBottom);
11652
11653            sizeChange(width, mBottom - mTop, width, oldHeight);
11654
11655            if (!matrixIsIdentity) {
11656                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11657                invalidate(true);
11658            }
11659            mBackgroundSizeChanged = true;
11660            if (mForegroundInfo != null) {
11661                mForegroundInfo.mBoundsChanged = true;
11662            }
11663            invalidateParentIfNeeded();
11664            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11665                // View was rejected last time it was drawn by its parent; this may have changed
11666                invalidateParentIfNeeded();
11667            }
11668        }
11669    }
11670
11671    /**
11672     * Left position of this view relative to its parent.
11673     *
11674     * @return The left edge of this view, in pixels.
11675     */
11676    @ViewDebug.CapturedViewProperty
11677    public final int getLeft() {
11678        return mLeft;
11679    }
11680
11681    /**
11682     * Sets the left position of this view relative to its parent. This method is meant to be called
11683     * by the layout system and should not generally be called otherwise, because the property
11684     * may be changed at any time by the layout.
11685     *
11686     * @param left The left of this view, in pixels.
11687     */
11688    public final void setLeft(int left) {
11689        if (left != mLeft) {
11690            final boolean matrixIsIdentity = hasIdentityMatrix();
11691            if (matrixIsIdentity) {
11692                if (mAttachInfo != null) {
11693                    int minLeft;
11694                    int xLoc;
11695                    if (left < mLeft) {
11696                        minLeft = left;
11697                        xLoc = left - mLeft;
11698                    } else {
11699                        minLeft = mLeft;
11700                        xLoc = 0;
11701                    }
11702                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11703                }
11704            } else {
11705                // Double-invalidation is necessary to capture view's old and new areas
11706                invalidate(true);
11707            }
11708
11709            int oldWidth = mRight - mLeft;
11710            int height = mBottom - mTop;
11711
11712            mLeft = left;
11713            mRenderNode.setLeft(left);
11714
11715            sizeChange(mRight - mLeft, height, oldWidth, height);
11716
11717            if (!matrixIsIdentity) {
11718                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11719                invalidate(true);
11720            }
11721            mBackgroundSizeChanged = true;
11722            if (mForegroundInfo != null) {
11723                mForegroundInfo.mBoundsChanged = true;
11724            }
11725            invalidateParentIfNeeded();
11726            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11727                // View was rejected last time it was drawn by its parent; this may have changed
11728                invalidateParentIfNeeded();
11729            }
11730        }
11731    }
11732
11733    /**
11734     * Right position of this view relative to its parent.
11735     *
11736     * @return The right edge of this view, in pixels.
11737     */
11738    @ViewDebug.CapturedViewProperty
11739    public final int getRight() {
11740        return mRight;
11741    }
11742
11743    /**
11744     * Sets the right position of this view relative to its parent. This method is meant to be called
11745     * by the layout system and should not generally be called otherwise, because the property
11746     * may be changed at any time by the layout.
11747     *
11748     * @param right The right of this view, in pixels.
11749     */
11750    public final void setRight(int right) {
11751        if (right != mRight) {
11752            final boolean matrixIsIdentity = hasIdentityMatrix();
11753            if (matrixIsIdentity) {
11754                if (mAttachInfo != null) {
11755                    int maxRight;
11756                    if (right < mRight) {
11757                        maxRight = mRight;
11758                    } else {
11759                        maxRight = right;
11760                    }
11761                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11762                }
11763            } else {
11764                // Double-invalidation is necessary to capture view's old and new areas
11765                invalidate(true);
11766            }
11767
11768            int oldWidth = mRight - mLeft;
11769            int height = mBottom - mTop;
11770
11771            mRight = right;
11772            mRenderNode.setRight(mRight);
11773
11774            sizeChange(mRight - mLeft, height, oldWidth, height);
11775
11776            if (!matrixIsIdentity) {
11777                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11778                invalidate(true);
11779            }
11780            mBackgroundSizeChanged = true;
11781            if (mForegroundInfo != null) {
11782                mForegroundInfo.mBoundsChanged = true;
11783            }
11784            invalidateParentIfNeeded();
11785            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11786                // View was rejected last time it was drawn by its parent; this may have changed
11787                invalidateParentIfNeeded();
11788            }
11789        }
11790    }
11791
11792    /**
11793     * The visual x position of this view, in pixels. This is equivalent to the
11794     * {@link #setTranslationX(float) translationX} property plus the current
11795     * {@link #getLeft() left} property.
11796     *
11797     * @return The visual x position of this view, in pixels.
11798     */
11799    @ViewDebug.ExportedProperty(category = "drawing")
11800    public float getX() {
11801        return mLeft + getTranslationX();
11802    }
11803
11804    /**
11805     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11806     * {@link #setTranslationX(float) translationX} property to be the difference between
11807     * the x value passed in and the current {@link #getLeft() left} property.
11808     *
11809     * @param x The visual x position of this view, in pixels.
11810     */
11811    public void setX(float x) {
11812        setTranslationX(x - mLeft);
11813    }
11814
11815    /**
11816     * The visual y position of this view, in pixels. This is equivalent to the
11817     * {@link #setTranslationY(float) translationY} property plus the current
11818     * {@link #getTop() top} property.
11819     *
11820     * @return The visual y position of this view, in pixels.
11821     */
11822    @ViewDebug.ExportedProperty(category = "drawing")
11823    public float getY() {
11824        return mTop + getTranslationY();
11825    }
11826
11827    /**
11828     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11829     * {@link #setTranslationY(float) translationY} property to be the difference between
11830     * the y value passed in and the current {@link #getTop() top} property.
11831     *
11832     * @param y The visual y position of this view, in pixels.
11833     */
11834    public void setY(float y) {
11835        setTranslationY(y - mTop);
11836    }
11837
11838    /**
11839     * The visual z position of this view, in pixels. This is equivalent to the
11840     * {@link #setTranslationZ(float) translationZ} property plus the current
11841     * {@link #getElevation() elevation} property.
11842     *
11843     * @return The visual z position of this view, in pixels.
11844     */
11845    @ViewDebug.ExportedProperty(category = "drawing")
11846    public float getZ() {
11847        return getElevation() + getTranslationZ();
11848    }
11849
11850    /**
11851     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11852     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11853     * the x value passed in and the current {@link #getElevation() elevation} property.
11854     *
11855     * @param z The visual z position of this view, in pixels.
11856     */
11857    public void setZ(float z) {
11858        setTranslationZ(z - getElevation());
11859    }
11860
11861    /**
11862     * The base elevation of this view relative to its parent, in pixels.
11863     *
11864     * @return The base depth position of the view, in pixels.
11865     */
11866    @ViewDebug.ExportedProperty(category = "drawing")
11867    public float getElevation() {
11868        return mRenderNode.getElevation();
11869    }
11870
11871    /**
11872     * Sets the base elevation of this view, in pixels.
11873     *
11874     * @attr ref android.R.styleable#View_elevation
11875     */
11876    public void setElevation(float elevation) {
11877        if (elevation != getElevation()) {
11878            invalidateViewProperty(true, false);
11879            mRenderNode.setElevation(elevation);
11880            invalidateViewProperty(false, true);
11881
11882            invalidateParentIfNeededAndWasQuickRejected();
11883        }
11884    }
11885
11886    /**
11887     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11888     * This position is post-layout, in addition to wherever the object's
11889     * layout placed it.
11890     *
11891     * @return The horizontal position of this view relative to its left position, in pixels.
11892     */
11893    @ViewDebug.ExportedProperty(category = "drawing")
11894    public float getTranslationX() {
11895        return mRenderNode.getTranslationX();
11896    }
11897
11898    /**
11899     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11900     * This effectively positions the object post-layout, in addition to wherever the object's
11901     * layout placed it.
11902     *
11903     * @param translationX The horizontal position of this view relative to its left position,
11904     * in pixels.
11905     *
11906     * @attr ref android.R.styleable#View_translationX
11907     */
11908    public void setTranslationX(float translationX) {
11909        if (translationX != getTranslationX()) {
11910            invalidateViewProperty(true, false);
11911            mRenderNode.setTranslationX(translationX);
11912            invalidateViewProperty(false, true);
11913
11914            invalidateParentIfNeededAndWasQuickRejected();
11915            notifySubtreeAccessibilityStateChangedIfNeeded();
11916        }
11917    }
11918
11919    /**
11920     * The vertical location of this view relative to its {@link #getTop() top} position.
11921     * This position is post-layout, in addition to wherever the object's
11922     * layout placed it.
11923     *
11924     * @return The vertical position of this view relative to its top position,
11925     * in pixels.
11926     */
11927    @ViewDebug.ExportedProperty(category = "drawing")
11928    public float getTranslationY() {
11929        return mRenderNode.getTranslationY();
11930    }
11931
11932    /**
11933     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11934     * This effectively positions the object post-layout, in addition to wherever the object's
11935     * layout placed it.
11936     *
11937     * @param translationY The vertical position of this view relative to its top position,
11938     * in pixels.
11939     *
11940     * @attr ref android.R.styleable#View_translationY
11941     */
11942    public void setTranslationY(float translationY) {
11943        if (translationY != getTranslationY()) {
11944            invalidateViewProperty(true, false);
11945            mRenderNode.setTranslationY(translationY);
11946            invalidateViewProperty(false, true);
11947
11948            invalidateParentIfNeededAndWasQuickRejected();
11949            notifySubtreeAccessibilityStateChangedIfNeeded();
11950        }
11951    }
11952
11953    /**
11954     * The depth location of this view relative to its {@link #getElevation() elevation}.
11955     *
11956     * @return The depth of this view relative to its elevation.
11957     */
11958    @ViewDebug.ExportedProperty(category = "drawing")
11959    public float getTranslationZ() {
11960        return mRenderNode.getTranslationZ();
11961    }
11962
11963    /**
11964     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11965     *
11966     * @attr ref android.R.styleable#View_translationZ
11967     */
11968    public void setTranslationZ(float translationZ) {
11969        if (translationZ != getTranslationZ()) {
11970            invalidateViewProperty(true, false);
11971            mRenderNode.setTranslationZ(translationZ);
11972            invalidateViewProperty(false, true);
11973
11974            invalidateParentIfNeededAndWasQuickRejected();
11975        }
11976    }
11977
11978    /** @hide */
11979    public void setAnimationMatrix(Matrix matrix) {
11980        invalidateViewProperty(true, false);
11981        mRenderNode.setAnimationMatrix(matrix);
11982        invalidateViewProperty(false, true);
11983
11984        invalidateParentIfNeededAndWasQuickRejected();
11985    }
11986
11987    /**
11988     * Returns the current StateListAnimator if exists.
11989     *
11990     * @return StateListAnimator or null if it does not exists
11991     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11992     */
11993    public StateListAnimator getStateListAnimator() {
11994        return mStateListAnimator;
11995    }
11996
11997    /**
11998     * Attaches the provided StateListAnimator to this View.
11999     * <p>
12000     * Any previously attached StateListAnimator will be detached.
12001     *
12002     * @param stateListAnimator The StateListAnimator to update the view
12003     * @see {@link android.animation.StateListAnimator}
12004     */
12005    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12006        if (mStateListAnimator == stateListAnimator) {
12007            return;
12008        }
12009        if (mStateListAnimator != null) {
12010            mStateListAnimator.setTarget(null);
12011        }
12012        mStateListAnimator = stateListAnimator;
12013        if (stateListAnimator != null) {
12014            stateListAnimator.setTarget(this);
12015            if (isAttachedToWindow()) {
12016                stateListAnimator.setState(getDrawableState());
12017            }
12018        }
12019    }
12020
12021    /**
12022     * Returns whether the Outline should be used to clip the contents of the View.
12023     * <p>
12024     * Note that this flag will only be respected if the View's Outline returns true from
12025     * {@link Outline#canClip()}.
12026     *
12027     * @see #setOutlineProvider(ViewOutlineProvider)
12028     * @see #setClipToOutline(boolean)
12029     */
12030    public final boolean getClipToOutline() {
12031        return mRenderNode.getClipToOutline();
12032    }
12033
12034    /**
12035     * Sets whether the View's Outline should be used to clip the contents of the View.
12036     * <p>
12037     * Only a single non-rectangular clip can be applied on a View at any time.
12038     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12039     * circular reveal} animation take priority over Outline clipping, and
12040     * child Outline clipping takes priority over Outline clipping done by a
12041     * parent.
12042     * <p>
12043     * Note that this flag will only be respected if the View's Outline returns true from
12044     * {@link Outline#canClip()}.
12045     *
12046     * @see #setOutlineProvider(ViewOutlineProvider)
12047     * @see #getClipToOutline()
12048     */
12049    public void setClipToOutline(boolean clipToOutline) {
12050        damageInParent();
12051        if (getClipToOutline() != clipToOutline) {
12052            mRenderNode.setClipToOutline(clipToOutline);
12053        }
12054    }
12055
12056    // correspond to the enum values of View_outlineProvider
12057    private static final int PROVIDER_BACKGROUND = 0;
12058    private static final int PROVIDER_NONE = 1;
12059    private static final int PROVIDER_BOUNDS = 2;
12060    private static final int PROVIDER_PADDED_BOUNDS = 3;
12061    private void setOutlineProviderFromAttribute(int providerInt) {
12062        switch (providerInt) {
12063            case PROVIDER_BACKGROUND:
12064                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12065                break;
12066            case PROVIDER_NONE:
12067                setOutlineProvider(null);
12068                break;
12069            case PROVIDER_BOUNDS:
12070                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12071                break;
12072            case PROVIDER_PADDED_BOUNDS:
12073                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12074                break;
12075        }
12076    }
12077
12078    /**
12079     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12080     * the shape of the shadow it casts, and enables outline clipping.
12081     * <p>
12082     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12083     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12084     * outline provider with this method allows this behavior to be overridden.
12085     * <p>
12086     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12087     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12088     * <p>
12089     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12090     *
12091     * @see #setClipToOutline(boolean)
12092     * @see #getClipToOutline()
12093     * @see #getOutlineProvider()
12094     */
12095    public void setOutlineProvider(ViewOutlineProvider provider) {
12096        mOutlineProvider = provider;
12097        invalidateOutline();
12098    }
12099
12100    /**
12101     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12102     * that defines the shape of the shadow it casts, and enables outline clipping.
12103     *
12104     * @see #setOutlineProvider(ViewOutlineProvider)
12105     */
12106    public ViewOutlineProvider getOutlineProvider() {
12107        return mOutlineProvider;
12108    }
12109
12110    /**
12111     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12112     *
12113     * @see #setOutlineProvider(ViewOutlineProvider)
12114     */
12115    public void invalidateOutline() {
12116        rebuildOutline();
12117
12118        notifySubtreeAccessibilityStateChangedIfNeeded();
12119        invalidateViewProperty(false, false);
12120    }
12121
12122    /**
12123     * Internal version of {@link #invalidateOutline()} which invalidates the
12124     * outline without invalidating the view itself. This is intended to be called from
12125     * within methods in the View class itself which are the result of the view being
12126     * invalidated already. For example, when we are drawing the background of a View,
12127     * we invalidate the outline in case it changed in the meantime, but we do not
12128     * need to invalidate the view because we're already drawing the background as part
12129     * of drawing the view in response to an earlier invalidation of the view.
12130     */
12131    private void rebuildOutline() {
12132        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12133        if (mAttachInfo == null) return;
12134
12135        if (mOutlineProvider == null) {
12136            // no provider, remove outline
12137            mRenderNode.setOutline(null);
12138        } else {
12139            final Outline outline = mAttachInfo.mTmpOutline;
12140            outline.setEmpty();
12141            outline.setAlpha(1.0f);
12142
12143            mOutlineProvider.getOutline(this, outline);
12144            mRenderNode.setOutline(outline);
12145        }
12146    }
12147
12148    /**
12149     * HierarchyViewer only
12150     *
12151     * @hide
12152     */
12153    @ViewDebug.ExportedProperty(category = "drawing")
12154    public boolean hasShadow() {
12155        return mRenderNode.hasShadow();
12156    }
12157
12158
12159    /** @hide */
12160    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
12161        mRenderNode.setRevealClip(shouldClip, x, y, radius);
12162        invalidateViewProperty(false, false);
12163    }
12164
12165    /**
12166     * Hit rectangle in parent's coordinates
12167     *
12168     * @param outRect The hit rectangle of the view.
12169     */
12170    public void getHitRect(Rect outRect) {
12171        if (hasIdentityMatrix() || mAttachInfo == null) {
12172            outRect.set(mLeft, mTop, mRight, mBottom);
12173        } else {
12174            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
12175            tmpRect.set(0, 0, getWidth(), getHeight());
12176            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
12177            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
12178                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
12179        }
12180    }
12181
12182    /**
12183     * Determines whether the given point, in local coordinates is inside the view.
12184     */
12185    /*package*/ final boolean pointInView(float localX, float localY) {
12186        return localX >= 0 && localX < (mRight - mLeft)
12187                && localY >= 0 && localY < (mBottom - mTop);
12188    }
12189
12190    /**
12191     * Utility method to determine whether the given point, in local coordinates,
12192     * is inside the view, where the area of the view is expanded by the slop factor.
12193     * This method is called while processing touch-move events to determine if the event
12194     * is still within the view.
12195     *
12196     * @hide
12197     */
12198    public boolean pointInView(float localX, float localY, float slop) {
12199        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
12200                localY < ((mBottom - mTop) + slop);
12201    }
12202
12203    /**
12204     * When a view has focus and the user navigates away from it, the next view is searched for
12205     * starting from the rectangle filled in by this method.
12206     *
12207     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
12208     * of the view.  However, if your view maintains some idea of internal selection,
12209     * such as a cursor, or a selected row or column, you should override this method and
12210     * fill in a more specific rectangle.
12211     *
12212     * @param r The rectangle to fill in, in this view's coordinates.
12213     */
12214    public void getFocusedRect(Rect r) {
12215        getDrawingRect(r);
12216    }
12217
12218    /**
12219     * If some part of this view is not clipped by any of its parents, then
12220     * return that area in r in global (root) coordinates. To convert r to local
12221     * coordinates (without taking possible View rotations into account), offset
12222     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
12223     * If the view is completely clipped or translated out, return false.
12224     *
12225     * @param r If true is returned, r holds the global coordinates of the
12226     *        visible portion of this view.
12227     * @param globalOffset If true is returned, globalOffset holds the dx,dy
12228     *        between this view and its root. globalOffet may be null.
12229     * @return true if r is non-empty (i.e. part of the view is visible at the
12230     *         root level.
12231     */
12232    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
12233        int width = mRight - mLeft;
12234        int height = mBottom - mTop;
12235        if (width > 0 && height > 0) {
12236            r.set(0, 0, width, height);
12237            if (globalOffset != null) {
12238                globalOffset.set(-mScrollX, -mScrollY);
12239            }
12240            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
12241        }
12242        return false;
12243    }
12244
12245    public final boolean getGlobalVisibleRect(Rect r) {
12246        return getGlobalVisibleRect(r, null);
12247    }
12248
12249    public final boolean getLocalVisibleRect(Rect r) {
12250        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
12251        if (getGlobalVisibleRect(r, offset)) {
12252            r.offset(-offset.x, -offset.y); // make r local
12253            return true;
12254        }
12255        return false;
12256    }
12257
12258    /**
12259     * Offset this view's vertical location by the specified number of pixels.
12260     *
12261     * @param offset the number of pixels to offset the view by
12262     */
12263    public void offsetTopAndBottom(int offset) {
12264        if (offset != 0) {
12265            final boolean matrixIsIdentity = hasIdentityMatrix();
12266            if (matrixIsIdentity) {
12267                if (isHardwareAccelerated()) {
12268                    invalidateViewProperty(false, false);
12269                } else {
12270                    final ViewParent p = mParent;
12271                    if (p != null && mAttachInfo != null) {
12272                        final Rect r = mAttachInfo.mTmpInvalRect;
12273                        int minTop;
12274                        int maxBottom;
12275                        int yLoc;
12276                        if (offset < 0) {
12277                            minTop = mTop + offset;
12278                            maxBottom = mBottom;
12279                            yLoc = offset;
12280                        } else {
12281                            minTop = mTop;
12282                            maxBottom = mBottom + offset;
12283                            yLoc = 0;
12284                        }
12285                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
12286                        p.invalidateChild(this, r);
12287                    }
12288                }
12289            } else {
12290                invalidateViewProperty(false, false);
12291            }
12292
12293            mTop += offset;
12294            mBottom += offset;
12295            mRenderNode.offsetTopAndBottom(offset);
12296            if (isHardwareAccelerated()) {
12297                invalidateViewProperty(false, false);
12298                invalidateParentIfNeededAndWasQuickRejected();
12299            } else {
12300                if (!matrixIsIdentity) {
12301                    invalidateViewProperty(false, true);
12302                }
12303                invalidateParentIfNeeded();
12304            }
12305            notifySubtreeAccessibilityStateChangedIfNeeded();
12306        }
12307    }
12308
12309    /**
12310     * Offset this view's horizontal location by the specified amount of pixels.
12311     *
12312     * @param offset the number of pixels to offset the view by
12313     */
12314    public void offsetLeftAndRight(int offset) {
12315        if (offset != 0) {
12316            final boolean matrixIsIdentity = hasIdentityMatrix();
12317            if (matrixIsIdentity) {
12318                if (isHardwareAccelerated()) {
12319                    invalidateViewProperty(false, false);
12320                } else {
12321                    final ViewParent p = mParent;
12322                    if (p != null && mAttachInfo != null) {
12323                        final Rect r = mAttachInfo.mTmpInvalRect;
12324                        int minLeft;
12325                        int maxRight;
12326                        if (offset < 0) {
12327                            minLeft = mLeft + offset;
12328                            maxRight = mRight;
12329                        } else {
12330                            minLeft = mLeft;
12331                            maxRight = mRight + offset;
12332                        }
12333                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
12334                        p.invalidateChild(this, r);
12335                    }
12336                }
12337            } else {
12338                invalidateViewProperty(false, false);
12339            }
12340
12341            mLeft += offset;
12342            mRight += offset;
12343            mRenderNode.offsetLeftAndRight(offset);
12344            if (isHardwareAccelerated()) {
12345                invalidateViewProperty(false, false);
12346                invalidateParentIfNeededAndWasQuickRejected();
12347            } else {
12348                if (!matrixIsIdentity) {
12349                    invalidateViewProperty(false, true);
12350                }
12351                invalidateParentIfNeeded();
12352            }
12353            notifySubtreeAccessibilityStateChangedIfNeeded();
12354        }
12355    }
12356
12357    /**
12358     * Get the LayoutParams associated with this view. All views should have
12359     * layout parameters. These supply parameters to the <i>parent</i> of this
12360     * view specifying how it should be arranged. There are many subclasses of
12361     * ViewGroup.LayoutParams, and these correspond to the different subclasses
12362     * of ViewGroup that are responsible for arranging their children.
12363     *
12364     * This method may return null if this View is not attached to a parent
12365     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
12366     * was not invoked successfully. When a View is attached to a parent
12367     * ViewGroup, this method must not return null.
12368     *
12369     * @return The LayoutParams associated with this view, or null if no
12370     *         parameters have been set yet
12371     */
12372    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
12373    public ViewGroup.LayoutParams getLayoutParams() {
12374        return mLayoutParams;
12375    }
12376
12377    /**
12378     * Set the layout parameters associated with this view. These supply
12379     * parameters to the <i>parent</i> of this view specifying how it should be
12380     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
12381     * correspond to the different subclasses of ViewGroup that are responsible
12382     * for arranging their children.
12383     *
12384     * @param params The layout parameters for this view, cannot be null
12385     */
12386    public void setLayoutParams(ViewGroup.LayoutParams params) {
12387        if (params == null) {
12388            throw new NullPointerException("Layout parameters cannot be null");
12389        }
12390        mLayoutParams = params;
12391        resolveLayoutParams();
12392        if (mParent instanceof ViewGroup) {
12393            ((ViewGroup) mParent).onSetLayoutParams(this, params);
12394        }
12395        requestLayout();
12396    }
12397
12398    /**
12399     * Resolve the layout parameters depending on the resolved layout direction
12400     *
12401     * @hide
12402     */
12403    public void resolveLayoutParams() {
12404        if (mLayoutParams != null) {
12405            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
12406        }
12407    }
12408
12409    /**
12410     * Set the scrolled position of your view. This will cause a call to
12411     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12412     * invalidated.
12413     * @param x the x position to scroll to
12414     * @param y the y position to scroll to
12415     */
12416    public void scrollTo(int x, int y) {
12417        if (mScrollX != x || mScrollY != y) {
12418            int oldX = mScrollX;
12419            int oldY = mScrollY;
12420            mScrollX = x;
12421            mScrollY = y;
12422            invalidateParentCaches();
12423            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
12424            if (!awakenScrollBars()) {
12425                postInvalidateOnAnimation();
12426            }
12427        }
12428    }
12429
12430    /**
12431     * Move the scrolled position of your view. This will cause a call to
12432     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12433     * invalidated.
12434     * @param x the amount of pixels to scroll by horizontally
12435     * @param y the amount of pixels to scroll by vertically
12436     */
12437    public void scrollBy(int x, int y) {
12438        scrollTo(mScrollX + x, mScrollY + y);
12439    }
12440
12441    /**
12442     * <p>Trigger the scrollbars to draw. When invoked this method starts an
12443     * animation to fade the scrollbars out after a default delay. If a subclass
12444     * provides animated scrolling, the start delay should equal the duration
12445     * of the scrolling animation.</p>
12446     *
12447     * <p>The animation starts only if at least one of the scrollbars is
12448     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
12449     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12450     * this method returns true, and false otherwise. If the animation is
12451     * started, this method calls {@link #invalidate()}; in that case the
12452     * caller should not call {@link #invalidate()}.</p>
12453     *
12454     * <p>This method should be invoked every time a subclass directly updates
12455     * the scroll parameters.</p>
12456     *
12457     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
12458     * and {@link #scrollTo(int, int)}.</p>
12459     *
12460     * @return true if the animation is played, false otherwise
12461     *
12462     * @see #awakenScrollBars(int)
12463     * @see #scrollBy(int, int)
12464     * @see #scrollTo(int, int)
12465     * @see #isHorizontalScrollBarEnabled()
12466     * @see #isVerticalScrollBarEnabled()
12467     * @see #setHorizontalScrollBarEnabled(boolean)
12468     * @see #setVerticalScrollBarEnabled(boolean)
12469     */
12470    protected boolean awakenScrollBars() {
12471        return mScrollCache != null &&
12472                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
12473    }
12474
12475    /**
12476     * Trigger the scrollbars to draw.
12477     * This method differs from awakenScrollBars() only in its default duration.
12478     * initialAwakenScrollBars() will show the scroll bars for longer than
12479     * usual to give the user more of a chance to notice them.
12480     *
12481     * @return true if the animation is played, false otherwise.
12482     */
12483    private boolean initialAwakenScrollBars() {
12484        return mScrollCache != null &&
12485                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
12486    }
12487
12488    /**
12489     * <p>
12490     * Trigger the scrollbars to draw. When invoked this method starts an
12491     * animation to fade the scrollbars out after a fixed delay. If a subclass
12492     * provides animated scrolling, the start delay should equal the duration of
12493     * the scrolling animation.
12494     * </p>
12495     *
12496     * <p>
12497     * The animation starts only if at least one of the scrollbars is enabled,
12498     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12499     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12500     * this method returns true, and false otherwise. If the animation is
12501     * started, this method calls {@link #invalidate()}; in that case the caller
12502     * should not call {@link #invalidate()}.
12503     * </p>
12504     *
12505     * <p>
12506     * This method should be invoked every time a subclass directly updates the
12507     * scroll parameters.
12508     * </p>
12509     *
12510     * @param startDelay the delay, in milliseconds, after which the animation
12511     *        should start; when the delay is 0, the animation starts
12512     *        immediately
12513     * @return true if the animation is played, false otherwise
12514     *
12515     * @see #scrollBy(int, int)
12516     * @see #scrollTo(int, int)
12517     * @see #isHorizontalScrollBarEnabled()
12518     * @see #isVerticalScrollBarEnabled()
12519     * @see #setHorizontalScrollBarEnabled(boolean)
12520     * @see #setVerticalScrollBarEnabled(boolean)
12521     */
12522    protected boolean awakenScrollBars(int startDelay) {
12523        return awakenScrollBars(startDelay, true);
12524    }
12525
12526    /**
12527     * <p>
12528     * Trigger the scrollbars to draw. When invoked this method starts an
12529     * animation to fade the scrollbars out after a fixed delay. If a subclass
12530     * provides animated scrolling, the start delay should equal the duration of
12531     * the scrolling animation.
12532     * </p>
12533     *
12534     * <p>
12535     * The animation starts only if at least one of the scrollbars is enabled,
12536     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12537     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12538     * this method returns true, and false otherwise. If the animation is
12539     * started, this method calls {@link #invalidate()} if the invalidate parameter
12540     * is set to true; in that case the caller
12541     * should not call {@link #invalidate()}.
12542     * </p>
12543     *
12544     * <p>
12545     * This method should be invoked every time a subclass directly updates the
12546     * scroll parameters.
12547     * </p>
12548     *
12549     * @param startDelay the delay, in milliseconds, after which the animation
12550     *        should start; when the delay is 0, the animation starts
12551     *        immediately
12552     *
12553     * @param invalidate Whether this method should call invalidate
12554     *
12555     * @return true if the animation is played, false otherwise
12556     *
12557     * @see #scrollBy(int, int)
12558     * @see #scrollTo(int, int)
12559     * @see #isHorizontalScrollBarEnabled()
12560     * @see #isVerticalScrollBarEnabled()
12561     * @see #setHorizontalScrollBarEnabled(boolean)
12562     * @see #setVerticalScrollBarEnabled(boolean)
12563     */
12564    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
12565        final ScrollabilityCache scrollCache = mScrollCache;
12566
12567        if (scrollCache == null || !scrollCache.fadeScrollBars) {
12568            return false;
12569        }
12570
12571        if (scrollCache.scrollBar == null) {
12572            scrollCache.scrollBar = new ScrollBarDrawable();
12573            scrollCache.scrollBar.setCallback(this);
12574            scrollCache.scrollBar.setState(getDrawableState());
12575        }
12576
12577        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
12578
12579            if (invalidate) {
12580                // Invalidate to show the scrollbars
12581                postInvalidateOnAnimation();
12582            }
12583
12584            if (scrollCache.state == ScrollabilityCache.OFF) {
12585                // FIXME: this is copied from WindowManagerService.
12586                // We should get this value from the system when it
12587                // is possible to do so.
12588                final int KEY_REPEAT_FIRST_DELAY = 750;
12589                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
12590            }
12591
12592            // Tell mScrollCache when we should start fading. This may
12593            // extend the fade start time if one was already scheduled
12594            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
12595            scrollCache.fadeStartTime = fadeStartTime;
12596            scrollCache.state = ScrollabilityCache.ON;
12597
12598            // Schedule our fader to run, unscheduling any old ones first
12599            if (mAttachInfo != null) {
12600                mAttachInfo.mHandler.removeCallbacks(scrollCache);
12601                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
12602            }
12603
12604            return true;
12605        }
12606
12607        return false;
12608    }
12609
12610    /**
12611     * Do not invalidate views which are not visible and which are not running an animation. They
12612     * will not get drawn and they should not set dirty flags as if they will be drawn
12613     */
12614    private boolean skipInvalidate() {
12615        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
12616                (!(mParent instanceof ViewGroup) ||
12617                        !((ViewGroup) mParent).isViewTransitioning(this));
12618    }
12619
12620    /**
12621     * Mark the area defined by dirty as needing to be drawn. If the view is
12622     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12623     * point in the future.
12624     * <p>
12625     * This must be called from a UI thread. To call from a non-UI thread, call
12626     * {@link #postInvalidate()}.
12627     * <p>
12628     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
12629     * {@code dirty}.
12630     *
12631     * @param dirty the rectangle representing the bounds of the dirty region
12632     */
12633    public void invalidate(Rect dirty) {
12634        final int scrollX = mScrollX;
12635        final int scrollY = mScrollY;
12636        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
12637                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
12638    }
12639
12640    /**
12641     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
12642     * coordinates of the dirty rect are relative to the view. If the view is
12643     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12644     * point in the future.
12645     * <p>
12646     * This must be called from a UI thread. To call from a non-UI thread, call
12647     * {@link #postInvalidate()}.
12648     *
12649     * @param l the left position of the dirty region
12650     * @param t the top position of the dirty region
12651     * @param r the right position of the dirty region
12652     * @param b the bottom position of the dirty region
12653     */
12654    public void invalidate(int l, int t, int r, int b) {
12655        final int scrollX = mScrollX;
12656        final int scrollY = mScrollY;
12657        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
12658    }
12659
12660    /**
12661     * Invalidate the whole view. If the view is visible,
12662     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
12663     * the future.
12664     * <p>
12665     * This must be called from a UI thread. To call from a non-UI thread, call
12666     * {@link #postInvalidate()}.
12667     */
12668    public void invalidate() {
12669        invalidate(true);
12670    }
12671
12672    /**
12673     * This is where the invalidate() work actually happens. A full invalidate()
12674     * causes the drawing cache to be invalidated, but this function can be
12675     * called with invalidateCache set to false to skip that invalidation step
12676     * for cases that do not need it (for example, a component that remains at
12677     * the same dimensions with the same content).
12678     *
12679     * @param invalidateCache Whether the drawing cache for this view should be
12680     *            invalidated as well. This is usually true for a full
12681     *            invalidate, but may be set to false if the View's contents or
12682     *            dimensions have not changed.
12683     */
12684    void invalidate(boolean invalidateCache) {
12685        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
12686    }
12687
12688    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
12689            boolean fullInvalidate) {
12690        if (mGhostView != null) {
12691            mGhostView.invalidate(true);
12692            return;
12693        }
12694
12695        if (skipInvalidate()) {
12696            return;
12697        }
12698
12699        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
12700                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
12701                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
12702                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
12703            if (fullInvalidate) {
12704                mLastIsOpaque = isOpaque();
12705                mPrivateFlags &= ~PFLAG_DRAWN;
12706            }
12707
12708            mPrivateFlags |= PFLAG_DIRTY;
12709
12710            if (invalidateCache) {
12711                mPrivateFlags |= PFLAG_INVALIDATED;
12712                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12713            }
12714
12715            // Propagate the damage rectangle to the parent view.
12716            final AttachInfo ai = mAttachInfo;
12717            final ViewParent p = mParent;
12718            if (p != null && ai != null && l < r && t < b) {
12719                final Rect damage = ai.mTmpInvalRect;
12720                damage.set(l, t, r, b);
12721                p.invalidateChild(this, damage);
12722            }
12723
12724            // Damage the entire projection receiver, if necessary.
12725            if (mBackground != null && mBackground.isProjected()) {
12726                final View receiver = getProjectionReceiver();
12727                if (receiver != null) {
12728                    receiver.damageInParent();
12729                }
12730            }
12731
12732            // Damage the entire IsolatedZVolume receiving this view's shadow.
12733            if (isHardwareAccelerated() && getZ() != 0) {
12734                damageShadowReceiver();
12735            }
12736        }
12737    }
12738
12739    /**
12740     * @return this view's projection receiver, or {@code null} if none exists
12741     */
12742    private View getProjectionReceiver() {
12743        ViewParent p = getParent();
12744        while (p != null && p instanceof View) {
12745            final View v = (View) p;
12746            if (v.isProjectionReceiver()) {
12747                return v;
12748            }
12749            p = p.getParent();
12750        }
12751
12752        return null;
12753    }
12754
12755    /**
12756     * @return whether the view is a projection receiver
12757     */
12758    private boolean isProjectionReceiver() {
12759        return mBackground != null;
12760    }
12761
12762    /**
12763     * Damage area of the screen that can be covered by this View's shadow.
12764     *
12765     * This method will guarantee that any changes to shadows cast by a View
12766     * are damaged on the screen for future redraw.
12767     */
12768    private void damageShadowReceiver() {
12769        final AttachInfo ai = mAttachInfo;
12770        if (ai != null) {
12771            ViewParent p = getParent();
12772            if (p != null && p instanceof ViewGroup) {
12773                final ViewGroup vg = (ViewGroup) p;
12774                vg.damageInParent();
12775            }
12776        }
12777    }
12778
12779    /**
12780     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
12781     * set any flags or handle all of the cases handled by the default invalidation methods.
12782     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
12783     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
12784     * walk up the hierarchy, transforming the dirty rect as necessary.
12785     *
12786     * The method also handles normal invalidation logic if display list properties are not
12787     * being used in this view. The invalidateParent and forceRedraw flags are used by that
12788     * backup approach, to handle these cases used in the various property-setting methods.
12789     *
12790     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
12791     * are not being used in this view
12792     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
12793     * list properties are not being used in this view
12794     */
12795    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
12796        if (!isHardwareAccelerated()
12797                || !mRenderNode.isValid()
12798                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
12799            if (invalidateParent) {
12800                invalidateParentCaches();
12801            }
12802            if (forceRedraw) {
12803                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12804            }
12805            invalidate(false);
12806        } else {
12807            damageInParent();
12808        }
12809        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
12810            damageShadowReceiver();
12811        }
12812    }
12813
12814    /**
12815     * Tells the parent view to damage this view's bounds.
12816     *
12817     * @hide
12818     */
12819    protected void damageInParent() {
12820        final AttachInfo ai = mAttachInfo;
12821        final ViewParent p = mParent;
12822        if (p != null && ai != null) {
12823            final Rect r = ai.mTmpInvalRect;
12824            r.set(0, 0, mRight - mLeft, mBottom - mTop);
12825            if (mParent instanceof ViewGroup) {
12826                ((ViewGroup) mParent).damageChild(this, r);
12827            } else {
12828                mParent.invalidateChild(this, r);
12829            }
12830        }
12831    }
12832
12833    /**
12834     * Utility method to transform a given Rect by the current matrix of this view.
12835     */
12836    void transformRect(final Rect rect) {
12837        if (!getMatrix().isIdentity()) {
12838            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12839            boundingRect.set(rect);
12840            getMatrix().mapRect(boundingRect);
12841            rect.set((int) Math.floor(boundingRect.left),
12842                    (int) Math.floor(boundingRect.top),
12843                    (int) Math.ceil(boundingRect.right),
12844                    (int) Math.ceil(boundingRect.bottom));
12845        }
12846    }
12847
12848    /**
12849     * Used to indicate that the parent of this view should clear its caches. This functionality
12850     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12851     * which is necessary when various parent-managed properties of the view change, such as
12852     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12853     * clears the parent caches and does not causes an invalidate event.
12854     *
12855     * @hide
12856     */
12857    protected void invalidateParentCaches() {
12858        if (mParent instanceof View) {
12859            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12860        }
12861    }
12862
12863    /**
12864     * Used to indicate that the parent of this view should be invalidated. This functionality
12865     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12866     * which is necessary when various parent-managed properties of the view change, such as
12867     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12868     * an invalidation event to the parent.
12869     *
12870     * @hide
12871     */
12872    protected void invalidateParentIfNeeded() {
12873        if (isHardwareAccelerated() && mParent instanceof View) {
12874            ((View) mParent).invalidate(true);
12875        }
12876    }
12877
12878    /**
12879     * @hide
12880     */
12881    protected void invalidateParentIfNeededAndWasQuickRejected() {
12882        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12883            // View was rejected last time it was drawn by its parent; this may have changed
12884            invalidateParentIfNeeded();
12885        }
12886    }
12887
12888    /**
12889     * Indicates whether this View is opaque. An opaque View guarantees that it will
12890     * draw all the pixels overlapping its bounds using a fully opaque color.
12891     *
12892     * Subclasses of View should override this method whenever possible to indicate
12893     * whether an instance is opaque. Opaque Views are treated in a special way by
12894     * the View hierarchy, possibly allowing it to perform optimizations during
12895     * invalidate/draw passes.
12896     *
12897     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12898     */
12899    @ViewDebug.ExportedProperty(category = "drawing")
12900    public boolean isOpaque() {
12901        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12902                getFinalAlpha() >= 1.0f;
12903    }
12904
12905    /**
12906     * @hide
12907     */
12908    protected void computeOpaqueFlags() {
12909        // Opaque if:
12910        //   - Has a background
12911        //   - Background is opaque
12912        //   - Doesn't have scrollbars or scrollbars overlay
12913
12914        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12915            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12916        } else {
12917            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12918        }
12919
12920        final int flags = mViewFlags;
12921        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12922                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12923                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12924            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12925        } else {
12926            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12927        }
12928    }
12929
12930    /**
12931     * @hide
12932     */
12933    protected boolean hasOpaqueScrollbars() {
12934        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12935    }
12936
12937    /**
12938     * @return A handler associated with the thread running the View. This
12939     * handler can be used to pump events in the UI events queue.
12940     */
12941    public Handler getHandler() {
12942        final AttachInfo attachInfo = mAttachInfo;
12943        if (attachInfo != null) {
12944            return attachInfo.mHandler;
12945        }
12946        return null;
12947    }
12948
12949    /**
12950     * Gets the view root associated with the View.
12951     * @return The view root, or null if none.
12952     * @hide
12953     */
12954    public ViewRootImpl getViewRootImpl() {
12955        if (mAttachInfo != null) {
12956            return mAttachInfo.mViewRootImpl;
12957        }
12958        return null;
12959    }
12960
12961    /**
12962     * @hide
12963     */
12964    public HardwareRenderer getHardwareRenderer() {
12965        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12966    }
12967
12968    /**
12969     * <p>Causes the Runnable to be added to the message queue.
12970     * The runnable will be run on the user interface thread.</p>
12971     *
12972     * @param action The Runnable that will be executed.
12973     *
12974     * @return Returns true if the Runnable was successfully placed in to the
12975     *         message queue.  Returns false on failure, usually because the
12976     *         looper processing the message queue is exiting.
12977     *
12978     * @see #postDelayed
12979     * @see #removeCallbacks
12980     */
12981    public boolean post(Runnable action) {
12982        final AttachInfo attachInfo = mAttachInfo;
12983        if (attachInfo != null) {
12984            return attachInfo.mHandler.post(action);
12985        }
12986        // Assume that post will succeed later
12987        ViewRootImpl.getRunQueue().post(action);
12988        return true;
12989    }
12990
12991    /**
12992     * <p>Causes the Runnable to be added to the message queue, to be run
12993     * after the specified amount of time elapses.
12994     * The runnable will be run on the user interface thread.</p>
12995     *
12996     * @param action The Runnable that will be executed.
12997     * @param delayMillis The delay (in milliseconds) until the Runnable
12998     *        will be executed.
12999     *
13000     * @return true if the Runnable was successfully placed in to the
13001     *         message queue.  Returns false on failure, usually because the
13002     *         looper processing the message queue is exiting.  Note that a
13003     *         result of true does not mean the Runnable will be processed --
13004     *         if the looper is quit before the delivery time of the message
13005     *         occurs then the message will be dropped.
13006     *
13007     * @see #post
13008     * @see #removeCallbacks
13009     */
13010    public boolean postDelayed(Runnable action, long delayMillis) {
13011        final AttachInfo attachInfo = mAttachInfo;
13012        if (attachInfo != null) {
13013            return attachInfo.mHandler.postDelayed(action, delayMillis);
13014        }
13015        // Assume that post will succeed later
13016        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
13017        return true;
13018    }
13019
13020    /**
13021     * <p>Causes the Runnable to execute on the next animation time step.
13022     * The runnable will be run on the user interface thread.</p>
13023     *
13024     * @param action The Runnable that will be executed.
13025     *
13026     * @see #postOnAnimationDelayed
13027     * @see #removeCallbacks
13028     */
13029    public void postOnAnimation(Runnable action) {
13030        final AttachInfo attachInfo = mAttachInfo;
13031        if (attachInfo != null) {
13032            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13033                    Choreographer.CALLBACK_ANIMATION, action, null);
13034        } else {
13035            // Assume that post will succeed later
13036            ViewRootImpl.getRunQueue().post(action);
13037        }
13038    }
13039
13040    /**
13041     * <p>Causes the Runnable to execute on the next animation time step,
13042     * after the specified amount of time elapses.
13043     * The runnable will be run on the user interface thread.</p>
13044     *
13045     * @param action The Runnable that will be executed.
13046     * @param delayMillis The delay (in milliseconds) until the Runnable
13047     *        will be executed.
13048     *
13049     * @see #postOnAnimation
13050     * @see #removeCallbacks
13051     */
13052    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13053        final AttachInfo attachInfo = mAttachInfo;
13054        if (attachInfo != null) {
13055            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13056                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13057        } else {
13058            // Assume that post will succeed later
13059            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
13060        }
13061    }
13062
13063    /**
13064     * <p>Removes the specified Runnable from the message queue.</p>
13065     *
13066     * @param action The Runnable to remove from the message handling queue
13067     *
13068     * @return true if this view could ask the Handler to remove the Runnable,
13069     *         false otherwise. When the returned value is true, the Runnable
13070     *         may or may not have been actually removed from the message queue
13071     *         (for instance, if the Runnable was not in the queue already.)
13072     *
13073     * @see #post
13074     * @see #postDelayed
13075     * @see #postOnAnimation
13076     * @see #postOnAnimationDelayed
13077     */
13078    public boolean removeCallbacks(Runnable action) {
13079        if (action != null) {
13080            final AttachInfo attachInfo = mAttachInfo;
13081            if (attachInfo != null) {
13082                attachInfo.mHandler.removeCallbacks(action);
13083                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13084                        Choreographer.CALLBACK_ANIMATION, action, null);
13085            }
13086            // Assume that post will succeed later
13087            ViewRootImpl.getRunQueue().removeCallbacks(action);
13088        }
13089        return true;
13090    }
13091
13092    /**
13093     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13094     * Use this to invalidate the View from a non-UI thread.</p>
13095     *
13096     * <p>This method can be invoked from outside of the UI thread
13097     * only when this View is attached to a window.</p>
13098     *
13099     * @see #invalidate()
13100     * @see #postInvalidateDelayed(long)
13101     */
13102    public void postInvalidate() {
13103        postInvalidateDelayed(0);
13104    }
13105
13106    /**
13107     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13108     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13109     *
13110     * <p>This method can be invoked from outside of the UI thread
13111     * only when this View is attached to a window.</p>
13112     *
13113     * @param left The left coordinate of the rectangle to invalidate.
13114     * @param top The top coordinate of the rectangle to invalidate.
13115     * @param right The right coordinate of the rectangle to invalidate.
13116     * @param bottom The bottom coordinate of the rectangle to invalidate.
13117     *
13118     * @see #invalidate(int, int, int, int)
13119     * @see #invalidate(Rect)
13120     * @see #postInvalidateDelayed(long, int, int, int, int)
13121     */
13122    public void postInvalidate(int left, int top, int right, int bottom) {
13123        postInvalidateDelayed(0, left, top, right, bottom);
13124    }
13125
13126    /**
13127     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13128     * loop. Waits for the specified amount of time.</p>
13129     *
13130     * <p>This method can be invoked from outside of the UI thread
13131     * only when this View is attached to a window.</p>
13132     *
13133     * @param delayMilliseconds the duration in milliseconds to delay the
13134     *         invalidation by
13135     *
13136     * @see #invalidate()
13137     * @see #postInvalidate()
13138     */
13139    public void postInvalidateDelayed(long delayMilliseconds) {
13140        // We try only with the AttachInfo because there's no point in invalidating
13141        // if we are not attached to our window
13142        final AttachInfo attachInfo = mAttachInfo;
13143        if (attachInfo != null) {
13144            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
13145        }
13146    }
13147
13148    /**
13149     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13150     * through the event loop. Waits for the specified amount of time.</p>
13151     *
13152     * <p>This method can be invoked from outside of the UI thread
13153     * only when this View is attached to a window.</p>
13154     *
13155     * @param delayMilliseconds the duration in milliseconds to delay the
13156     *         invalidation by
13157     * @param left The left coordinate of the rectangle to invalidate.
13158     * @param top The top coordinate of the rectangle to invalidate.
13159     * @param right The right coordinate of the rectangle to invalidate.
13160     * @param bottom The bottom coordinate of the rectangle to invalidate.
13161     *
13162     * @see #invalidate(int, int, int, int)
13163     * @see #invalidate(Rect)
13164     * @see #postInvalidate(int, int, int, int)
13165     */
13166    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
13167            int right, int bottom) {
13168
13169        // We try only with the AttachInfo because there's no point in invalidating
13170        // if we are not attached to our window
13171        final AttachInfo attachInfo = mAttachInfo;
13172        if (attachInfo != null) {
13173            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
13174            info.target = this;
13175            info.left = left;
13176            info.top = top;
13177            info.right = right;
13178            info.bottom = bottom;
13179
13180            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
13181        }
13182    }
13183
13184    /**
13185     * <p>Cause an invalidate to happen on the next animation time step, typically the
13186     * next display frame.</p>
13187     *
13188     * <p>This method can be invoked from outside of the UI thread
13189     * only when this View is attached to a window.</p>
13190     *
13191     * @see #invalidate()
13192     */
13193    public void postInvalidateOnAnimation() {
13194        // We try only with the AttachInfo because there's no point in invalidating
13195        // if we are not attached to our window
13196        final AttachInfo attachInfo = mAttachInfo;
13197        if (attachInfo != null) {
13198            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
13199        }
13200    }
13201
13202    /**
13203     * <p>Cause an invalidate of the specified area to happen on the next animation
13204     * time step, typically the next display frame.</p>
13205     *
13206     * <p>This method can be invoked from outside of the UI thread
13207     * only when this View is attached to a window.</p>
13208     *
13209     * @param left The left coordinate of the rectangle to invalidate.
13210     * @param top The top coordinate of the rectangle to invalidate.
13211     * @param right The right coordinate of the rectangle to invalidate.
13212     * @param bottom The bottom coordinate of the rectangle to invalidate.
13213     *
13214     * @see #invalidate(int, int, int, int)
13215     * @see #invalidate(Rect)
13216     */
13217    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
13218        // We try only with the AttachInfo because there's no point in invalidating
13219        // if we are not attached to our window
13220        final AttachInfo attachInfo = mAttachInfo;
13221        if (attachInfo != null) {
13222            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
13223            info.target = this;
13224            info.left = left;
13225            info.top = top;
13226            info.right = right;
13227            info.bottom = bottom;
13228
13229            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
13230        }
13231    }
13232
13233    /**
13234     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
13235     * This event is sent at most once every
13236     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
13237     */
13238    private void postSendViewScrolledAccessibilityEventCallback() {
13239        if (mSendViewScrolledAccessibilityEvent == null) {
13240            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
13241        }
13242        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
13243            mSendViewScrolledAccessibilityEvent.mIsPending = true;
13244            postDelayed(mSendViewScrolledAccessibilityEvent,
13245                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
13246        }
13247    }
13248
13249    /**
13250     * Called by a parent to request that a child update its values for mScrollX
13251     * and mScrollY if necessary. This will typically be done if the child is
13252     * animating a scroll using a {@link android.widget.Scroller Scroller}
13253     * object.
13254     */
13255    public void computeScroll() {
13256    }
13257
13258    /**
13259     * <p>Indicate whether the horizontal edges are faded when the view is
13260     * scrolled horizontally.</p>
13261     *
13262     * @return true if the horizontal edges should are faded on scroll, false
13263     *         otherwise
13264     *
13265     * @see #setHorizontalFadingEdgeEnabled(boolean)
13266     *
13267     * @attr ref android.R.styleable#View_requiresFadingEdge
13268     */
13269    public boolean isHorizontalFadingEdgeEnabled() {
13270        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
13271    }
13272
13273    /**
13274     * <p>Define whether the horizontal edges should be faded when this view
13275     * is scrolled horizontally.</p>
13276     *
13277     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
13278     *                                    be faded when the view is scrolled
13279     *                                    horizontally
13280     *
13281     * @see #isHorizontalFadingEdgeEnabled()
13282     *
13283     * @attr ref android.R.styleable#View_requiresFadingEdge
13284     */
13285    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
13286        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
13287            if (horizontalFadingEdgeEnabled) {
13288                initScrollCache();
13289            }
13290
13291            mViewFlags ^= FADING_EDGE_HORIZONTAL;
13292        }
13293    }
13294
13295    /**
13296     * <p>Indicate whether the vertical edges are faded when the view is
13297     * scrolled horizontally.</p>
13298     *
13299     * @return true if the vertical edges should are faded on scroll, false
13300     *         otherwise
13301     *
13302     * @see #setVerticalFadingEdgeEnabled(boolean)
13303     *
13304     * @attr ref android.R.styleable#View_requiresFadingEdge
13305     */
13306    public boolean isVerticalFadingEdgeEnabled() {
13307        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
13308    }
13309
13310    /**
13311     * <p>Define whether the vertical edges should be faded when this view
13312     * is scrolled vertically.</p>
13313     *
13314     * @param verticalFadingEdgeEnabled true if the vertical edges should
13315     *                                  be faded when the view is scrolled
13316     *                                  vertically
13317     *
13318     * @see #isVerticalFadingEdgeEnabled()
13319     *
13320     * @attr ref android.R.styleable#View_requiresFadingEdge
13321     */
13322    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
13323        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
13324            if (verticalFadingEdgeEnabled) {
13325                initScrollCache();
13326            }
13327
13328            mViewFlags ^= FADING_EDGE_VERTICAL;
13329        }
13330    }
13331
13332    /**
13333     * Returns the strength, or intensity, of the top faded edge. The strength is
13334     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13335     * returns 0.0 or 1.0 but no value in between.
13336     *
13337     * Subclasses should override this method to provide a smoother fade transition
13338     * when scrolling occurs.
13339     *
13340     * @return the intensity of the top fade as a float between 0.0f and 1.0f
13341     */
13342    protected float getTopFadingEdgeStrength() {
13343        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
13344    }
13345
13346    /**
13347     * Returns the strength, or intensity, of the bottom faded edge. The strength is
13348     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13349     * returns 0.0 or 1.0 but no value in between.
13350     *
13351     * Subclasses should override this method to provide a smoother fade transition
13352     * when scrolling occurs.
13353     *
13354     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
13355     */
13356    protected float getBottomFadingEdgeStrength() {
13357        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
13358                computeVerticalScrollRange() ? 1.0f : 0.0f;
13359    }
13360
13361    /**
13362     * Returns the strength, or intensity, of the left faded edge. The strength is
13363     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13364     * returns 0.0 or 1.0 but no value in between.
13365     *
13366     * Subclasses should override this method to provide a smoother fade transition
13367     * when scrolling occurs.
13368     *
13369     * @return the intensity of the left fade as a float between 0.0f and 1.0f
13370     */
13371    protected float getLeftFadingEdgeStrength() {
13372        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
13373    }
13374
13375    /**
13376     * Returns the strength, or intensity, of the right faded edge. The strength is
13377     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13378     * returns 0.0 or 1.0 but no value in between.
13379     *
13380     * Subclasses should override this method to provide a smoother fade transition
13381     * when scrolling occurs.
13382     *
13383     * @return the intensity of the right fade as a float between 0.0f and 1.0f
13384     */
13385    protected float getRightFadingEdgeStrength() {
13386        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
13387                computeHorizontalScrollRange() ? 1.0f : 0.0f;
13388    }
13389
13390    /**
13391     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
13392     * scrollbar is not drawn by default.</p>
13393     *
13394     * @return true if the horizontal scrollbar should be painted, false
13395     *         otherwise
13396     *
13397     * @see #setHorizontalScrollBarEnabled(boolean)
13398     */
13399    public boolean isHorizontalScrollBarEnabled() {
13400        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13401    }
13402
13403    /**
13404     * <p>Define whether the horizontal scrollbar should be drawn or not. The
13405     * scrollbar is not drawn by default.</p>
13406     *
13407     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
13408     *                                   be painted
13409     *
13410     * @see #isHorizontalScrollBarEnabled()
13411     */
13412    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
13413        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
13414            mViewFlags ^= SCROLLBARS_HORIZONTAL;
13415            computeOpaqueFlags();
13416            resolvePadding();
13417        }
13418    }
13419
13420    /**
13421     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
13422     * scrollbar is not drawn by default.</p>
13423     *
13424     * @return true if the vertical scrollbar should be painted, false
13425     *         otherwise
13426     *
13427     * @see #setVerticalScrollBarEnabled(boolean)
13428     */
13429    public boolean isVerticalScrollBarEnabled() {
13430        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
13431    }
13432
13433    /**
13434     * <p>Define whether the vertical scrollbar should be drawn or not. The
13435     * scrollbar is not drawn by default.</p>
13436     *
13437     * @param verticalScrollBarEnabled true if the vertical scrollbar should
13438     *                                 be painted
13439     *
13440     * @see #isVerticalScrollBarEnabled()
13441     */
13442    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
13443        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
13444            mViewFlags ^= SCROLLBARS_VERTICAL;
13445            computeOpaqueFlags();
13446            resolvePadding();
13447        }
13448    }
13449
13450    /**
13451     * @hide
13452     */
13453    protected void recomputePadding() {
13454        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13455    }
13456
13457    /**
13458     * Define whether scrollbars will fade when the view is not scrolling.
13459     *
13460     * @param fadeScrollbars whether to enable fading
13461     *
13462     * @attr ref android.R.styleable#View_fadeScrollbars
13463     */
13464    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
13465        initScrollCache();
13466        final ScrollabilityCache scrollabilityCache = mScrollCache;
13467        scrollabilityCache.fadeScrollBars = fadeScrollbars;
13468        if (fadeScrollbars) {
13469            scrollabilityCache.state = ScrollabilityCache.OFF;
13470        } else {
13471            scrollabilityCache.state = ScrollabilityCache.ON;
13472        }
13473    }
13474
13475    /**
13476     *
13477     * Returns true if scrollbars will fade when this view is not scrolling
13478     *
13479     * @return true if scrollbar fading is enabled
13480     *
13481     * @attr ref android.R.styleable#View_fadeScrollbars
13482     */
13483    public boolean isScrollbarFadingEnabled() {
13484        return mScrollCache != null && mScrollCache.fadeScrollBars;
13485    }
13486
13487    /**
13488     *
13489     * Returns the delay before scrollbars fade.
13490     *
13491     * @return the delay before scrollbars fade
13492     *
13493     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13494     */
13495    public int getScrollBarDefaultDelayBeforeFade() {
13496        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
13497                mScrollCache.scrollBarDefaultDelayBeforeFade;
13498    }
13499
13500    /**
13501     * Define the delay before scrollbars fade.
13502     *
13503     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
13504     *
13505     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13506     */
13507    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
13508        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
13509    }
13510
13511    /**
13512     *
13513     * Returns the scrollbar fade duration.
13514     *
13515     * @return the scrollbar fade duration
13516     *
13517     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13518     */
13519    public int getScrollBarFadeDuration() {
13520        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
13521                mScrollCache.scrollBarFadeDuration;
13522    }
13523
13524    /**
13525     * Define the scrollbar fade duration.
13526     *
13527     * @param scrollBarFadeDuration - the scrollbar fade duration
13528     *
13529     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13530     */
13531    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
13532        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
13533    }
13534
13535    /**
13536     *
13537     * Returns the scrollbar size.
13538     *
13539     * @return the scrollbar size
13540     *
13541     * @attr ref android.R.styleable#View_scrollbarSize
13542     */
13543    public int getScrollBarSize() {
13544        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
13545                mScrollCache.scrollBarSize;
13546    }
13547
13548    /**
13549     * Define the scrollbar size.
13550     *
13551     * @param scrollBarSize - the scrollbar size
13552     *
13553     * @attr ref android.R.styleable#View_scrollbarSize
13554     */
13555    public void setScrollBarSize(int scrollBarSize) {
13556        getScrollCache().scrollBarSize = scrollBarSize;
13557    }
13558
13559    /**
13560     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
13561     * inset. When inset, they add to the padding of the view. And the scrollbars
13562     * can be drawn inside the padding area or on the edge of the view. For example,
13563     * if a view has a background drawable and you want to draw the scrollbars
13564     * inside the padding specified by the drawable, you can use
13565     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
13566     * appear at the edge of the view, ignoring the padding, then you can use
13567     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
13568     * @param style the style of the scrollbars. Should be one of
13569     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
13570     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
13571     * @see #SCROLLBARS_INSIDE_OVERLAY
13572     * @see #SCROLLBARS_INSIDE_INSET
13573     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13574     * @see #SCROLLBARS_OUTSIDE_INSET
13575     *
13576     * @attr ref android.R.styleable#View_scrollbarStyle
13577     */
13578    public void setScrollBarStyle(@ScrollBarStyle int style) {
13579        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
13580            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
13581            computeOpaqueFlags();
13582            resolvePadding();
13583        }
13584    }
13585
13586    /**
13587     * <p>Returns the current scrollbar style.</p>
13588     * @return the current scrollbar style
13589     * @see #SCROLLBARS_INSIDE_OVERLAY
13590     * @see #SCROLLBARS_INSIDE_INSET
13591     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13592     * @see #SCROLLBARS_OUTSIDE_INSET
13593     *
13594     * @attr ref android.R.styleable#View_scrollbarStyle
13595     */
13596    @ViewDebug.ExportedProperty(mapping = {
13597            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
13598            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
13599            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
13600            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
13601    })
13602    @ScrollBarStyle
13603    public int getScrollBarStyle() {
13604        return mViewFlags & SCROLLBARS_STYLE_MASK;
13605    }
13606
13607    /**
13608     * <p>Compute the horizontal range that the horizontal scrollbar
13609     * represents.</p>
13610     *
13611     * <p>The range is expressed in arbitrary units that must be the same as the
13612     * units used by {@link #computeHorizontalScrollExtent()} and
13613     * {@link #computeHorizontalScrollOffset()}.</p>
13614     *
13615     * <p>The default range is the drawing width of this view.</p>
13616     *
13617     * @return the total horizontal range represented by the horizontal
13618     *         scrollbar
13619     *
13620     * @see #computeHorizontalScrollExtent()
13621     * @see #computeHorizontalScrollOffset()
13622     * @see android.widget.ScrollBarDrawable
13623     */
13624    protected int computeHorizontalScrollRange() {
13625        return getWidth();
13626    }
13627
13628    /**
13629     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
13630     * within the horizontal range. This value is used to compute the position
13631     * of the thumb within the scrollbar's track.</p>
13632     *
13633     * <p>The range is expressed in arbitrary units that must be the same as the
13634     * units used by {@link #computeHorizontalScrollRange()} and
13635     * {@link #computeHorizontalScrollExtent()}.</p>
13636     *
13637     * <p>The default offset is the scroll offset of this view.</p>
13638     *
13639     * @return the horizontal offset of the scrollbar's thumb
13640     *
13641     * @see #computeHorizontalScrollRange()
13642     * @see #computeHorizontalScrollExtent()
13643     * @see android.widget.ScrollBarDrawable
13644     */
13645    protected int computeHorizontalScrollOffset() {
13646        return mScrollX;
13647    }
13648
13649    /**
13650     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
13651     * within the horizontal range. This value is used to compute the length
13652     * of the thumb within the scrollbar's track.</p>
13653     *
13654     * <p>The range is expressed in arbitrary units that must be the same as the
13655     * units used by {@link #computeHorizontalScrollRange()} and
13656     * {@link #computeHorizontalScrollOffset()}.</p>
13657     *
13658     * <p>The default extent is the drawing width of this view.</p>
13659     *
13660     * @return the horizontal extent of the scrollbar's thumb
13661     *
13662     * @see #computeHorizontalScrollRange()
13663     * @see #computeHorizontalScrollOffset()
13664     * @see android.widget.ScrollBarDrawable
13665     */
13666    protected int computeHorizontalScrollExtent() {
13667        return getWidth();
13668    }
13669
13670    /**
13671     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
13672     *
13673     * <p>The range is expressed in arbitrary units that must be the same as the
13674     * units used by {@link #computeVerticalScrollExtent()} and
13675     * {@link #computeVerticalScrollOffset()}.</p>
13676     *
13677     * @return the total vertical range represented by the vertical scrollbar
13678     *
13679     * <p>The default range is the drawing height of this view.</p>
13680     *
13681     * @see #computeVerticalScrollExtent()
13682     * @see #computeVerticalScrollOffset()
13683     * @see android.widget.ScrollBarDrawable
13684     */
13685    protected int computeVerticalScrollRange() {
13686        return getHeight();
13687    }
13688
13689    /**
13690     * <p>Compute the vertical offset of the vertical scrollbar's thumb
13691     * within the horizontal range. This value is used to compute the position
13692     * of the thumb within the scrollbar's track.</p>
13693     *
13694     * <p>The range is expressed in arbitrary units that must be the same as the
13695     * units used by {@link #computeVerticalScrollRange()} and
13696     * {@link #computeVerticalScrollExtent()}.</p>
13697     *
13698     * <p>The default offset is the scroll offset of this view.</p>
13699     *
13700     * @return the vertical offset of the scrollbar's thumb
13701     *
13702     * @see #computeVerticalScrollRange()
13703     * @see #computeVerticalScrollExtent()
13704     * @see android.widget.ScrollBarDrawable
13705     */
13706    protected int computeVerticalScrollOffset() {
13707        return mScrollY;
13708    }
13709
13710    /**
13711     * <p>Compute the vertical extent of the vertical scrollbar's thumb
13712     * within the vertical range. This value is used to compute the length
13713     * of the thumb within the scrollbar's track.</p>
13714     *
13715     * <p>The range is expressed in arbitrary units that must be the same as the
13716     * units used by {@link #computeVerticalScrollRange()} and
13717     * {@link #computeVerticalScrollOffset()}.</p>
13718     *
13719     * <p>The default extent is the drawing height of this view.</p>
13720     *
13721     * @return the vertical extent of the scrollbar's thumb
13722     *
13723     * @see #computeVerticalScrollRange()
13724     * @see #computeVerticalScrollOffset()
13725     * @see android.widget.ScrollBarDrawable
13726     */
13727    protected int computeVerticalScrollExtent() {
13728        return getHeight();
13729    }
13730
13731    /**
13732     * Check if this view can be scrolled horizontally in a certain direction.
13733     *
13734     * @param direction Negative to check scrolling left, positive to check scrolling right.
13735     * @return true if this view can be scrolled in the specified direction, false otherwise.
13736     */
13737    public boolean canScrollHorizontally(int direction) {
13738        final int offset = computeHorizontalScrollOffset();
13739        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
13740        if (range == 0) return false;
13741        if (direction < 0) {
13742            return offset > 0;
13743        } else {
13744            return offset < range - 1;
13745        }
13746    }
13747
13748    /**
13749     * Check if this view can be scrolled vertically in a certain direction.
13750     *
13751     * @param direction Negative to check scrolling up, positive to check scrolling down.
13752     * @return true if this view can be scrolled in the specified direction, false otherwise.
13753     */
13754    public boolean canScrollVertically(int direction) {
13755        final int offset = computeVerticalScrollOffset();
13756        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
13757        if (range == 0) return false;
13758        if (direction < 0) {
13759            return offset > 0;
13760        } else {
13761            return offset < range - 1;
13762        }
13763    }
13764
13765    void getScrollIndicatorBounds(@NonNull Rect out) {
13766        out.left = mScrollX;
13767        out.right = mScrollX + mRight - mLeft;
13768        out.top = mScrollY;
13769        out.bottom = mScrollY + mBottom - mTop;
13770    }
13771
13772    private void onDrawScrollIndicators(Canvas c) {
13773        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
13774            // No scroll indicators enabled.
13775            return;
13776        }
13777
13778        final Drawable dr = mScrollIndicatorDrawable;
13779        if (dr == null) {
13780            // Scroll indicators aren't supported here.
13781            return;
13782        }
13783
13784        final int h = dr.getIntrinsicHeight();
13785        final int w = dr.getIntrinsicWidth();
13786        final Rect rect = mAttachInfo.mTmpInvalRect;
13787        getScrollIndicatorBounds(rect);
13788
13789        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
13790            final boolean canScrollUp = canScrollVertically(-1);
13791            if (canScrollUp) {
13792                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
13793                dr.draw(c);
13794            }
13795        }
13796
13797        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
13798            final boolean canScrollDown = canScrollVertically(1);
13799            if (canScrollDown) {
13800                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
13801                dr.draw(c);
13802            }
13803        }
13804
13805        final int leftRtl;
13806        final int rightRtl;
13807        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13808            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
13809            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
13810        } else {
13811            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
13812            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
13813        }
13814
13815        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
13816        if ((mPrivateFlags3 & leftMask) != 0) {
13817            final boolean canScrollLeft = canScrollHorizontally(-1);
13818            if (canScrollLeft) {
13819                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
13820                dr.draw(c);
13821            }
13822        }
13823
13824        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
13825        if ((mPrivateFlags3 & rightMask) != 0) {
13826            final boolean canScrollRight = canScrollHorizontally(1);
13827            if (canScrollRight) {
13828                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
13829                dr.draw(c);
13830            }
13831        }
13832    }
13833
13834    /**
13835     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
13836     * scrollbars are painted only if they have been awakened first.</p>
13837     *
13838     * @param canvas the canvas on which to draw the scrollbars
13839     *
13840     * @see #awakenScrollBars(int)
13841     */
13842    protected final void onDrawScrollBars(Canvas canvas) {
13843        // scrollbars are drawn only when the animation is running
13844        final ScrollabilityCache cache = mScrollCache;
13845        if (cache != null) {
13846
13847            int state = cache.state;
13848
13849            if (state == ScrollabilityCache.OFF) {
13850                return;
13851            }
13852
13853            boolean invalidate = false;
13854
13855            if (state == ScrollabilityCache.FADING) {
13856                // We're fading -- get our fade interpolation
13857                if (cache.interpolatorValues == null) {
13858                    cache.interpolatorValues = new float[1];
13859                }
13860
13861                float[] values = cache.interpolatorValues;
13862
13863                // Stops the animation if we're done
13864                if (cache.scrollBarInterpolator.timeToValues(values) ==
13865                        Interpolator.Result.FREEZE_END) {
13866                    cache.state = ScrollabilityCache.OFF;
13867                } else {
13868                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
13869                }
13870
13871                // This will make the scroll bars inval themselves after
13872                // drawing. We only want this when we're fading so that
13873                // we prevent excessive redraws
13874                invalidate = true;
13875            } else {
13876                // We're just on -- but we may have been fading before so
13877                // reset alpha
13878                cache.scrollBar.mutate().setAlpha(255);
13879            }
13880
13881
13882            final int viewFlags = mViewFlags;
13883
13884            final boolean drawHorizontalScrollBar =
13885                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13886            final boolean drawVerticalScrollBar =
13887                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
13888                && !isVerticalScrollBarHidden();
13889
13890            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
13891                final int width = mRight - mLeft;
13892                final int height = mBottom - mTop;
13893
13894                final ScrollBarDrawable scrollBar = cache.scrollBar;
13895
13896                final int scrollX = mScrollX;
13897                final int scrollY = mScrollY;
13898                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
13899
13900                int left;
13901                int top;
13902                int right;
13903                int bottom;
13904
13905                if (drawHorizontalScrollBar) {
13906                    int size = scrollBar.getSize(false);
13907                    if (size <= 0) {
13908                        size = cache.scrollBarSize;
13909                    }
13910
13911                    scrollBar.setParameters(computeHorizontalScrollRange(),
13912                                            computeHorizontalScrollOffset(),
13913                                            computeHorizontalScrollExtent(), false);
13914                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13915                            getVerticalScrollbarWidth() : 0;
13916                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13917                    left = scrollX + (mPaddingLeft & inside);
13918                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13919                    bottom = top + size;
13920                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13921                    if (invalidate) {
13922                        invalidate(left, top, right, bottom);
13923                    }
13924                }
13925
13926                if (drawVerticalScrollBar) {
13927                    int size = scrollBar.getSize(true);
13928                    if (size <= 0) {
13929                        size = cache.scrollBarSize;
13930                    }
13931
13932                    scrollBar.setParameters(computeVerticalScrollRange(),
13933                                            computeVerticalScrollOffset(),
13934                                            computeVerticalScrollExtent(), true);
13935                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13936                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13937                        verticalScrollbarPosition = isLayoutRtl() ?
13938                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13939                    }
13940                    switch (verticalScrollbarPosition) {
13941                        default:
13942                        case SCROLLBAR_POSITION_RIGHT:
13943                            left = scrollX + width - size - (mUserPaddingRight & inside);
13944                            break;
13945                        case SCROLLBAR_POSITION_LEFT:
13946                            left = scrollX + (mUserPaddingLeft & inside);
13947                            break;
13948                    }
13949                    top = scrollY + (mPaddingTop & inside);
13950                    right = left + size;
13951                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13952                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13953                    if (invalidate) {
13954                        invalidate(left, top, right, bottom);
13955                    }
13956                }
13957            }
13958        }
13959    }
13960
13961    /**
13962     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13963     * FastScroller is visible.
13964     * @return whether to temporarily hide the vertical scrollbar
13965     * @hide
13966     */
13967    protected boolean isVerticalScrollBarHidden() {
13968        return false;
13969    }
13970
13971    /**
13972     * <p>Draw the horizontal scrollbar if
13973     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13974     *
13975     * @param canvas the canvas on which to draw the scrollbar
13976     * @param scrollBar the scrollbar's drawable
13977     *
13978     * @see #isHorizontalScrollBarEnabled()
13979     * @see #computeHorizontalScrollRange()
13980     * @see #computeHorizontalScrollExtent()
13981     * @see #computeHorizontalScrollOffset()
13982     * @see android.widget.ScrollBarDrawable
13983     * @hide
13984     */
13985    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13986            int l, int t, int r, int b) {
13987        scrollBar.setBounds(l, t, r, b);
13988        scrollBar.draw(canvas);
13989    }
13990
13991    /**
13992     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13993     * returns true.</p>
13994     *
13995     * @param canvas the canvas on which to draw the scrollbar
13996     * @param scrollBar the scrollbar's drawable
13997     *
13998     * @see #isVerticalScrollBarEnabled()
13999     * @see #computeVerticalScrollRange()
14000     * @see #computeVerticalScrollExtent()
14001     * @see #computeVerticalScrollOffset()
14002     * @see android.widget.ScrollBarDrawable
14003     * @hide
14004     */
14005    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14006            int l, int t, int r, int b) {
14007        scrollBar.setBounds(l, t, r, b);
14008        scrollBar.draw(canvas);
14009    }
14010
14011    /**
14012     * Implement this to do your drawing.
14013     *
14014     * @param canvas the canvas on which the background will be drawn
14015     */
14016    protected void onDraw(Canvas canvas) {
14017    }
14018
14019    /*
14020     * Caller is responsible for calling requestLayout if necessary.
14021     * (This allows addViewInLayout to not request a new layout.)
14022     */
14023    void assignParent(ViewParent parent) {
14024        if (mParent == null) {
14025            mParent = parent;
14026        } else if (parent == null) {
14027            mParent = null;
14028        } else {
14029            throw new RuntimeException("view " + this + " being added, but"
14030                    + " it already has a parent");
14031        }
14032    }
14033
14034    /**
14035     * This is called when the view is attached to a window.  At this point it
14036     * has a Surface and will start drawing.  Note that this function is
14037     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14038     * however it may be called any time before the first onDraw -- including
14039     * before or after {@link #onMeasure(int, int)}.
14040     *
14041     * @see #onDetachedFromWindow()
14042     */
14043    @CallSuper
14044    protected void onAttachedToWindow() {
14045        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14046            mParent.requestTransparentRegion(this);
14047        }
14048
14049        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14050
14051        jumpDrawablesToCurrentState();
14052
14053        resetSubtreeAccessibilityStateChanged();
14054
14055        // rebuild, since Outline not maintained while View is detached
14056        rebuildOutline();
14057
14058        if (isFocused()) {
14059            InputMethodManager imm = InputMethodManager.peekInstance();
14060            if (imm != null) {
14061                imm.focusIn(this);
14062            }
14063        }
14064    }
14065
14066    /**
14067     * Resolve all RTL related properties.
14068     *
14069     * @return true if resolution of RTL properties has been done
14070     *
14071     * @hide
14072     */
14073    public boolean resolveRtlPropertiesIfNeeded() {
14074        if (!needRtlPropertiesResolution()) return false;
14075
14076        // Order is important here: LayoutDirection MUST be resolved first
14077        if (!isLayoutDirectionResolved()) {
14078            resolveLayoutDirection();
14079            resolveLayoutParams();
14080        }
14081        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14082        if (!isTextDirectionResolved()) {
14083            resolveTextDirection();
14084        }
14085        if (!isTextAlignmentResolved()) {
14086            resolveTextAlignment();
14087        }
14088        // Should resolve Drawables before Padding because we need the layout direction of the
14089        // Drawable to correctly resolve Padding.
14090        if (!areDrawablesResolved()) {
14091            resolveDrawables();
14092        }
14093        if (!isPaddingResolved()) {
14094            resolvePadding();
14095        }
14096        onRtlPropertiesChanged(getLayoutDirection());
14097        return true;
14098    }
14099
14100    /**
14101     * Reset resolution of all RTL related properties.
14102     *
14103     * @hide
14104     */
14105    public void resetRtlProperties() {
14106        resetResolvedLayoutDirection();
14107        resetResolvedTextDirection();
14108        resetResolvedTextAlignment();
14109        resetResolvedPadding();
14110        resetResolvedDrawables();
14111    }
14112
14113    /**
14114     * @see #onScreenStateChanged(int)
14115     */
14116    void dispatchScreenStateChanged(int screenState) {
14117        onScreenStateChanged(screenState);
14118    }
14119
14120    /**
14121     * This method is called whenever the state of the screen this view is
14122     * attached to changes. A state change will usually occurs when the screen
14123     * turns on or off (whether it happens automatically or the user does it
14124     * manually.)
14125     *
14126     * @param screenState The new state of the screen. Can be either
14127     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14128     */
14129    public void onScreenStateChanged(int screenState) {
14130    }
14131
14132    /**
14133     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
14134     */
14135    private boolean hasRtlSupport() {
14136        return mContext.getApplicationInfo().hasRtlSupport();
14137    }
14138
14139    /**
14140     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
14141     * RTL not supported)
14142     */
14143    private boolean isRtlCompatibilityMode() {
14144        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
14145        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
14146    }
14147
14148    /**
14149     * @return true if RTL properties need resolution.
14150     *
14151     */
14152    private boolean needRtlPropertiesResolution() {
14153        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
14154    }
14155
14156    /**
14157     * Called when any RTL property (layout direction or text direction or text alignment) has
14158     * been changed.
14159     *
14160     * Subclasses need to override this method to take care of cached information that depends on the
14161     * resolved layout direction, or to inform child views that inherit their layout direction.
14162     *
14163     * The default implementation does nothing.
14164     *
14165     * @param layoutDirection the direction of the layout
14166     *
14167     * @see #LAYOUT_DIRECTION_LTR
14168     * @see #LAYOUT_DIRECTION_RTL
14169     */
14170    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
14171    }
14172
14173    /**
14174     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
14175     * that the parent directionality can and will be resolved before its children.
14176     *
14177     * @return true if resolution has been done, false otherwise.
14178     *
14179     * @hide
14180     */
14181    public boolean resolveLayoutDirection() {
14182        // Clear any previous layout direction resolution
14183        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
14184
14185        if (hasRtlSupport()) {
14186            // Set resolved depending on layout direction
14187            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
14188                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
14189                case LAYOUT_DIRECTION_INHERIT:
14190                    // We cannot resolve yet. LTR is by default and let the resolution happen again
14191                    // later to get the correct resolved value
14192                    if (!canResolveLayoutDirection()) return false;
14193
14194                    // Parent has not yet resolved, LTR is still the default
14195                    try {
14196                        if (!mParent.isLayoutDirectionResolved()) return false;
14197
14198                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14199                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
14200                        }
14201                    } catch (AbstractMethodError e) {
14202                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
14203                                " does not fully implement ViewParent", e);
14204                    }
14205                    break;
14206                case LAYOUT_DIRECTION_RTL:
14207                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
14208                    break;
14209                case LAYOUT_DIRECTION_LOCALE:
14210                    if((LAYOUT_DIRECTION_RTL ==
14211                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
14212                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
14213                    }
14214                    break;
14215                default:
14216                    // Nothing to do, LTR by default
14217            }
14218        }
14219
14220        // Set to resolved
14221        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
14222        return true;
14223    }
14224
14225    /**
14226     * Check if layout direction resolution can be done.
14227     *
14228     * @return true if layout direction resolution can be done otherwise return false.
14229     */
14230    public boolean canResolveLayoutDirection() {
14231        switch (getRawLayoutDirection()) {
14232            case LAYOUT_DIRECTION_INHERIT:
14233                if (mParent != null) {
14234                    try {
14235                        return mParent.canResolveLayoutDirection();
14236                    } catch (AbstractMethodError e) {
14237                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
14238                                " does not fully implement ViewParent", e);
14239                    }
14240                }
14241                return false;
14242
14243            default:
14244                return true;
14245        }
14246    }
14247
14248    /**
14249     * Reset the resolved layout direction. Layout direction will be resolved during a call to
14250     * {@link #onMeasure(int, int)}.
14251     *
14252     * @hide
14253     */
14254    public void resetResolvedLayoutDirection() {
14255        // Reset the current resolved bits
14256        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
14257    }
14258
14259    /**
14260     * @return true if the layout direction is inherited.
14261     *
14262     * @hide
14263     */
14264    public boolean isLayoutDirectionInherited() {
14265        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
14266    }
14267
14268    /**
14269     * @return true if layout direction has been resolved.
14270     */
14271    public boolean isLayoutDirectionResolved() {
14272        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
14273    }
14274
14275    /**
14276     * Return if padding has been resolved
14277     *
14278     * @hide
14279     */
14280    boolean isPaddingResolved() {
14281        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
14282    }
14283
14284    /**
14285     * Resolves padding depending on layout direction, if applicable, and
14286     * recomputes internal padding values to adjust for scroll bars.
14287     *
14288     * @hide
14289     */
14290    public void resolvePadding() {
14291        final int resolvedLayoutDirection = getLayoutDirection();
14292
14293        if (!isRtlCompatibilityMode()) {
14294            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
14295            // If start / end padding are defined, they will be resolved (hence overriding) to
14296            // left / right or right / left depending on the resolved layout direction.
14297            // If start / end padding are not defined, use the left / right ones.
14298            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
14299                Rect padding = sThreadLocal.get();
14300                if (padding == null) {
14301                    padding = new Rect();
14302                    sThreadLocal.set(padding);
14303                }
14304                mBackground.getPadding(padding);
14305                if (!mLeftPaddingDefined) {
14306                    mUserPaddingLeftInitial = padding.left;
14307                }
14308                if (!mRightPaddingDefined) {
14309                    mUserPaddingRightInitial = padding.right;
14310                }
14311            }
14312            switch (resolvedLayoutDirection) {
14313                case LAYOUT_DIRECTION_RTL:
14314                    if (mUserPaddingStart != UNDEFINED_PADDING) {
14315                        mUserPaddingRight = mUserPaddingStart;
14316                    } else {
14317                        mUserPaddingRight = mUserPaddingRightInitial;
14318                    }
14319                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
14320                        mUserPaddingLeft = mUserPaddingEnd;
14321                    } else {
14322                        mUserPaddingLeft = mUserPaddingLeftInitial;
14323                    }
14324                    break;
14325                case LAYOUT_DIRECTION_LTR:
14326                default:
14327                    if (mUserPaddingStart != UNDEFINED_PADDING) {
14328                        mUserPaddingLeft = mUserPaddingStart;
14329                    } else {
14330                        mUserPaddingLeft = mUserPaddingLeftInitial;
14331                    }
14332                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
14333                        mUserPaddingRight = mUserPaddingEnd;
14334                    } else {
14335                        mUserPaddingRight = mUserPaddingRightInitial;
14336                    }
14337            }
14338
14339            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
14340        }
14341
14342        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14343        onRtlPropertiesChanged(resolvedLayoutDirection);
14344
14345        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
14346    }
14347
14348    /**
14349     * Reset the resolved layout direction.
14350     *
14351     * @hide
14352     */
14353    public void resetResolvedPadding() {
14354        resetResolvedPaddingInternal();
14355    }
14356
14357    /**
14358     * Used when we only want to reset *this* view's padding and not trigger overrides
14359     * in ViewGroup that reset children too.
14360     */
14361    void resetResolvedPaddingInternal() {
14362        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
14363    }
14364
14365    /**
14366     * This is called when the view is detached from a window.  At this point it
14367     * no longer has a surface for drawing.
14368     *
14369     * @see #onAttachedToWindow()
14370     */
14371    @CallSuper
14372    protected void onDetachedFromWindow() {
14373    }
14374
14375    /**
14376     * This is a framework-internal mirror of onDetachedFromWindow() that's called
14377     * after onDetachedFromWindow().
14378     *
14379     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
14380     * The super method should be called at the end of the overridden method to ensure
14381     * subclasses are destroyed first
14382     *
14383     * @hide
14384     */
14385    @CallSuper
14386    protected void onDetachedFromWindowInternal() {
14387        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
14388        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14389
14390        removeUnsetPressCallback();
14391        removeLongPressCallback();
14392        removePerformClickCallback();
14393        removeSendViewScrolledAccessibilityEventCallback();
14394        stopNestedScroll();
14395
14396        // Anything that started animating right before detach should already
14397        // be in its final state when re-attached.
14398        jumpDrawablesToCurrentState();
14399
14400        destroyDrawingCache();
14401
14402        cleanupDraw();
14403        mCurrentAnimation = null;
14404    }
14405
14406    private void cleanupDraw() {
14407        resetDisplayList();
14408        if (mAttachInfo != null) {
14409            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
14410        }
14411    }
14412
14413    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
14414    }
14415
14416    /**
14417     * @return The number of times this view has been attached to a window
14418     */
14419    protected int getWindowAttachCount() {
14420        return mWindowAttachCount;
14421    }
14422
14423    /**
14424     * Retrieve a unique token identifying the window this view is attached to.
14425     * @return Return the window's token for use in
14426     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
14427     */
14428    public IBinder getWindowToken() {
14429        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
14430    }
14431
14432    /**
14433     * Retrieve the {@link WindowId} for the window this view is
14434     * currently attached to.
14435     */
14436    public WindowId getWindowId() {
14437        if (mAttachInfo == null) {
14438            return null;
14439        }
14440        if (mAttachInfo.mWindowId == null) {
14441            try {
14442                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
14443                        mAttachInfo.mWindowToken);
14444                mAttachInfo.mWindowId = new WindowId(
14445                        mAttachInfo.mIWindowId);
14446            } catch (RemoteException e) {
14447            }
14448        }
14449        return mAttachInfo.mWindowId;
14450    }
14451
14452    /**
14453     * Retrieve a unique token identifying the top-level "real" window of
14454     * the window that this view is attached to.  That is, this is like
14455     * {@link #getWindowToken}, except if the window this view in is a panel
14456     * window (attached to another containing window), then the token of
14457     * the containing window is returned instead.
14458     *
14459     * @return Returns the associated window token, either
14460     * {@link #getWindowToken()} or the containing window's token.
14461     */
14462    public IBinder getApplicationWindowToken() {
14463        AttachInfo ai = mAttachInfo;
14464        if (ai != null) {
14465            IBinder appWindowToken = ai.mPanelParentWindowToken;
14466            if (appWindowToken == null) {
14467                appWindowToken = ai.mWindowToken;
14468            }
14469            return appWindowToken;
14470        }
14471        return null;
14472    }
14473
14474    /**
14475     * Gets the logical display to which the view's window has been attached.
14476     *
14477     * @return The logical display, or null if the view is not currently attached to a window.
14478     */
14479    public Display getDisplay() {
14480        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
14481    }
14482
14483    /**
14484     * Retrieve private session object this view hierarchy is using to
14485     * communicate with the window manager.
14486     * @return the session object to communicate with the window manager
14487     */
14488    /*package*/ IWindowSession getWindowSession() {
14489        return mAttachInfo != null ? mAttachInfo.mSession : null;
14490    }
14491
14492    /**
14493     * Return the visibility value of the least visible component passed.
14494     */
14495    int combineVisibility(int vis1, int vis2) {
14496        // This works because VISIBLE < INVISIBLE < GONE.
14497        return Math.max(vis1, vis2);
14498    }
14499
14500    /**
14501     * @param info the {@link android.view.View.AttachInfo} to associated with
14502     *        this view
14503     */
14504    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
14505        //System.out.println("Attached! " + this);
14506        mAttachInfo = info;
14507        if (mOverlay != null) {
14508            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
14509        }
14510        mWindowAttachCount++;
14511        // We will need to evaluate the drawable state at least once.
14512        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14513        if (mFloatingTreeObserver != null) {
14514            info.mTreeObserver.merge(mFloatingTreeObserver);
14515            mFloatingTreeObserver = null;
14516        }
14517        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
14518            mAttachInfo.mScrollContainers.add(this);
14519            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
14520        }
14521        performCollectViewAttributes(mAttachInfo, visibility);
14522        onAttachedToWindow();
14523
14524        ListenerInfo li = mListenerInfo;
14525        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14526                li != null ? li.mOnAttachStateChangeListeners : null;
14527        if (listeners != null && listeners.size() > 0) {
14528            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14529            // perform the dispatching. The iterator is a safe guard against listeners that
14530            // could mutate the list by calling the various add/remove methods. This prevents
14531            // the array from being modified while we iterate it.
14532            for (OnAttachStateChangeListener listener : listeners) {
14533                listener.onViewAttachedToWindow(this);
14534            }
14535        }
14536
14537        int vis = info.mWindowVisibility;
14538        if (vis != GONE) {
14539            onWindowVisibilityChanged(vis);
14540        }
14541
14542        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
14543        // As all views in the subtree will already receive dispatchAttachedToWindow
14544        // traversing the subtree again here is not desired.
14545        onVisibilityChanged(this, visibility);
14546
14547        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
14548            // If nobody has evaluated the drawable state yet, then do it now.
14549            refreshDrawableState();
14550        }
14551        needGlobalAttributesUpdate(false);
14552    }
14553
14554    void dispatchDetachedFromWindow() {
14555        AttachInfo info = mAttachInfo;
14556        if (info != null) {
14557            int vis = info.mWindowVisibility;
14558            if (vis != GONE) {
14559                onWindowVisibilityChanged(GONE);
14560            }
14561        }
14562
14563        onDetachedFromWindow();
14564        onDetachedFromWindowInternal();
14565
14566        InputMethodManager imm = InputMethodManager.peekInstance();
14567        if (imm != null) {
14568            imm.onViewDetachedFromWindow(this);
14569        }
14570
14571        ListenerInfo li = mListenerInfo;
14572        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14573                li != null ? li.mOnAttachStateChangeListeners : null;
14574        if (listeners != null && listeners.size() > 0) {
14575            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14576            // perform the dispatching. The iterator is a safe guard against listeners that
14577            // could mutate the list by calling the various add/remove methods. This prevents
14578            // the array from being modified while we iterate it.
14579            for (OnAttachStateChangeListener listener : listeners) {
14580                listener.onViewDetachedFromWindow(this);
14581            }
14582        }
14583
14584        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
14585            mAttachInfo.mScrollContainers.remove(this);
14586            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
14587        }
14588
14589        mAttachInfo = null;
14590        if (mOverlay != null) {
14591            mOverlay.getOverlayView().dispatchDetachedFromWindow();
14592        }
14593    }
14594
14595    /**
14596     * Cancel any deferred high-level input events that were previously posted to the event queue.
14597     *
14598     * <p>Many views post high-level events such as click handlers to the event queue
14599     * to run deferred in order to preserve a desired user experience - clearing visible
14600     * pressed states before executing, etc. This method will abort any events of this nature
14601     * that are currently in flight.</p>
14602     *
14603     * <p>Custom views that generate their own high-level deferred input events should override
14604     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
14605     *
14606     * <p>This will also cancel pending input events for any child views.</p>
14607     *
14608     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
14609     * This will not impact newer events posted after this call that may occur as a result of
14610     * lower-level input events still waiting in the queue. If you are trying to prevent
14611     * double-submitted  events for the duration of some sort of asynchronous transaction
14612     * you should also take other steps to protect against unexpected double inputs e.g. calling
14613     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
14614     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
14615     */
14616    public final void cancelPendingInputEvents() {
14617        dispatchCancelPendingInputEvents();
14618    }
14619
14620    /**
14621     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
14622     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
14623     */
14624    void dispatchCancelPendingInputEvents() {
14625        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
14626        onCancelPendingInputEvents();
14627        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
14628            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
14629                    " did not call through to super.onCancelPendingInputEvents()");
14630        }
14631    }
14632
14633    /**
14634     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
14635     * a parent view.
14636     *
14637     * <p>This method is responsible for removing any pending high-level input events that were
14638     * posted to the event queue to run later. Custom view classes that post their own deferred
14639     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
14640     * {@link android.os.Handler} should override this method, call
14641     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
14642     * </p>
14643     */
14644    public void onCancelPendingInputEvents() {
14645        removePerformClickCallback();
14646        cancelLongPress();
14647        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
14648    }
14649
14650    /**
14651     * Store this view hierarchy's frozen state into the given container.
14652     *
14653     * @param container The SparseArray in which to save the view's state.
14654     *
14655     * @see #restoreHierarchyState(android.util.SparseArray)
14656     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14657     * @see #onSaveInstanceState()
14658     */
14659    public void saveHierarchyState(SparseArray<Parcelable> container) {
14660        dispatchSaveInstanceState(container);
14661    }
14662
14663    /**
14664     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
14665     * this view and its children. May be overridden to modify how freezing happens to a
14666     * view's children; for example, some views may want to not store state for their children.
14667     *
14668     * @param container The SparseArray in which to save the view's state.
14669     *
14670     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14671     * @see #saveHierarchyState(android.util.SparseArray)
14672     * @see #onSaveInstanceState()
14673     */
14674    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
14675        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
14676            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14677            Parcelable state = onSaveInstanceState();
14678            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14679                throw new IllegalStateException(
14680                        "Derived class did not call super.onSaveInstanceState()");
14681            }
14682            if (state != null) {
14683                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
14684                // + ": " + state);
14685                container.put(mID, state);
14686            }
14687        }
14688    }
14689
14690    /**
14691     * Hook allowing a view to generate a representation of its internal state
14692     * that can later be used to create a new instance with that same state.
14693     * This state should only contain information that is not persistent or can
14694     * not be reconstructed later. For example, you will never store your
14695     * current position on screen because that will be computed again when a
14696     * new instance of the view is placed in its view hierarchy.
14697     * <p>
14698     * Some examples of things you may store here: the current cursor position
14699     * in a text view (but usually not the text itself since that is stored in a
14700     * content provider or other persistent storage), the currently selected
14701     * item in a list view.
14702     *
14703     * @return Returns a Parcelable object containing the view's current dynamic
14704     *         state, or null if there is nothing interesting to save. The
14705     *         default implementation returns null.
14706     * @see #onRestoreInstanceState(android.os.Parcelable)
14707     * @see #saveHierarchyState(android.util.SparseArray)
14708     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14709     * @see #setSaveEnabled(boolean)
14710     */
14711    @CallSuper
14712    protected Parcelable onSaveInstanceState() {
14713        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14714        if (mStartActivityRequestWho != null) {
14715            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
14716            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
14717            return state;
14718        }
14719        return BaseSavedState.EMPTY_STATE;
14720    }
14721
14722    /**
14723     * Restore this view hierarchy's frozen state from the given container.
14724     *
14725     * @param container The SparseArray which holds previously frozen states.
14726     *
14727     * @see #saveHierarchyState(android.util.SparseArray)
14728     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14729     * @see #onRestoreInstanceState(android.os.Parcelable)
14730     */
14731    public void restoreHierarchyState(SparseArray<Parcelable> container) {
14732        dispatchRestoreInstanceState(container);
14733    }
14734
14735    /**
14736     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
14737     * state for this view and its children. May be overridden to modify how restoring
14738     * happens to a view's children; for example, some views may want to not store state
14739     * for their children.
14740     *
14741     * @param container The SparseArray which holds previously saved state.
14742     *
14743     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14744     * @see #restoreHierarchyState(android.util.SparseArray)
14745     * @see #onRestoreInstanceState(android.os.Parcelable)
14746     */
14747    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
14748        if (mID != NO_ID) {
14749            Parcelable state = container.get(mID);
14750            if (state != null) {
14751                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
14752                // + ": " + state);
14753                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14754                onRestoreInstanceState(state);
14755                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14756                    throw new IllegalStateException(
14757                            "Derived class did not call super.onRestoreInstanceState()");
14758                }
14759            }
14760        }
14761    }
14762
14763    /**
14764     * Hook allowing a view to re-apply a representation of its internal state that had previously
14765     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
14766     * null state.
14767     *
14768     * @param state The frozen state that had previously been returned by
14769     *        {@link #onSaveInstanceState}.
14770     *
14771     * @see #onSaveInstanceState()
14772     * @see #restoreHierarchyState(android.util.SparseArray)
14773     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14774     */
14775    @CallSuper
14776    protected void onRestoreInstanceState(Parcelable state) {
14777        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14778        if (state != null && !(state instanceof AbsSavedState)) {
14779            throw new IllegalArgumentException("Wrong state class, expecting View State but "
14780                    + "received " + state.getClass().toString() + " instead. This usually happens "
14781                    + "when two views of different type have the same id in the same hierarchy. "
14782                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
14783                    + "other views do not use the same id.");
14784        }
14785        if (state != null && state instanceof BaseSavedState) {
14786            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
14787        }
14788    }
14789
14790    /**
14791     * <p>Return the time at which the drawing of the view hierarchy started.</p>
14792     *
14793     * @return the drawing start time in milliseconds
14794     */
14795    public long getDrawingTime() {
14796        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
14797    }
14798
14799    /**
14800     * <p>Enables or disables the duplication of the parent's state into this view. When
14801     * duplication is enabled, this view gets its drawable state from its parent rather
14802     * than from its own internal properties.</p>
14803     *
14804     * <p>Note: in the current implementation, setting this property to true after the
14805     * view was added to a ViewGroup might have no effect at all. This property should
14806     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
14807     *
14808     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
14809     * property is enabled, an exception will be thrown.</p>
14810     *
14811     * <p>Note: if the child view uses and updates additional states which are unknown to the
14812     * parent, these states should not be affected by this method.</p>
14813     *
14814     * @param enabled True to enable duplication of the parent's drawable state, false
14815     *                to disable it.
14816     *
14817     * @see #getDrawableState()
14818     * @see #isDuplicateParentStateEnabled()
14819     */
14820    public void setDuplicateParentStateEnabled(boolean enabled) {
14821        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
14822    }
14823
14824    /**
14825     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
14826     *
14827     * @return True if this view's drawable state is duplicated from the parent,
14828     *         false otherwise
14829     *
14830     * @see #getDrawableState()
14831     * @see #setDuplicateParentStateEnabled(boolean)
14832     */
14833    public boolean isDuplicateParentStateEnabled() {
14834        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
14835    }
14836
14837    /**
14838     * <p>Specifies the type of layer backing this view. The layer can be
14839     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14840     * {@link #LAYER_TYPE_HARDWARE}.</p>
14841     *
14842     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14843     * instance that controls how the layer is composed on screen. The following
14844     * properties of the paint are taken into account when composing the layer:</p>
14845     * <ul>
14846     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14847     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14848     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14849     * </ul>
14850     *
14851     * <p>If this view has an alpha value set to < 1.0 by calling
14852     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
14853     * by this view's alpha value.</p>
14854     *
14855     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
14856     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
14857     * for more information on when and how to use layers.</p>
14858     *
14859     * @param layerType The type of layer to use with this view, must be one of
14860     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14861     *        {@link #LAYER_TYPE_HARDWARE}
14862     * @param paint The paint used to compose the layer. This argument is optional
14863     *        and can be null. It is ignored when the layer type is
14864     *        {@link #LAYER_TYPE_NONE}
14865     *
14866     * @see #getLayerType()
14867     * @see #LAYER_TYPE_NONE
14868     * @see #LAYER_TYPE_SOFTWARE
14869     * @see #LAYER_TYPE_HARDWARE
14870     * @see #setAlpha(float)
14871     *
14872     * @attr ref android.R.styleable#View_layerType
14873     */
14874    public void setLayerType(int layerType, Paint paint) {
14875        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
14876            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
14877                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
14878        }
14879
14880        boolean typeChanged = mRenderNode.setLayerType(layerType);
14881
14882        if (!typeChanged) {
14883            setLayerPaint(paint);
14884            return;
14885        }
14886
14887        // Destroy any previous software drawing cache if needed
14888        if (mLayerType == LAYER_TYPE_SOFTWARE) {
14889            destroyDrawingCache();
14890        }
14891
14892        mLayerType = layerType;
14893        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
14894        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
14895        mRenderNode.setLayerPaint(mLayerPaint);
14896
14897        // draw() behaves differently if we are on a layer, so we need to
14898        // invalidate() here
14899        invalidateParentCaches();
14900        invalidate(true);
14901    }
14902
14903    /**
14904     * Updates the {@link Paint} object used with the current layer (used only if the current
14905     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
14906     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
14907     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
14908     * ensure that the view gets redrawn immediately.
14909     *
14910     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14911     * instance that controls how the layer is composed on screen. The following
14912     * properties of the paint are taken into account when composing the layer:</p>
14913     * <ul>
14914     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14915     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14916     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14917     * </ul>
14918     *
14919     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
14920     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
14921     *
14922     * @param paint The paint used to compose the layer. This argument is optional
14923     *        and can be null. It is ignored when the layer type is
14924     *        {@link #LAYER_TYPE_NONE}
14925     *
14926     * @see #setLayerType(int, android.graphics.Paint)
14927     */
14928    public void setLayerPaint(Paint paint) {
14929        int layerType = getLayerType();
14930        if (layerType != LAYER_TYPE_NONE) {
14931            mLayerPaint = paint == null ? new Paint() : paint;
14932            if (layerType == LAYER_TYPE_HARDWARE) {
14933                if (mRenderNode.setLayerPaint(mLayerPaint)) {
14934                    invalidateViewProperty(false, false);
14935                }
14936            } else {
14937                invalidate();
14938            }
14939        }
14940    }
14941
14942    /**
14943     * Indicates what type of layer is currently associated with this view. By default
14944     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14945     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14946     * for more information on the different types of layers.
14947     *
14948     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14949     *         {@link #LAYER_TYPE_HARDWARE}
14950     *
14951     * @see #setLayerType(int, android.graphics.Paint)
14952     * @see #buildLayer()
14953     * @see #LAYER_TYPE_NONE
14954     * @see #LAYER_TYPE_SOFTWARE
14955     * @see #LAYER_TYPE_HARDWARE
14956     */
14957    public int getLayerType() {
14958        return mLayerType;
14959    }
14960
14961    /**
14962     * Forces this view's layer to be created and this view to be rendered
14963     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14964     * invoking this method will have no effect.
14965     *
14966     * This method can for instance be used to render a view into its layer before
14967     * starting an animation. If this view is complex, rendering into the layer
14968     * before starting the animation will avoid skipping frames.
14969     *
14970     * @throws IllegalStateException If this view is not attached to a window
14971     *
14972     * @see #setLayerType(int, android.graphics.Paint)
14973     */
14974    public void buildLayer() {
14975        if (mLayerType == LAYER_TYPE_NONE) return;
14976
14977        final AttachInfo attachInfo = mAttachInfo;
14978        if (attachInfo == null) {
14979            throw new IllegalStateException("This view must be attached to a window first");
14980        }
14981
14982        if (getWidth() == 0 || getHeight() == 0) {
14983            return;
14984        }
14985
14986        switch (mLayerType) {
14987            case LAYER_TYPE_HARDWARE:
14988                updateDisplayListIfDirty();
14989                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14990                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14991                }
14992                break;
14993            case LAYER_TYPE_SOFTWARE:
14994                buildDrawingCache(true);
14995                break;
14996        }
14997    }
14998
14999    /**
15000     * If this View draws with a HardwareLayer, returns it.
15001     * Otherwise returns null
15002     *
15003     * TODO: Only TextureView uses this, can we eliminate it?
15004     */
15005    HardwareLayer getHardwareLayer() {
15006        return null;
15007    }
15008
15009    /**
15010     * Destroys all hardware rendering resources. This method is invoked
15011     * when the system needs to reclaim resources. Upon execution of this
15012     * method, you should free any OpenGL resources created by the view.
15013     *
15014     * Note: you <strong>must</strong> call
15015     * <code>super.destroyHardwareResources()</code> when overriding
15016     * this method.
15017     *
15018     * @hide
15019     */
15020    @CallSuper
15021    protected void destroyHardwareResources() {
15022        // Although the Layer will be destroyed by RenderNode, we want to release
15023        // the staging display list, which is also a signal to RenderNode that it's
15024        // safe to free its copy of the display list as it knows that we will
15025        // push an updated DisplayList if we try to draw again
15026        resetDisplayList();
15027    }
15028
15029    /**
15030     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15031     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15032     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15033     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15034     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15035     * null.</p>
15036     *
15037     * <p>Enabling the drawing cache is similar to
15038     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15039     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15040     * drawing cache has no effect on rendering because the system uses a different mechanism
15041     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15042     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15043     * for information on how to enable software and hardware layers.</p>
15044     *
15045     * <p>This API can be used to manually generate
15046     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15047     * {@link #getDrawingCache()}.</p>
15048     *
15049     * @param enabled true to enable the drawing cache, false otherwise
15050     *
15051     * @see #isDrawingCacheEnabled()
15052     * @see #getDrawingCache()
15053     * @see #buildDrawingCache()
15054     * @see #setLayerType(int, android.graphics.Paint)
15055     */
15056    public void setDrawingCacheEnabled(boolean enabled) {
15057        mCachingFailed = false;
15058        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15059    }
15060
15061    /**
15062     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15063     *
15064     * @return true if the drawing cache is enabled
15065     *
15066     * @see #setDrawingCacheEnabled(boolean)
15067     * @see #getDrawingCache()
15068     */
15069    @ViewDebug.ExportedProperty(category = "drawing")
15070    public boolean isDrawingCacheEnabled() {
15071        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15072    }
15073
15074    /**
15075     * Debugging utility which recursively outputs the dirty state of a view and its
15076     * descendants.
15077     *
15078     * @hide
15079     */
15080    @SuppressWarnings({"UnusedDeclaration"})
15081    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15082        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15083                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15084                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15085                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15086        if (clear) {
15087            mPrivateFlags &= clearMask;
15088        }
15089        if (this instanceof ViewGroup) {
15090            ViewGroup parent = (ViewGroup) this;
15091            final int count = parent.getChildCount();
15092            for (int i = 0; i < count; i++) {
15093                final View child = parent.getChildAt(i);
15094                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15095            }
15096        }
15097    }
15098
15099    /**
15100     * This method is used by ViewGroup to cause its children to restore or recreate their
15101     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15102     * to recreate its own display list, which would happen if it went through the normal
15103     * draw/dispatchDraw mechanisms.
15104     *
15105     * @hide
15106     */
15107    protected void dispatchGetDisplayList() {}
15108
15109    /**
15110     * A view that is not attached or hardware accelerated cannot create a display list.
15111     * This method checks these conditions and returns the appropriate result.
15112     *
15113     * @return true if view has the ability to create a display list, false otherwise.
15114     *
15115     * @hide
15116     */
15117    public boolean canHaveDisplayList() {
15118        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
15119    }
15120
15121    /**
15122     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15123     * @hide
15124     */
15125    @NonNull
15126    public RenderNode updateDisplayListIfDirty() {
15127        final RenderNode renderNode = mRenderNode;
15128        if (!canHaveDisplayList()) {
15129            // can't populate RenderNode, don't try
15130            return renderNode;
15131        }
15132
15133        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
15134                || !renderNode.isValid()
15135                || (mRecreateDisplayList)) {
15136            // Don't need to recreate the display list, just need to tell our
15137            // children to restore/recreate theirs
15138            if (renderNode.isValid()
15139                    && !mRecreateDisplayList) {
15140                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15141                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15142                dispatchGetDisplayList();
15143
15144                return renderNode; // no work needed
15145            }
15146
15147            // If we got here, we're recreating it. Mark it as such to ensure that
15148            // we copy in child display lists into ours in drawChild()
15149            mRecreateDisplayList = true;
15150
15151            int width = mRight - mLeft;
15152            int height = mBottom - mTop;
15153            int layerType = getLayerType();
15154
15155            final DisplayListCanvas canvas = renderNode.start(width, height);
15156            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
15157
15158            try {
15159                final HardwareLayer layer = getHardwareLayer();
15160                if (layer != null && layer.isValid()) {
15161                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
15162                } else if (layerType == LAYER_TYPE_SOFTWARE) {
15163                    buildDrawingCache(true);
15164                    Bitmap cache = getDrawingCache(true);
15165                    if (cache != null) {
15166                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
15167                    }
15168                } else {
15169                    computeScroll();
15170
15171                    canvas.translate(-mScrollX, -mScrollY);
15172                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15173                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15174
15175                    // Fast path for layouts with no backgrounds
15176                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15177                        dispatchDraw(canvas);
15178                        if (mOverlay != null && !mOverlay.isEmpty()) {
15179                            mOverlay.getOverlayView().draw(canvas);
15180                        }
15181                    } else {
15182                        draw(canvas);
15183                    }
15184                }
15185            } finally {
15186                renderNode.end(canvas);
15187                setDisplayListProperties(renderNode);
15188            }
15189        } else {
15190            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
15191            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15192        }
15193        return renderNode;
15194    }
15195
15196    private void resetDisplayList() {
15197        if (mRenderNode.isValid()) {
15198            mRenderNode.destroyDisplayListData();
15199        }
15200
15201        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
15202            mBackgroundRenderNode.destroyDisplayListData();
15203        }
15204    }
15205
15206    /**
15207     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
15208     *
15209     * @return A non-scaled bitmap representing this view or null if cache is disabled.
15210     *
15211     * @see #getDrawingCache(boolean)
15212     */
15213    public Bitmap getDrawingCache() {
15214        return getDrawingCache(false);
15215    }
15216
15217    /**
15218     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
15219     * is null when caching is disabled. If caching is enabled and the cache is not ready,
15220     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
15221     * draw from the cache when the cache is enabled. To benefit from the cache, you must
15222     * request the drawing cache by calling this method and draw it on screen if the
15223     * returned bitmap is not null.</p>
15224     *
15225     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
15226     * this method will create a bitmap of the same size as this view. Because this bitmap
15227     * will be drawn scaled by the parent ViewGroup, the result on screen might show
15228     * scaling artifacts. To avoid such artifacts, you should call this method by setting
15229     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
15230     * size than the view. This implies that your application must be able to handle this
15231     * size.</p>
15232     *
15233     * @param autoScale Indicates whether the generated bitmap should be scaled based on
15234     *        the current density of the screen when the application is in compatibility
15235     *        mode.
15236     *
15237     * @return A bitmap representing this view or null if cache is disabled.
15238     *
15239     * @see #setDrawingCacheEnabled(boolean)
15240     * @see #isDrawingCacheEnabled()
15241     * @see #buildDrawingCache(boolean)
15242     * @see #destroyDrawingCache()
15243     */
15244    public Bitmap getDrawingCache(boolean autoScale) {
15245        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
15246            return null;
15247        }
15248        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
15249            buildDrawingCache(autoScale);
15250        }
15251        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
15252    }
15253
15254    /**
15255     * <p>Frees the resources used by the drawing cache. If you call
15256     * {@link #buildDrawingCache()} manually without calling
15257     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
15258     * should cleanup the cache with this method afterwards.</p>
15259     *
15260     * @see #setDrawingCacheEnabled(boolean)
15261     * @see #buildDrawingCache()
15262     * @see #getDrawingCache()
15263     */
15264    public void destroyDrawingCache() {
15265        if (mDrawingCache != null) {
15266            mDrawingCache.recycle();
15267            mDrawingCache = null;
15268        }
15269        if (mUnscaledDrawingCache != null) {
15270            mUnscaledDrawingCache.recycle();
15271            mUnscaledDrawingCache = null;
15272        }
15273    }
15274
15275    /**
15276     * Setting a solid background color for the drawing cache's bitmaps will improve
15277     * performance and memory usage. Note, though that this should only be used if this
15278     * view will always be drawn on top of a solid color.
15279     *
15280     * @param color The background color to use for the drawing cache's bitmap
15281     *
15282     * @see #setDrawingCacheEnabled(boolean)
15283     * @see #buildDrawingCache()
15284     * @see #getDrawingCache()
15285     */
15286    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
15287        if (color != mDrawingCacheBackgroundColor) {
15288            mDrawingCacheBackgroundColor = color;
15289            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
15290        }
15291    }
15292
15293    /**
15294     * @see #setDrawingCacheBackgroundColor(int)
15295     *
15296     * @return The background color to used for the drawing cache's bitmap
15297     */
15298    @ColorInt
15299    public int getDrawingCacheBackgroundColor() {
15300        return mDrawingCacheBackgroundColor;
15301    }
15302
15303    /**
15304     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
15305     *
15306     * @see #buildDrawingCache(boolean)
15307     */
15308    public void buildDrawingCache() {
15309        buildDrawingCache(false);
15310    }
15311
15312    /**
15313     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
15314     *
15315     * <p>If you call {@link #buildDrawingCache()} manually without calling
15316     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
15317     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
15318     *
15319     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
15320     * this method will create a bitmap of the same size as this view. Because this bitmap
15321     * will be drawn scaled by the parent ViewGroup, the result on screen might show
15322     * scaling artifacts. To avoid such artifacts, you should call this method by setting
15323     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
15324     * size than the view. This implies that your application must be able to handle this
15325     * size.</p>
15326     *
15327     * <p>You should avoid calling this method when hardware acceleration is enabled. If
15328     * you do not need the drawing cache bitmap, calling this method will increase memory
15329     * usage and cause the view to be rendered in software once, thus negatively impacting
15330     * performance.</p>
15331     *
15332     * @see #getDrawingCache()
15333     * @see #destroyDrawingCache()
15334     */
15335    public void buildDrawingCache(boolean autoScale) {
15336        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
15337                mDrawingCache == null : mUnscaledDrawingCache == null)) {
15338            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
15339                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
15340                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
15341            }
15342            try {
15343                buildDrawingCacheImpl(autoScale);
15344            } finally {
15345                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
15346            }
15347        }
15348    }
15349
15350    /**
15351     * private, internal implementation of buildDrawingCache, used to enable tracing
15352     */
15353    private void buildDrawingCacheImpl(boolean autoScale) {
15354        mCachingFailed = false;
15355
15356        int width = mRight - mLeft;
15357        int height = mBottom - mTop;
15358
15359        final AttachInfo attachInfo = mAttachInfo;
15360        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
15361
15362        if (autoScale && scalingRequired) {
15363            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
15364            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
15365        }
15366
15367        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
15368        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
15369        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
15370
15371        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
15372        final long drawingCacheSize =
15373                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
15374        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
15375            if (width > 0 && height > 0) {
15376                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
15377                        + " too large to fit into a software layer (or drawing cache), needs "
15378                        + projectedBitmapSize + " bytes, only "
15379                        + drawingCacheSize + " available");
15380            }
15381            destroyDrawingCache();
15382            mCachingFailed = true;
15383            return;
15384        }
15385
15386        boolean clear = true;
15387        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
15388
15389        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
15390            Bitmap.Config quality;
15391            if (!opaque) {
15392                // Never pick ARGB_4444 because it looks awful
15393                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
15394                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
15395                    case DRAWING_CACHE_QUALITY_AUTO:
15396                    case DRAWING_CACHE_QUALITY_LOW:
15397                    case DRAWING_CACHE_QUALITY_HIGH:
15398                    default:
15399                        quality = Bitmap.Config.ARGB_8888;
15400                        break;
15401                }
15402            } else {
15403                // Optimization for translucent windows
15404                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
15405                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
15406            }
15407
15408            // Try to cleanup memory
15409            if (bitmap != null) bitmap.recycle();
15410
15411            try {
15412                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15413                        width, height, quality);
15414                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
15415                if (autoScale) {
15416                    mDrawingCache = bitmap;
15417                } else {
15418                    mUnscaledDrawingCache = bitmap;
15419                }
15420                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
15421            } catch (OutOfMemoryError e) {
15422                // If there is not enough memory to create the bitmap cache, just
15423                // ignore the issue as bitmap caches are not required to draw the
15424                // view hierarchy
15425                if (autoScale) {
15426                    mDrawingCache = null;
15427                } else {
15428                    mUnscaledDrawingCache = null;
15429                }
15430                mCachingFailed = true;
15431                return;
15432            }
15433
15434            clear = drawingCacheBackgroundColor != 0;
15435        }
15436
15437        Canvas canvas;
15438        if (attachInfo != null) {
15439            canvas = attachInfo.mCanvas;
15440            if (canvas == null) {
15441                canvas = new Canvas();
15442            }
15443            canvas.setBitmap(bitmap);
15444            // Temporarily clobber the cached Canvas in case one of our children
15445            // is also using a drawing cache. Without this, the children would
15446            // steal the canvas by attaching their own bitmap to it and bad, bad
15447            // thing would happen (invisible views, corrupted drawings, etc.)
15448            attachInfo.mCanvas = null;
15449        } else {
15450            // This case should hopefully never or seldom happen
15451            canvas = new Canvas(bitmap);
15452        }
15453
15454        if (clear) {
15455            bitmap.eraseColor(drawingCacheBackgroundColor);
15456        }
15457
15458        computeScroll();
15459        final int restoreCount = canvas.save();
15460
15461        if (autoScale && scalingRequired) {
15462            final float scale = attachInfo.mApplicationScale;
15463            canvas.scale(scale, scale);
15464        }
15465
15466        canvas.translate(-mScrollX, -mScrollY);
15467
15468        mPrivateFlags |= PFLAG_DRAWN;
15469        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
15470                mLayerType != LAYER_TYPE_NONE) {
15471            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
15472        }
15473
15474        // Fast path for layouts with no backgrounds
15475        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15476            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15477            dispatchDraw(canvas);
15478            if (mOverlay != null && !mOverlay.isEmpty()) {
15479                mOverlay.getOverlayView().draw(canvas);
15480            }
15481        } else {
15482            draw(canvas);
15483        }
15484
15485        canvas.restoreToCount(restoreCount);
15486        canvas.setBitmap(null);
15487
15488        if (attachInfo != null) {
15489            // Restore the cached Canvas for our siblings
15490            attachInfo.mCanvas = canvas;
15491        }
15492    }
15493
15494    /**
15495     * Create a snapshot of the view into a bitmap.  We should probably make
15496     * some form of this public, but should think about the API.
15497     */
15498    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
15499        int width = mRight - mLeft;
15500        int height = mBottom - mTop;
15501
15502        final AttachInfo attachInfo = mAttachInfo;
15503        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
15504        width = (int) ((width * scale) + 0.5f);
15505        height = (int) ((height * scale) + 0.5f);
15506
15507        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15508                width > 0 ? width : 1, height > 0 ? height : 1, quality);
15509        if (bitmap == null) {
15510            throw new OutOfMemoryError();
15511        }
15512
15513        Resources resources = getResources();
15514        if (resources != null) {
15515            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
15516        }
15517
15518        Canvas canvas;
15519        if (attachInfo != null) {
15520            canvas = attachInfo.mCanvas;
15521            if (canvas == null) {
15522                canvas = new Canvas();
15523            }
15524            canvas.setBitmap(bitmap);
15525            // Temporarily clobber the cached Canvas in case one of our children
15526            // is also using a drawing cache. Without this, the children would
15527            // steal the canvas by attaching their own bitmap to it and bad, bad
15528            // things would happen (invisible views, corrupted drawings, etc.)
15529            attachInfo.mCanvas = null;
15530        } else {
15531            // This case should hopefully never or seldom happen
15532            canvas = new Canvas(bitmap);
15533        }
15534
15535        if ((backgroundColor & 0xff000000) != 0) {
15536            bitmap.eraseColor(backgroundColor);
15537        }
15538
15539        computeScroll();
15540        final int restoreCount = canvas.save();
15541        canvas.scale(scale, scale);
15542        canvas.translate(-mScrollX, -mScrollY);
15543
15544        // Temporarily remove the dirty mask
15545        int flags = mPrivateFlags;
15546        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15547
15548        // Fast path for layouts with no backgrounds
15549        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15550            dispatchDraw(canvas);
15551            if (mOverlay != null && !mOverlay.isEmpty()) {
15552                mOverlay.getOverlayView().draw(canvas);
15553            }
15554        } else {
15555            draw(canvas);
15556        }
15557
15558        mPrivateFlags = flags;
15559
15560        canvas.restoreToCount(restoreCount);
15561        canvas.setBitmap(null);
15562
15563        if (attachInfo != null) {
15564            // Restore the cached Canvas for our siblings
15565            attachInfo.mCanvas = canvas;
15566        }
15567
15568        return bitmap;
15569    }
15570
15571    /**
15572     * Indicates whether this View is currently in edit mode. A View is usually
15573     * in edit mode when displayed within a developer tool. For instance, if
15574     * this View is being drawn by a visual user interface builder, this method
15575     * should return true.
15576     *
15577     * Subclasses should check the return value of this method to provide
15578     * different behaviors if their normal behavior might interfere with the
15579     * host environment. For instance: the class spawns a thread in its
15580     * constructor, the drawing code relies on device-specific features, etc.
15581     *
15582     * This method is usually checked in the drawing code of custom widgets.
15583     *
15584     * @return True if this View is in edit mode, false otherwise.
15585     */
15586    public boolean isInEditMode() {
15587        return false;
15588    }
15589
15590    /**
15591     * If the View draws content inside its padding and enables fading edges,
15592     * it needs to support padding offsets. Padding offsets are added to the
15593     * fading edges to extend the length of the fade so that it covers pixels
15594     * drawn inside the padding.
15595     *
15596     * Subclasses of this class should override this method if they need
15597     * to draw content inside the padding.
15598     *
15599     * @return True if padding offset must be applied, false otherwise.
15600     *
15601     * @see #getLeftPaddingOffset()
15602     * @see #getRightPaddingOffset()
15603     * @see #getTopPaddingOffset()
15604     * @see #getBottomPaddingOffset()
15605     *
15606     * @since CURRENT
15607     */
15608    protected boolean isPaddingOffsetRequired() {
15609        return false;
15610    }
15611
15612    /**
15613     * Amount by which to extend the left fading region. Called only when
15614     * {@link #isPaddingOffsetRequired()} returns true.
15615     *
15616     * @return The left padding offset in pixels.
15617     *
15618     * @see #isPaddingOffsetRequired()
15619     *
15620     * @since CURRENT
15621     */
15622    protected int getLeftPaddingOffset() {
15623        return 0;
15624    }
15625
15626    /**
15627     * Amount by which to extend the right fading region. Called only when
15628     * {@link #isPaddingOffsetRequired()} returns true.
15629     *
15630     * @return The right padding offset in pixels.
15631     *
15632     * @see #isPaddingOffsetRequired()
15633     *
15634     * @since CURRENT
15635     */
15636    protected int getRightPaddingOffset() {
15637        return 0;
15638    }
15639
15640    /**
15641     * Amount by which to extend the top fading region. Called only when
15642     * {@link #isPaddingOffsetRequired()} returns true.
15643     *
15644     * @return The top padding offset in pixels.
15645     *
15646     * @see #isPaddingOffsetRequired()
15647     *
15648     * @since CURRENT
15649     */
15650    protected int getTopPaddingOffset() {
15651        return 0;
15652    }
15653
15654    /**
15655     * Amount by which to extend the bottom fading region. Called only when
15656     * {@link #isPaddingOffsetRequired()} returns true.
15657     *
15658     * @return The bottom padding offset in pixels.
15659     *
15660     * @see #isPaddingOffsetRequired()
15661     *
15662     * @since CURRENT
15663     */
15664    protected int getBottomPaddingOffset() {
15665        return 0;
15666    }
15667
15668    /**
15669     * @hide
15670     * @param offsetRequired
15671     */
15672    protected int getFadeTop(boolean offsetRequired) {
15673        int top = mPaddingTop;
15674        if (offsetRequired) top += getTopPaddingOffset();
15675        return top;
15676    }
15677
15678    /**
15679     * @hide
15680     * @param offsetRequired
15681     */
15682    protected int getFadeHeight(boolean offsetRequired) {
15683        int padding = mPaddingTop;
15684        if (offsetRequired) padding += getTopPaddingOffset();
15685        return mBottom - mTop - mPaddingBottom - padding;
15686    }
15687
15688    /**
15689     * <p>Indicates whether this view is attached to a hardware accelerated
15690     * window or not.</p>
15691     *
15692     * <p>Even if this method returns true, it does not mean that every call
15693     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15694     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15695     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15696     * window is hardware accelerated,
15697     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15698     * return false, and this method will return true.</p>
15699     *
15700     * @return True if the view is attached to a window and the window is
15701     *         hardware accelerated; false in any other case.
15702     */
15703    @ViewDebug.ExportedProperty(category = "drawing")
15704    public boolean isHardwareAccelerated() {
15705        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15706    }
15707
15708    /**
15709     * Sets a rectangular area on this view to which the view will be clipped
15710     * when it is drawn. Setting the value to null will remove the clip bounds
15711     * and the view will draw normally, using its full bounds.
15712     *
15713     * @param clipBounds The rectangular area, in the local coordinates of
15714     * this view, to which future drawing operations will be clipped.
15715     */
15716    public void setClipBounds(Rect clipBounds) {
15717        if (clipBounds == mClipBounds
15718                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15719            return;
15720        }
15721        if (clipBounds != null) {
15722            if (mClipBounds == null) {
15723                mClipBounds = new Rect(clipBounds);
15724            } else {
15725                mClipBounds.set(clipBounds);
15726            }
15727        } else {
15728            mClipBounds = null;
15729        }
15730        mRenderNode.setClipBounds(mClipBounds);
15731        invalidateViewProperty(false, false);
15732    }
15733
15734    /**
15735     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15736     *
15737     * @return A copy of the current clip bounds if clip bounds are set,
15738     * otherwise null.
15739     */
15740    public Rect getClipBounds() {
15741        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15742    }
15743
15744
15745    /**
15746     * Populates an output rectangle with the clip bounds of the view,
15747     * returning {@code true} if successful or {@code false} if the view's
15748     * clip bounds are {@code null}.
15749     *
15750     * @param outRect rectangle in which to place the clip bounds of the view
15751     * @return {@code true} if successful or {@code false} if the view's
15752     *         clip bounds are {@code null}
15753     */
15754    public boolean getClipBounds(Rect outRect) {
15755        if (mClipBounds != null) {
15756            outRect.set(mClipBounds);
15757            return true;
15758        }
15759        return false;
15760    }
15761
15762    /**
15763     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15764     * case of an active Animation being run on the view.
15765     */
15766    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15767            Animation a, boolean scalingRequired) {
15768        Transformation invalidationTransform;
15769        final int flags = parent.mGroupFlags;
15770        final boolean initialized = a.isInitialized();
15771        if (!initialized) {
15772            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15773            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15774            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15775            onAnimationStart();
15776        }
15777
15778        final Transformation t = parent.getChildTransformation();
15779        boolean more = a.getTransformation(drawingTime, t, 1f);
15780        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15781            if (parent.mInvalidationTransformation == null) {
15782                parent.mInvalidationTransformation = new Transformation();
15783            }
15784            invalidationTransform = parent.mInvalidationTransformation;
15785            a.getTransformation(drawingTime, invalidationTransform, 1f);
15786        } else {
15787            invalidationTransform = t;
15788        }
15789
15790        if (more) {
15791            if (!a.willChangeBounds()) {
15792                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15793                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15794                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15795                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15796                    // The child need to draw an animation, potentially offscreen, so
15797                    // make sure we do not cancel invalidate requests
15798                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15799                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15800                }
15801            } else {
15802                if (parent.mInvalidateRegion == null) {
15803                    parent.mInvalidateRegion = new RectF();
15804                }
15805                final RectF region = parent.mInvalidateRegion;
15806                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15807                        invalidationTransform);
15808
15809                // The child need to draw an animation, potentially offscreen, so
15810                // make sure we do not cancel invalidate requests
15811                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15812
15813                final int left = mLeft + (int) region.left;
15814                final int top = mTop + (int) region.top;
15815                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15816                        top + (int) (region.height() + .5f));
15817            }
15818        }
15819        return more;
15820    }
15821
15822    /**
15823     * This method is called by getDisplayList() when a display list is recorded for a View.
15824     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15825     */
15826    void setDisplayListProperties(RenderNode renderNode) {
15827        if (renderNode != null) {
15828            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15829            renderNode.setClipToBounds(mParent instanceof ViewGroup
15830                    && ((ViewGroup) mParent).getClipChildren());
15831
15832            float alpha = 1;
15833            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15834                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15835                ViewGroup parentVG = (ViewGroup) mParent;
15836                final Transformation t = parentVG.getChildTransformation();
15837                if (parentVG.getChildStaticTransformation(this, t)) {
15838                    final int transformType = t.getTransformationType();
15839                    if (transformType != Transformation.TYPE_IDENTITY) {
15840                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15841                            alpha = t.getAlpha();
15842                        }
15843                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15844                            renderNode.setStaticMatrix(t.getMatrix());
15845                        }
15846                    }
15847                }
15848            }
15849            if (mTransformationInfo != null) {
15850                alpha *= getFinalAlpha();
15851                if (alpha < 1) {
15852                    final int multipliedAlpha = (int) (255 * alpha);
15853                    if (onSetAlpha(multipliedAlpha)) {
15854                        alpha = 1;
15855                    }
15856                }
15857                renderNode.setAlpha(alpha);
15858            } else if (alpha < 1) {
15859                renderNode.setAlpha(alpha);
15860            }
15861        }
15862    }
15863
15864    /**
15865     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15866     *
15867     * This is where the View specializes rendering behavior based on layer type,
15868     * and hardware acceleration.
15869     */
15870    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15871        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15872        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15873         *
15874         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15875         * HW accelerated, it can't handle drawing RenderNodes.
15876         */
15877        boolean drawingWithRenderNode = mAttachInfo != null
15878                && mAttachInfo.mHardwareAccelerated
15879                && hardwareAcceleratedCanvas;
15880
15881        boolean more = false;
15882        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15883        final int parentFlags = parent.mGroupFlags;
15884
15885        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15886            parent.getChildTransformation().clear();
15887            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15888        }
15889
15890        Transformation transformToApply = null;
15891        boolean concatMatrix = false;
15892        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15893        final Animation a = getAnimation();
15894        if (a != null) {
15895            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15896            concatMatrix = a.willChangeTransformationMatrix();
15897            if (concatMatrix) {
15898                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15899            }
15900            transformToApply = parent.getChildTransformation();
15901        } else {
15902            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15903                // No longer animating: clear out old animation matrix
15904                mRenderNode.setAnimationMatrix(null);
15905                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15906            }
15907            if (!drawingWithRenderNode
15908                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15909                final Transformation t = parent.getChildTransformation();
15910                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15911                if (hasTransform) {
15912                    final int transformType = t.getTransformationType();
15913                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15914                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15915                }
15916            }
15917        }
15918
15919        concatMatrix |= !childHasIdentityMatrix;
15920
15921        // Sets the flag as early as possible to allow draw() implementations
15922        // to call invalidate() successfully when doing animations
15923        mPrivateFlags |= PFLAG_DRAWN;
15924
15925        if (!concatMatrix &&
15926                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15927                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15928                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15929                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15930            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15931            return more;
15932        }
15933        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15934
15935        if (hardwareAcceleratedCanvas) {
15936            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15937            // retain the flag's value temporarily in the mRecreateDisplayList flag
15938            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15939            mPrivateFlags &= ~PFLAG_INVALIDATED;
15940        }
15941
15942        RenderNode renderNode = null;
15943        Bitmap cache = null;
15944        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
15945        if (layerType == LAYER_TYPE_SOFTWARE
15946                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15947            // If not drawing with RenderNode, treat HW layers as SW
15948            layerType = LAYER_TYPE_SOFTWARE;
15949            buildDrawingCache(true);
15950            cache = getDrawingCache(true);
15951        }
15952
15953        if (drawingWithRenderNode) {
15954            // Delay getting the display list until animation-driven alpha values are
15955            // set up and possibly passed on to the view
15956            renderNode = updateDisplayListIfDirty();
15957            if (!renderNode.isValid()) {
15958                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15959                // to getDisplayList(), the display list will be marked invalid and we should not
15960                // try to use it again.
15961                renderNode = null;
15962                drawingWithRenderNode = false;
15963            }
15964        }
15965
15966        int sx = 0;
15967        int sy = 0;
15968        if (!drawingWithRenderNode) {
15969            computeScroll();
15970            sx = mScrollX;
15971            sy = mScrollY;
15972        }
15973
15974        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
15975        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
15976
15977        int restoreTo = -1;
15978        if (!drawingWithRenderNode || transformToApply != null) {
15979            restoreTo = canvas.save();
15980        }
15981        if (offsetForScroll) {
15982            canvas.translate(mLeft - sx, mTop - sy);
15983        } else {
15984            if (!drawingWithRenderNode) {
15985                canvas.translate(mLeft, mTop);
15986            }
15987            if (scalingRequired) {
15988                if (drawingWithRenderNode) {
15989                    // TODO: Might not need this if we put everything inside the DL
15990                    restoreTo = canvas.save();
15991                }
15992                // mAttachInfo cannot be null, otherwise scalingRequired == false
15993                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15994                canvas.scale(scale, scale);
15995            }
15996        }
15997
15998        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15999        if (transformToApply != null
16000                || alpha < 1
16001                || !hasIdentityMatrix()
16002                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16003            if (transformToApply != null || !childHasIdentityMatrix) {
16004                int transX = 0;
16005                int transY = 0;
16006
16007                if (offsetForScroll) {
16008                    transX = -sx;
16009                    transY = -sy;
16010                }
16011
16012                if (transformToApply != null) {
16013                    if (concatMatrix) {
16014                        if (drawingWithRenderNode) {
16015                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16016                        } else {
16017                            // Undo the scroll translation, apply the transformation matrix,
16018                            // then redo the scroll translate to get the correct result.
16019                            canvas.translate(-transX, -transY);
16020                            canvas.concat(transformToApply.getMatrix());
16021                            canvas.translate(transX, transY);
16022                        }
16023                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16024                    }
16025
16026                    float transformAlpha = transformToApply.getAlpha();
16027                    if (transformAlpha < 1) {
16028                        alpha *= transformAlpha;
16029                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16030                    }
16031                }
16032
16033                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16034                    canvas.translate(-transX, -transY);
16035                    canvas.concat(getMatrix());
16036                    canvas.translate(transX, transY);
16037                }
16038            }
16039
16040            // Deal with alpha if it is or used to be <1
16041            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16042                if (alpha < 1) {
16043                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16044                } else {
16045                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16046                }
16047                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16048                if (!drawingWithDrawingCache) {
16049                    final int multipliedAlpha = (int) (255 * alpha);
16050                    if (!onSetAlpha(multipliedAlpha)) {
16051                        if (drawingWithRenderNode) {
16052                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16053                        } else if (layerType == LAYER_TYPE_NONE) {
16054                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16055                                    multipliedAlpha);
16056                        }
16057                    } else {
16058                        // Alpha is handled by the child directly, clobber the layer's alpha
16059                        mPrivateFlags |= PFLAG_ALPHA_SET;
16060                    }
16061                }
16062            }
16063        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16064            onSetAlpha(255);
16065            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16066        }
16067
16068        if (!drawingWithRenderNode) {
16069            // apply clips directly, since RenderNode won't do it for this draw
16070            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16071                if (offsetForScroll) {
16072                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16073                } else {
16074                    if (!scalingRequired || cache == null) {
16075                        canvas.clipRect(0, 0, getWidth(), getHeight());
16076                    } else {
16077                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16078                    }
16079                }
16080            }
16081
16082            if (mClipBounds != null) {
16083                // clip bounds ignore scroll
16084                canvas.clipRect(mClipBounds);
16085            }
16086        }
16087
16088        if (!drawingWithDrawingCache) {
16089            if (drawingWithRenderNode) {
16090                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16091                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16092            } else {
16093                // Fast path for layouts with no backgrounds
16094                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16095                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16096                    dispatchDraw(canvas);
16097                } else {
16098                    draw(canvas);
16099                }
16100            }
16101        } else if (cache != null) {
16102            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16103            if (layerType == LAYER_TYPE_NONE) {
16104                // no layer paint, use temporary paint to draw bitmap
16105                Paint cachePaint = parent.mCachePaint;
16106                if (cachePaint == null) {
16107                    cachePaint = new Paint();
16108                    cachePaint.setDither(false);
16109                    parent.mCachePaint = cachePaint;
16110                }
16111                cachePaint.setAlpha((int) (alpha * 255));
16112                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16113            } else {
16114                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16115                int layerPaintAlpha = mLayerPaint.getAlpha();
16116                mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16117                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
16118                mLayerPaint.setAlpha(layerPaintAlpha);
16119            }
16120        }
16121
16122        if (restoreTo >= 0) {
16123            canvas.restoreToCount(restoreTo);
16124        }
16125
16126        if (a != null && !more) {
16127            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
16128                onSetAlpha(255);
16129            }
16130            parent.finishAnimatingView(this, a);
16131        }
16132
16133        if (more && hardwareAcceleratedCanvas) {
16134            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16135                // alpha animations should cause the child to recreate its display list
16136                invalidate(true);
16137            }
16138        }
16139
16140        mRecreateDisplayList = false;
16141
16142        return more;
16143    }
16144
16145    /**
16146     * Manually render this view (and all of its children) to the given Canvas.
16147     * The view must have already done a full layout before this function is
16148     * called.  When implementing a view, implement
16149     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
16150     * If you do need to override this method, call the superclass version.
16151     *
16152     * @param canvas The Canvas to which the View is rendered.
16153     */
16154    @CallSuper
16155    public void draw(Canvas canvas) {
16156        final int privateFlags = mPrivateFlags;
16157        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
16158                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
16159        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
16160
16161        /*
16162         * Draw traversal performs several drawing steps which must be executed
16163         * in the appropriate order:
16164         *
16165         *      1. Draw the background
16166         *      2. If necessary, save the canvas' layers to prepare for fading
16167         *      3. Draw view's content
16168         *      4. Draw children
16169         *      5. If necessary, draw the fading edges and restore layers
16170         *      6. Draw decorations (scrollbars for instance)
16171         */
16172
16173        // Step 1, draw the background, if needed
16174        int saveCount;
16175
16176        if (!dirtyOpaque) {
16177            drawBackground(canvas);
16178        }
16179
16180        // skip step 2 & 5 if possible (common case)
16181        final int viewFlags = mViewFlags;
16182        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
16183        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
16184        if (!verticalEdges && !horizontalEdges) {
16185            // Step 3, draw the content
16186            if (!dirtyOpaque) onDraw(canvas);
16187
16188            // Step 4, draw the children
16189            dispatchDraw(canvas);
16190
16191            // Overlay is part of the content and draws beneath Foreground
16192            if (mOverlay != null && !mOverlay.isEmpty()) {
16193                mOverlay.getOverlayView().dispatchDraw(canvas);
16194            }
16195
16196            // Step 6, draw decorations (foreground, scrollbars)
16197            onDrawForeground(canvas);
16198
16199            // we're done...
16200            return;
16201        }
16202
16203        /*
16204         * Here we do the full fledged routine...
16205         * (this is an uncommon case where speed matters less,
16206         * this is why we repeat some of the tests that have been
16207         * done above)
16208         */
16209
16210        boolean drawTop = false;
16211        boolean drawBottom = false;
16212        boolean drawLeft = false;
16213        boolean drawRight = false;
16214
16215        float topFadeStrength = 0.0f;
16216        float bottomFadeStrength = 0.0f;
16217        float leftFadeStrength = 0.0f;
16218        float rightFadeStrength = 0.0f;
16219
16220        // Step 2, save the canvas' layers
16221        int paddingLeft = mPaddingLeft;
16222
16223        final boolean offsetRequired = isPaddingOffsetRequired();
16224        if (offsetRequired) {
16225            paddingLeft += getLeftPaddingOffset();
16226        }
16227
16228        int left = mScrollX + paddingLeft;
16229        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
16230        int top = mScrollY + getFadeTop(offsetRequired);
16231        int bottom = top + getFadeHeight(offsetRequired);
16232
16233        if (offsetRequired) {
16234            right += getRightPaddingOffset();
16235            bottom += getBottomPaddingOffset();
16236        }
16237
16238        final ScrollabilityCache scrollabilityCache = mScrollCache;
16239        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
16240        int length = (int) fadeHeight;
16241
16242        // clip the fade length if top and bottom fades overlap
16243        // overlapping fades produce odd-looking artifacts
16244        if (verticalEdges && (top + length > bottom - length)) {
16245            length = (bottom - top) / 2;
16246        }
16247
16248        // also clip horizontal fades if necessary
16249        if (horizontalEdges && (left + length > right - length)) {
16250            length = (right - left) / 2;
16251        }
16252
16253        if (verticalEdges) {
16254            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
16255            drawTop = topFadeStrength * fadeHeight > 1.0f;
16256            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
16257            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
16258        }
16259
16260        if (horizontalEdges) {
16261            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
16262            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
16263            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
16264            drawRight = rightFadeStrength * fadeHeight > 1.0f;
16265        }
16266
16267        saveCount = canvas.getSaveCount();
16268
16269        int solidColor = getSolidColor();
16270        if (solidColor == 0) {
16271            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
16272
16273            if (drawTop) {
16274                canvas.saveLayer(left, top, right, top + length, null, flags);
16275            }
16276
16277            if (drawBottom) {
16278                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
16279            }
16280
16281            if (drawLeft) {
16282                canvas.saveLayer(left, top, left + length, bottom, null, flags);
16283            }
16284
16285            if (drawRight) {
16286                canvas.saveLayer(right - length, top, right, bottom, null, flags);
16287            }
16288        } else {
16289            scrollabilityCache.setFadeColor(solidColor);
16290        }
16291
16292        // Step 3, draw the content
16293        if (!dirtyOpaque) onDraw(canvas);
16294
16295        // Step 4, draw the children
16296        dispatchDraw(canvas);
16297
16298        // Step 5, draw the fade effect and restore layers
16299        final Paint p = scrollabilityCache.paint;
16300        final Matrix matrix = scrollabilityCache.matrix;
16301        final Shader fade = scrollabilityCache.shader;
16302
16303        if (drawTop) {
16304            matrix.setScale(1, fadeHeight * topFadeStrength);
16305            matrix.postTranslate(left, top);
16306            fade.setLocalMatrix(matrix);
16307            p.setShader(fade);
16308            canvas.drawRect(left, top, right, top + length, p);
16309        }
16310
16311        if (drawBottom) {
16312            matrix.setScale(1, fadeHeight * bottomFadeStrength);
16313            matrix.postRotate(180);
16314            matrix.postTranslate(left, bottom);
16315            fade.setLocalMatrix(matrix);
16316            p.setShader(fade);
16317            canvas.drawRect(left, bottom - length, right, bottom, p);
16318        }
16319
16320        if (drawLeft) {
16321            matrix.setScale(1, fadeHeight * leftFadeStrength);
16322            matrix.postRotate(-90);
16323            matrix.postTranslate(left, top);
16324            fade.setLocalMatrix(matrix);
16325            p.setShader(fade);
16326            canvas.drawRect(left, top, left + length, bottom, p);
16327        }
16328
16329        if (drawRight) {
16330            matrix.setScale(1, fadeHeight * rightFadeStrength);
16331            matrix.postRotate(90);
16332            matrix.postTranslate(right, top);
16333            fade.setLocalMatrix(matrix);
16334            p.setShader(fade);
16335            canvas.drawRect(right - length, top, right, bottom, p);
16336        }
16337
16338        canvas.restoreToCount(saveCount);
16339
16340        // Overlay is part of the content and draws beneath Foreground
16341        if (mOverlay != null && !mOverlay.isEmpty()) {
16342            mOverlay.getOverlayView().dispatchDraw(canvas);
16343        }
16344
16345        // Step 6, draw decorations (foreground, scrollbars)
16346        onDrawForeground(canvas);
16347    }
16348
16349    /**
16350     * Draws the background onto the specified canvas.
16351     *
16352     * @param canvas Canvas on which to draw the background
16353     */
16354    private void drawBackground(Canvas canvas) {
16355        final Drawable background = mBackground;
16356        if (background == null) {
16357            return;
16358        }
16359
16360        setBackgroundBounds();
16361
16362        // Attempt to use a display list if requested.
16363        if (canvas.isHardwareAccelerated() && mAttachInfo != null
16364                && mAttachInfo.mHardwareRenderer != null) {
16365            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
16366
16367            final RenderNode renderNode = mBackgroundRenderNode;
16368            if (renderNode != null && renderNode.isValid()) {
16369                setBackgroundRenderNodeProperties(renderNode);
16370                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16371                return;
16372            }
16373        }
16374
16375        final int scrollX = mScrollX;
16376        final int scrollY = mScrollY;
16377        if ((scrollX | scrollY) == 0) {
16378            background.draw(canvas);
16379        } else {
16380            canvas.translate(scrollX, scrollY);
16381            background.draw(canvas);
16382            canvas.translate(-scrollX, -scrollY);
16383        }
16384    }
16385
16386    /**
16387     * Sets the correct background bounds and rebuilds the outline, if needed.
16388     * <p/>
16389     * This is called by LayoutLib.
16390     */
16391    void setBackgroundBounds() {
16392        if (mBackgroundSizeChanged && mBackground != null) {
16393            mBackground.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
16394            mBackgroundSizeChanged = false;
16395            rebuildOutline();
16396        }
16397    }
16398
16399    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
16400        renderNode.setTranslationX(mScrollX);
16401        renderNode.setTranslationY(mScrollY);
16402    }
16403
16404    /**
16405     * Creates a new display list or updates the existing display list for the
16406     * specified Drawable.
16407     *
16408     * @param drawable Drawable for which to create a display list
16409     * @param renderNode Existing RenderNode, or {@code null}
16410     * @return A valid display list for the specified drawable
16411     */
16412    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
16413        if (renderNode == null) {
16414            renderNode = RenderNode.create(drawable.getClass().getName(), this);
16415        }
16416
16417        final Rect bounds = drawable.getBounds();
16418        final int width = bounds.width();
16419        final int height = bounds.height();
16420        final DisplayListCanvas canvas = renderNode.start(width, height);
16421
16422        // Reverse left/top translation done by drawable canvas, which will
16423        // instead be applied by rendernode's LTRB bounds below. This way, the
16424        // drawable's bounds match with its rendernode bounds and its content
16425        // will lie within those bounds in the rendernode tree.
16426        canvas.translate(-bounds.left, -bounds.top);
16427
16428        try {
16429            drawable.draw(canvas);
16430        } finally {
16431            renderNode.end(canvas);
16432        }
16433
16434        // Set up drawable properties that are view-independent.
16435        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
16436        renderNode.setProjectBackwards(drawable.isProjected());
16437        renderNode.setProjectionReceiver(true);
16438        renderNode.setClipToBounds(false);
16439        return renderNode;
16440    }
16441
16442    /**
16443     * Returns the overlay for this view, creating it if it does not yet exist.
16444     * Adding drawables to the overlay will cause them to be displayed whenever
16445     * the view itself is redrawn. Objects in the overlay should be actively
16446     * managed: remove them when they should not be displayed anymore. The
16447     * overlay will always have the same size as its host view.
16448     *
16449     * <p>Note: Overlays do not currently work correctly with {@link
16450     * SurfaceView} or {@link TextureView}; contents in overlays for these
16451     * types of views may not display correctly.</p>
16452     *
16453     * @return The ViewOverlay object for this view.
16454     * @see ViewOverlay
16455     */
16456    public ViewOverlay getOverlay() {
16457        if (mOverlay == null) {
16458            mOverlay = new ViewOverlay(mContext, this);
16459        }
16460        return mOverlay;
16461    }
16462
16463    /**
16464     * Override this if your view is known to always be drawn on top of a solid color background,
16465     * and needs to draw fading edges. Returning a non-zero color enables the view system to
16466     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
16467     * should be set to 0xFF.
16468     *
16469     * @see #setVerticalFadingEdgeEnabled(boolean)
16470     * @see #setHorizontalFadingEdgeEnabled(boolean)
16471     *
16472     * @return The known solid color background for this view, or 0 if the color may vary
16473     */
16474    @ViewDebug.ExportedProperty(category = "drawing")
16475    @ColorInt
16476    public int getSolidColor() {
16477        return 0;
16478    }
16479
16480    /**
16481     * Build a human readable string representation of the specified view flags.
16482     *
16483     * @param flags the view flags to convert to a string
16484     * @return a String representing the supplied flags
16485     */
16486    private static String printFlags(int flags) {
16487        String output = "";
16488        int numFlags = 0;
16489        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
16490            output += "TAKES_FOCUS";
16491            numFlags++;
16492        }
16493
16494        switch (flags & VISIBILITY_MASK) {
16495        case INVISIBLE:
16496            if (numFlags > 0) {
16497                output += " ";
16498            }
16499            output += "INVISIBLE";
16500            // USELESS HERE numFlags++;
16501            break;
16502        case GONE:
16503            if (numFlags > 0) {
16504                output += " ";
16505            }
16506            output += "GONE";
16507            // USELESS HERE numFlags++;
16508            break;
16509        default:
16510            break;
16511        }
16512        return output;
16513    }
16514
16515    /**
16516     * Build a human readable string representation of the specified private
16517     * view flags.
16518     *
16519     * @param privateFlags the private view flags to convert to a string
16520     * @return a String representing the supplied flags
16521     */
16522    private static String printPrivateFlags(int privateFlags) {
16523        String output = "";
16524        int numFlags = 0;
16525
16526        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
16527            output += "WANTS_FOCUS";
16528            numFlags++;
16529        }
16530
16531        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
16532            if (numFlags > 0) {
16533                output += " ";
16534            }
16535            output += "FOCUSED";
16536            numFlags++;
16537        }
16538
16539        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
16540            if (numFlags > 0) {
16541                output += " ";
16542            }
16543            output += "SELECTED";
16544            numFlags++;
16545        }
16546
16547        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
16548            if (numFlags > 0) {
16549                output += " ";
16550            }
16551            output += "IS_ROOT_NAMESPACE";
16552            numFlags++;
16553        }
16554
16555        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
16556            if (numFlags > 0) {
16557                output += " ";
16558            }
16559            output += "HAS_BOUNDS";
16560            numFlags++;
16561        }
16562
16563        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
16564            if (numFlags > 0) {
16565                output += " ";
16566            }
16567            output += "DRAWN";
16568            // USELESS HERE numFlags++;
16569        }
16570        return output;
16571    }
16572
16573    /**
16574     * <p>Indicates whether or not this view's layout will be requested during
16575     * the next hierarchy layout pass.</p>
16576     *
16577     * @return true if the layout will be forced during next layout pass
16578     */
16579    public boolean isLayoutRequested() {
16580        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
16581    }
16582
16583    /**
16584     * Return true if o is a ViewGroup that is laying out using optical bounds.
16585     * @hide
16586     */
16587    public static boolean isLayoutModeOptical(Object o) {
16588        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
16589    }
16590
16591    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
16592        Insets parentInsets = mParent instanceof View ?
16593                ((View) mParent).getOpticalInsets() : Insets.NONE;
16594        Insets childInsets = getOpticalInsets();
16595        return setFrame(
16596                left   + parentInsets.left - childInsets.left,
16597                top    + parentInsets.top  - childInsets.top,
16598                right  + parentInsets.left + childInsets.right,
16599                bottom + parentInsets.top  + childInsets.bottom);
16600    }
16601
16602    /**
16603     * Assign a size and position to a view and all of its
16604     * descendants
16605     *
16606     * <p>This is the second phase of the layout mechanism.
16607     * (The first is measuring). In this phase, each parent calls
16608     * layout on all of its children to position them.
16609     * This is typically done using the child measurements
16610     * that were stored in the measure pass().</p>
16611     *
16612     * <p>Derived classes should not override this method.
16613     * Derived classes with children should override
16614     * onLayout. In that method, they should
16615     * call layout on each of their children.</p>
16616     *
16617     * @param l Left position, relative to parent
16618     * @param t Top position, relative to parent
16619     * @param r Right position, relative to parent
16620     * @param b Bottom position, relative to parent
16621     */
16622    @SuppressWarnings({"unchecked"})
16623    public void layout(int l, int t, int r, int b) {
16624        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
16625            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
16626            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16627        }
16628
16629        int oldL = mLeft;
16630        int oldT = mTop;
16631        int oldB = mBottom;
16632        int oldR = mRight;
16633
16634        boolean changed = isLayoutModeOptical(mParent) ?
16635                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
16636
16637        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
16638            onLayout(changed, l, t, r, b);
16639            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
16640
16641            ListenerInfo li = mListenerInfo;
16642            if (li != null && li.mOnLayoutChangeListeners != null) {
16643                ArrayList<OnLayoutChangeListener> listenersCopy =
16644                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16645                int numListeners = listenersCopy.size();
16646                for (int i = 0; i < numListeners; ++i) {
16647                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16648                }
16649            }
16650        }
16651
16652        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16653        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16654    }
16655
16656    /**
16657     * Called from layout when this view should
16658     * assign a size and position to each of its children.
16659     *
16660     * Derived classes with children should override
16661     * this method and call layout on each of
16662     * their children.
16663     * @param changed This is a new size or position for this view
16664     * @param left Left position, relative to parent
16665     * @param top Top position, relative to parent
16666     * @param right Right position, relative to parent
16667     * @param bottom Bottom position, relative to parent
16668     */
16669    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16670    }
16671
16672    /**
16673     * Assign a size and position to this view.
16674     *
16675     * This is called from layout.
16676     *
16677     * @param left Left position, relative to parent
16678     * @param top Top position, relative to parent
16679     * @param right Right position, relative to parent
16680     * @param bottom Bottom position, relative to parent
16681     * @return true if the new size and position are different than the
16682     *         previous ones
16683     * {@hide}
16684     */
16685    protected boolean setFrame(int left, int top, int right, int bottom) {
16686        boolean changed = false;
16687
16688        if (DBG) {
16689            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16690                    + right + "," + bottom + ")");
16691        }
16692
16693        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16694            changed = true;
16695
16696            // Remember our drawn bit
16697            int drawn = mPrivateFlags & PFLAG_DRAWN;
16698
16699            int oldWidth = mRight - mLeft;
16700            int oldHeight = mBottom - mTop;
16701            int newWidth = right - left;
16702            int newHeight = bottom - top;
16703            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16704
16705            // Invalidate our old position
16706            invalidate(sizeChanged);
16707
16708            mLeft = left;
16709            mTop = top;
16710            mRight = right;
16711            mBottom = bottom;
16712            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16713
16714            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16715
16716
16717            if (sizeChanged) {
16718                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16719            }
16720
16721            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16722                // If we are visible, force the DRAWN bit to on so that
16723                // this invalidate will go through (at least to our parent).
16724                // This is because someone may have invalidated this view
16725                // before this call to setFrame came in, thereby clearing
16726                // the DRAWN bit.
16727                mPrivateFlags |= PFLAG_DRAWN;
16728                invalidate(sizeChanged);
16729                // parent display list may need to be recreated based on a change in the bounds
16730                // of any child
16731                invalidateParentCaches();
16732            }
16733
16734            // Reset drawn bit to original value (invalidate turns it off)
16735            mPrivateFlags |= drawn;
16736
16737            mBackgroundSizeChanged = true;
16738            if (mForegroundInfo != null) {
16739                mForegroundInfo.mBoundsChanged = true;
16740            }
16741
16742            notifySubtreeAccessibilityStateChangedIfNeeded();
16743        }
16744        return changed;
16745    }
16746
16747    /**
16748     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16749     * @hide
16750     */
16751    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16752        setFrame(left, top, right, bottom);
16753    }
16754
16755    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16756        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16757        if (mOverlay != null) {
16758            mOverlay.getOverlayView().setRight(newWidth);
16759            mOverlay.getOverlayView().setBottom(newHeight);
16760        }
16761        rebuildOutline();
16762    }
16763
16764    /**
16765     * Finalize inflating a view from XML.  This is called as the last phase
16766     * of inflation, after all child views have been added.
16767     *
16768     * <p>Even if the subclass overrides onFinishInflate, they should always be
16769     * sure to call the super method, so that we get called.
16770     */
16771    @CallSuper
16772    protected void onFinishInflate() {
16773    }
16774
16775    /**
16776     * Returns the resources associated with this view.
16777     *
16778     * @return Resources object.
16779     */
16780    public Resources getResources() {
16781        return mResources;
16782    }
16783
16784    /**
16785     * Invalidates the specified Drawable.
16786     *
16787     * @param drawable the drawable to invalidate
16788     */
16789    @Override
16790    public void invalidateDrawable(@NonNull Drawable drawable) {
16791        if (verifyDrawable(drawable)) {
16792            final Rect dirty = drawable.getDirtyBounds();
16793            final int scrollX = mScrollX;
16794            final int scrollY = mScrollY;
16795
16796            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16797                    dirty.right + scrollX, dirty.bottom + scrollY);
16798            rebuildOutline();
16799        }
16800    }
16801
16802    /**
16803     * Schedules an action on a drawable to occur at a specified time.
16804     *
16805     * @param who the recipient of the action
16806     * @param what the action to run on the drawable
16807     * @param when the time at which the action must occur. Uses the
16808     *        {@link SystemClock#uptimeMillis} timebase.
16809     */
16810    @Override
16811    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16812        if (verifyDrawable(who) && what != null) {
16813            final long delay = when - SystemClock.uptimeMillis();
16814            if (mAttachInfo != null) {
16815                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16816                        Choreographer.CALLBACK_ANIMATION, what, who,
16817                        Choreographer.subtractFrameDelay(delay));
16818            } else {
16819                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16820            }
16821        }
16822    }
16823
16824    /**
16825     * Cancels a scheduled action on a drawable.
16826     *
16827     * @param who the recipient of the action
16828     * @param what the action to cancel
16829     */
16830    @Override
16831    public void unscheduleDrawable(Drawable who, Runnable what) {
16832        if (verifyDrawable(who) && what != null) {
16833            if (mAttachInfo != null) {
16834                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16835                        Choreographer.CALLBACK_ANIMATION, what, who);
16836            }
16837            ViewRootImpl.getRunQueue().removeCallbacks(what);
16838        }
16839    }
16840
16841    /**
16842     * Unschedule any events associated with the given Drawable.  This can be
16843     * used when selecting a new Drawable into a view, so that the previous
16844     * one is completely unscheduled.
16845     *
16846     * @param who The Drawable to unschedule.
16847     *
16848     * @see #drawableStateChanged
16849     */
16850    public void unscheduleDrawable(Drawable who) {
16851        if (mAttachInfo != null && who != null) {
16852            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16853                    Choreographer.CALLBACK_ANIMATION, null, who);
16854        }
16855    }
16856
16857    /**
16858     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16859     * that the View directionality can and will be resolved before its Drawables.
16860     *
16861     * Will call {@link View#onResolveDrawables} when resolution is done.
16862     *
16863     * @hide
16864     */
16865    protected void resolveDrawables() {
16866        // Drawables resolution may need to happen before resolving the layout direction (which is
16867        // done only during the measure() call).
16868        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16869        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16870        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16871        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16872        // direction to be resolved as its resolved value will be the same as its raw value.
16873        if (!isLayoutDirectionResolved() &&
16874                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16875            return;
16876        }
16877
16878        final int layoutDirection = isLayoutDirectionResolved() ?
16879                getLayoutDirection() : getRawLayoutDirection();
16880
16881        if (mBackground != null) {
16882            mBackground.setLayoutDirection(layoutDirection);
16883        }
16884        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16885            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16886        }
16887        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16888        onResolveDrawables(layoutDirection);
16889    }
16890
16891    boolean areDrawablesResolved() {
16892        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16893    }
16894
16895    /**
16896     * Called when layout direction has been resolved.
16897     *
16898     * The default implementation does nothing.
16899     *
16900     * @param layoutDirection The resolved layout direction.
16901     *
16902     * @see #LAYOUT_DIRECTION_LTR
16903     * @see #LAYOUT_DIRECTION_RTL
16904     *
16905     * @hide
16906     */
16907    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16908    }
16909
16910    /**
16911     * @hide
16912     */
16913    protected void resetResolvedDrawables() {
16914        resetResolvedDrawablesInternal();
16915    }
16916
16917    void resetResolvedDrawablesInternal() {
16918        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16919    }
16920
16921    /**
16922     * If your view subclass is displaying its own Drawable objects, it should
16923     * override this function and return true for any Drawable it is
16924     * displaying.  This allows animations for those drawables to be
16925     * scheduled.
16926     *
16927     * <p>Be sure to call through to the super class when overriding this
16928     * function.
16929     *
16930     * @param who The Drawable to verify.  Return true if it is one you are
16931     *            displaying, else return the result of calling through to the
16932     *            super class.
16933     *
16934     * @return boolean If true than the Drawable is being displayed in the
16935     *         view; else false and it is not allowed to animate.
16936     *
16937     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16938     * @see #drawableStateChanged()
16939     */
16940    @CallSuper
16941    protected boolean verifyDrawable(Drawable who) {
16942        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16943                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16944    }
16945
16946    /**
16947     * This function is called whenever the state of the view changes in such
16948     * a way that it impacts the state of drawables being shown.
16949     * <p>
16950     * If the View has a StateListAnimator, it will also be called to run necessary state
16951     * change animations.
16952     * <p>
16953     * Be sure to call through to the superclass when overriding this function.
16954     *
16955     * @see Drawable#setState(int[])
16956     */
16957    @CallSuper
16958    protected void drawableStateChanged() {
16959        final int[] state = getDrawableState();
16960
16961        final Drawable bg = mBackground;
16962        if (bg != null && bg.isStateful()) {
16963            bg.setState(state);
16964        }
16965
16966        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16967        if (fg != null && fg.isStateful()) {
16968            fg.setState(state);
16969        }
16970
16971        if (mScrollCache != null) {
16972            final Drawable scrollBar = mScrollCache.scrollBar;
16973            if (scrollBar != null && scrollBar.isStateful()) {
16974                scrollBar.setState(state);
16975            }
16976        }
16977
16978        if (mStateListAnimator != null) {
16979            mStateListAnimator.setState(state);
16980        }
16981    }
16982
16983    /**
16984     * This function is called whenever the view hotspot changes and needs to
16985     * be propagated to drawables or child views managed by the view.
16986     * <p>
16987     * Dispatching to child views is handled by
16988     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16989     * <p>
16990     * Be sure to call through to the superclass when overriding this function.
16991     *
16992     * @param x hotspot x coordinate
16993     * @param y hotspot y coordinate
16994     */
16995    @CallSuper
16996    public void drawableHotspotChanged(float x, float y) {
16997        if (mBackground != null) {
16998            mBackground.setHotspot(x, y);
16999        }
17000        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17001            mForegroundInfo.mDrawable.setHotspot(x, y);
17002        }
17003
17004        dispatchDrawableHotspotChanged(x, y);
17005    }
17006
17007    /**
17008     * Dispatches drawableHotspotChanged to all of this View's children.
17009     *
17010     * @param x hotspot x coordinate
17011     * @param y hotspot y coordinate
17012     * @see #drawableHotspotChanged(float, float)
17013     */
17014    public void dispatchDrawableHotspotChanged(float x, float y) {
17015    }
17016
17017    /**
17018     * Call this to force a view to update its drawable state. This will cause
17019     * drawableStateChanged to be called on this view. Views that are interested
17020     * in the new state should call getDrawableState.
17021     *
17022     * @see #drawableStateChanged
17023     * @see #getDrawableState
17024     */
17025    public void refreshDrawableState() {
17026        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17027        drawableStateChanged();
17028
17029        ViewParent parent = mParent;
17030        if (parent != null) {
17031            parent.childDrawableStateChanged(this);
17032        }
17033    }
17034
17035    /**
17036     * Return an array of resource IDs of the drawable states representing the
17037     * current state of the view.
17038     *
17039     * @return The current drawable state
17040     *
17041     * @see Drawable#setState(int[])
17042     * @see #drawableStateChanged()
17043     * @see #onCreateDrawableState(int)
17044     */
17045    public final int[] getDrawableState() {
17046        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17047            return mDrawableState;
17048        } else {
17049            mDrawableState = onCreateDrawableState(0);
17050            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17051            return mDrawableState;
17052        }
17053    }
17054
17055    /**
17056     * Generate the new {@link android.graphics.drawable.Drawable} state for
17057     * this view. This is called by the view
17058     * system when the cached Drawable state is determined to be invalid.  To
17059     * retrieve the current state, you should use {@link #getDrawableState}.
17060     *
17061     * @param extraSpace if non-zero, this is the number of extra entries you
17062     * would like in the returned array in which you can place your own
17063     * states.
17064     *
17065     * @return Returns an array holding the current {@link Drawable} state of
17066     * the view.
17067     *
17068     * @see #mergeDrawableStates(int[], int[])
17069     */
17070    protected int[] onCreateDrawableState(int extraSpace) {
17071        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17072                mParent instanceof View) {
17073            return ((View) mParent).onCreateDrawableState(extraSpace);
17074        }
17075
17076        int[] drawableState;
17077
17078        int privateFlags = mPrivateFlags;
17079
17080        int viewStateIndex = 0;
17081        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17082        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17083        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17084        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17085        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17086        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17087        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17088                HardwareRenderer.isAvailable()) {
17089            // This is set if HW acceleration is requested, even if the current
17090            // process doesn't allow it.  This is just to allow app preview
17091            // windows to better match their app.
17092            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17093        }
17094        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17095
17096        final int privateFlags2 = mPrivateFlags2;
17097        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17098            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17099        }
17100        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17101            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17102        }
17103
17104        drawableState = StateSet.get(viewStateIndex);
17105
17106        //noinspection ConstantIfStatement
17107        if (false) {
17108            Log.i("View", "drawableStateIndex=" + viewStateIndex);
17109            Log.i("View", toString()
17110                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
17111                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
17112                    + " fo=" + hasFocus()
17113                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
17114                    + " wf=" + hasWindowFocus()
17115                    + ": " + Arrays.toString(drawableState));
17116        }
17117
17118        if (extraSpace == 0) {
17119            return drawableState;
17120        }
17121
17122        final int[] fullState;
17123        if (drawableState != null) {
17124            fullState = new int[drawableState.length + extraSpace];
17125            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
17126        } else {
17127            fullState = new int[extraSpace];
17128        }
17129
17130        return fullState;
17131    }
17132
17133    /**
17134     * Merge your own state values in <var>additionalState</var> into the base
17135     * state values <var>baseState</var> that were returned by
17136     * {@link #onCreateDrawableState(int)}.
17137     *
17138     * @param baseState The base state values returned by
17139     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
17140     * own additional state values.
17141     *
17142     * @param additionalState The additional state values you would like
17143     * added to <var>baseState</var>; this array is not modified.
17144     *
17145     * @return As a convenience, the <var>baseState</var> array you originally
17146     * passed into the function is returned.
17147     *
17148     * @see #onCreateDrawableState(int)
17149     */
17150    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
17151        final int N = baseState.length;
17152        int i = N - 1;
17153        while (i >= 0 && baseState[i] == 0) {
17154            i--;
17155        }
17156        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
17157        return baseState;
17158    }
17159
17160    /**
17161     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
17162     * on all Drawable objects associated with this view.
17163     * <p>
17164     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
17165     * attached to this view.
17166     */
17167    @CallSuper
17168    public void jumpDrawablesToCurrentState() {
17169        if (mBackground != null) {
17170            mBackground.jumpToCurrentState();
17171        }
17172        if (mStateListAnimator != null) {
17173            mStateListAnimator.jumpToCurrentState();
17174        }
17175        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17176            mForegroundInfo.mDrawable.jumpToCurrentState();
17177        }
17178    }
17179
17180    /**
17181     * Sets the background color for this view.
17182     * @param color the color of the background
17183     */
17184    @RemotableViewMethod
17185    public void setBackgroundColor(@ColorInt int color) {
17186        if (mBackground instanceof ColorDrawable) {
17187            ((ColorDrawable) mBackground.mutate()).setColor(color);
17188            computeOpaqueFlags();
17189            mBackgroundResource = 0;
17190        } else {
17191            setBackground(new ColorDrawable(color));
17192        }
17193    }
17194
17195    /**
17196     * Set the background to a given resource. The resource should refer to
17197     * a Drawable object or 0 to remove the background.
17198     * @param resid The identifier of the resource.
17199     *
17200     * @attr ref android.R.styleable#View_background
17201     */
17202    @RemotableViewMethod
17203    public void setBackgroundResource(@DrawableRes int resid) {
17204        if (resid != 0 && resid == mBackgroundResource) {
17205            return;
17206        }
17207
17208        Drawable d = null;
17209        if (resid != 0) {
17210            d = mContext.getDrawable(resid);
17211        }
17212        setBackground(d);
17213
17214        mBackgroundResource = resid;
17215    }
17216
17217    /**
17218     * Set the background to a given Drawable, or remove the background. If the
17219     * background has padding, this View's padding is set to the background's
17220     * padding. However, when a background is removed, this View's padding isn't
17221     * touched. If setting the padding is desired, please use
17222     * {@link #setPadding(int, int, int, int)}.
17223     *
17224     * @param background The Drawable to use as the background, or null to remove the
17225     *        background
17226     */
17227    public void setBackground(Drawable background) {
17228        //noinspection deprecation
17229        setBackgroundDrawable(background);
17230    }
17231
17232    /**
17233     * @deprecated use {@link #setBackground(Drawable)} instead
17234     */
17235    @Deprecated
17236    public void setBackgroundDrawable(Drawable background) {
17237        computeOpaqueFlags();
17238
17239        if (background == mBackground) {
17240            return;
17241        }
17242
17243        boolean requestLayout = false;
17244
17245        mBackgroundResource = 0;
17246
17247        /*
17248         * Regardless of whether we're setting a new background or not, we want
17249         * to clear the previous drawable.
17250         */
17251        if (mBackground != null) {
17252            mBackground.setCallback(null);
17253            unscheduleDrawable(mBackground);
17254        }
17255
17256        if (background != null) {
17257            Rect padding = sThreadLocal.get();
17258            if (padding == null) {
17259                padding = new Rect();
17260                sThreadLocal.set(padding);
17261            }
17262            resetResolvedDrawablesInternal();
17263            background.setLayoutDirection(getLayoutDirection());
17264            if (background.getPadding(padding)) {
17265                resetResolvedPaddingInternal();
17266                switch (background.getLayoutDirection()) {
17267                    case LAYOUT_DIRECTION_RTL:
17268                        mUserPaddingLeftInitial = padding.right;
17269                        mUserPaddingRightInitial = padding.left;
17270                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
17271                        break;
17272                    case LAYOUT_DIRECTION_LTR:
17273                    default:
17274                        mUserPaddingLeftInitial = padding.left;
17275                        mUserPaddingRightInitial = padding.right;
17276                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
17277                }
17278                mLeftPaddingDefined = false;
17279                mRightPaddingDefined = false;
17280            }
17281
17282            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
17283            // if it has a different minimum size, we should layout again
17284            if (mBackground == null
17285                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
17286                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
17287                requestLayout = true;
17288            }
17289
17290            background.setCallback(this);
17291            if (background.isStateful()) {
17292                background.setState(getDrawableState());
17293            }
17294            background.setVisible(getVisibility() == VISIBLE, false);
17295            mBackground = background;
17296
17297            applyBackgroundTint();
17298
17299            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
17300                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
17301                requestLayout = true;
17302            }
17303        } else {
17304            /* Remove the background */
17305            mBackground = null;
17306            if ((mViewFlags & WILL_NOT_DRAW) != 0
17307                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
17308                mPrivateFlags |= PFLAG_SKIP_DRAW;
17309            }
17310
17311            /*
17312             * When the background is set, we try to apply its padding to this
17313             * View. When the background is removed, we don't touch this View's
17314             * padding. This is noted in the Javadocs. Hence, we don't need to
17315             * requestLayout(), the invalidate() below is sufficient.
17316             */
17317
17318            // The old background's minimum size could have affected this
17319            // View's layout, so let's requestLayout
17320            requestLayout = true;
17321        }
17322
17323        computeOpaqueFlags();
17324
17325        if (requestLayout) {
17326            requestLayout();
17327        }
17328
17329        mBackgroundSizeChanged = true;
17330        invalidate(true);
17331    }
17332
17333    /**
17334     * Gets the background drawable
17335     *
17336     * @return The drawable used as the background for this view, if any.
17337     *
17338     * @see #setBackground(Drawable)
17339     *
17340     * @attr ref android.R.styleable#View_background
17341     */
17342    public Drawable getBackground() {
17343        return mBackground;
17344    }
17345
17346    /**
17347     * Applies a tint to the background drawable. Does not modify the current tint
17348     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17349     * <p>
17350     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
17351     * mutate the drawable and apply the specified tint and tint mode using
17352     * {@link Drawable#setTintList(ColorStateList)}.
17353     *
17354     * @param tint the tint to apply, may be {@code null} to clear tint
17355     *
17356     * @attr ref android.R.styleable#View_backgroundTint
17357     * @see #getBackgroundTintList()
17358     * @see Drawable#setTintList(ColorStateList)
17359     */
17360    public void setBackgroundTintList(@Nullable ColorStateList tint) {
17361        if (mBackgroundTint == null) {
17362            mBackgroundTint = new TintInfo();
17363        }
17364        mBackgroundTint.mTintList = tint;
17365        mBackgroundTint.mHasTintList = true;
17366
17367        applyBackgroundTint();
17368    }
17369
17370    /**
17371     * Return the tint applied to the background drawable, if specified.
17372     *
17373     * @return the tint applied to the background drawable
17374     * @attr ref android.R.styleable#View_backgroundTint
17375     * @see #setBackgroundTintList(ColorStateList)
17376     */
17377    @Nullable
17378    public ColorStateList getBackgroundTintList() {
17379        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
17380    }
17381
17382    /**
17383     * Specifies the blending mode used to apply the tint specified by
17384     * {@link #setBackgroundTintList(ColorStateList)}} to the background
17385     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17386     *
17387     * @param tintMode the blending mode used to apply the tint, may be
17388     *                 {@code null} to clear tint
17389     * @attr ref android.R.styleable#View_backgroundTintMode
17390     * @see #getBackgroundTintMode()
17391     * @see Drawable#setTintMode(PorterDuff.Mode)
17392     */
17393    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17394        if (mBackgroundTint == null) {
17395            mBackgroundTint = new TintInfo();
17396        }
17397        mBackgroundTint.mTintMode = tintMode;
17398        mBackgroundTint.mHasTintMode = true;
17399
17400        applyBackgroundTint();
17401    }
17402
17403    /**
17404     * Return the blending mode used to apply the tint to the background
17405     * drawable, if specified.
17406     *
17407     * @return the blending mode used to apply the tint to the background
17408     *         drawable
17409     * @attr ref android.R.styleable#View_backgroundTintMode
17410     * @see #setBackgroundTintMode(PorterDuff.Mode)
17411     */
17412    @Nullable
17413    public PorterDuff.Mode getBackgroundTintMode() {
17414        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
17415    }
17416
17417    private void applyBackgroundTint() {
17418        if (mBackground != null && mBackgroundTint != null) {
17419            final TintInfo tintInfo = mBackgroundTint;
17420            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17421                mBackground = mBackground.mutate();
17422
17423                if (tintInfo.mHasTintList) {
17424                    mBackground.setTintList(tintInfo.mTintList);
17425                }
17426
17427                if (tintInfo.mHasTintMode) {
17428                    mBackground.setTintMode(tintInfo.mTintMode);
17429                }
17430
17431                // The drawable (or one of its children) may not have been
17432                // stateful before applying the tint, so let's try again.
17433                if (mBackground.isStateful()) {
17434                    mBackground.setState(getDrawableState());
17435                }
17436            }
17437        }
17438    }
17439
17440    /**
17441     * Returns the drawable used as the foreground of this View. The
17442     * foreground drawable, if non-null, is always drawn on top of the view's content.
17443     *
17444     * @return a Drawable or null if no foreground was set
17445     *
17446     * @see #onDrawForeground(Canvas)
17447     */
17448    public Drawable getForeground() {
17449        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17450    }
17451
17452    /**
17453     * Supply a Drawable that is to be rendered on top of all of the content in the view.
17454     *
17455     * @param foreground the Drawable to be drawn on top of the children
17456     *
17457     * @attr ref android.R.styleable#View_foreground
17458     */
17459    public void setForeground(Drawable foreground) {
17460        if (mForegroundInfo == null) {
17461            if (foreground == null) {
17462                // Nothing to do.
17463                return;
17464            }
17465            mForegroundInfo = new ForegroundInfo();
17466        }
17467
17468        if (foreground == mForegroundInfo.mDrawable) {
17469            // Nothing to do
17470            return;
17471        }
17472
17473        if (mForegroundInfo.mDrawable != null) {
17474            mForegroundInfo.mDrawable.setCallback(null);
17475            unscheduleDrawable(mForegroundInfo.mDrawable);
17476        }
17477
17478        mForegroundInfo.mDrawable = foreground;
17479        mForegroundInfo.mBoundsChanged = true;
17480        if (foreground != null) {
17481            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
17482                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
17483            }
17484            foreground.setCallback(this);
17485            foreground.setLayoutDirection(getLayoutDirection());
17486            if (foreground.isStateful()) {
17487                foreground.setState(getDrawableState());
17488            }
17489            applyForegroundTint();
17490        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
17491            mPrivateFlags |= PFLAG_SKIP_DRAW;
17492        }
17493        requestLayout();
17494        invalidate();
17495    }
17496
17497    /**
17498     * Magic bit used to support features of framework-internal window decor implementation details.
17499     * This used to live exclusively in FrameLayout.
17500     *
17501     * @return true if the foreground should draw inside the padding region or false
17502     *         if it should draw inset by the view's padding
17503     * @hide internal use only; only used by FrameLayout and internal screen layouts.
17504     */
17505    public boolean isForegroundInsidePadding() {
17506        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
17507    }
17508
17509    /**
17510     * Describes how the foreground is positioned.
17511     *
17512     * @return foreground gravity.
17513     *
17514     * @see #setForegroundGravity(int)
17515     *
17516     * @attr ref android.R.styleable#View_foregroundGravity
17517     */
17518    public int getForegroundGravity() {
17519        return mForegroundInfo != null ? mForegroundInfo.mGravity
17520                : Gravity.START | Gravity.TOP;
17521    }
17522
17523    /**
17524     * Describes how the foreground is positioned. Defaults to START and TOP.
17525     *
17526     * @param gravity see {@link android.view.Gravity}
17527     *
17528     * @see #getForegroundGravity()
17529     *
17530     * @attr ref android.R.styleable#View_foregroundGravity
17531     */
17532    public void setForegroundGravity(int gravity) {
17533        if (mForegroundInfo == null) {
17534            mForegroundInfo = new ForegroundInfo();
17535        }
17536
17537        if (mForegroundInfo.mGravity != gravity) {
17538            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
17539                gravity |= Gravity.START;
17540            }
17541
17542            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
17543                gravity |= Gravity.TOP;
17544            }
17545
17546            mForegroundInfo.mGravity = gravity;
17547            requestLayout();
17548        }
17549    }
17550
17551    /**
17552     * Applies a tint to the foreground drawable. Does not modify the current tint
17553     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17554     * <p>
17555     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
17556     * mutate the drawable and apply the specified tint and tint mode using
17557     * {@link Drawable#setTintList(ColorStateList)}.
17558     *
17559     * @param tint the tint to apply, may be {@code null} to clear tint
17560     *
17561     * @attr ref android.R.styleable#View_foregroundTint
17562     * @see #getForegroundTintList()
17563     * @see Drawable#setTintList(ColorStateList)
17564     */
17565    public void setForegroundTintList(@Nullable ColorStateList tint) {
17566        if (mForegroundInfo == null) {
17567            mForegroundInfo = new ForegroundInfo();
17568        }
17569        if (mForegroundInfo.mTintInfo == null) {
17570            mForegroundInfo.mTintInfo = new TintInfo();
17571        }
17572        mForegroundInfo.mTintInfo.mTintList = tint;
17573        mForegroundInfo.mTintInfo.mHasTintList = true;
17574
17575        applyForegroundTint();
17576    }
17577
17578    /**
17579     * Return the tint applied to the foreground drawable, if specified.
17580     *
17581     * @return the tint applied to the foreground drawable
17582     * @attr ref android.R.styleable#View_foregroundTint
17583     * @see #setForegroundTintList(ColorStateList)
17584     */
17585    @Nullable
17586    public ColorStateList getForegroundTintList() {
17587        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17588                ? mForegroundInfo.mTintInfo.mTintList : null;
17589    }
17590
17591    /**
17592     * Specifies the blending mode used to apply the tint specified by
17593     * {@link #setForegroundTintList(ColorStateList)}} to the background
17594     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17595     *
17596     * @param tintMode the blending mode used to apply the tint, may be
17597     *                 {@code null} to clear tint
17598     * @attr ref android.R.styleable#View_foregroundTintMode
17599     * @see #getForegroundTintMode()
17600     * @see Drawable#setTintMode(PorterDuff.Mode)
17601     */
17602    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17603        if (mForegroundInfo == null) {
17604            mForegroundInfo = new ForegroundInfo();
17605        }
17606        if (mForegroundInfo.mTintInfo == null) {
17607            mForegroundInfo.mTintInfo = new TintInfo();
17608        }
17609        mForegroundInfo.mTintInfo.mTintMode = tintMode;
17610        mForegroundInfo.mTintInfo.mHasTintMode = true;
17611
17612        applyForegroundTint();
17613    }
17614
17615    /**
17616     * Return the blending mode used to apply the tint to the foreground
17617     * drawable, if specified.
17618     *
17619     * @return the blending mode used to apply the tint to the foreground
17620     *         drawable
17621     * @attr ref android.R.styleable#View_foregroundTintMode
17622     * @see #setForegroundTintMode(PorterDuff.Mode)
17623     */
17624    @Nullable
17625    public PorterDuff.Mode getForegroundTintMode() {
17626        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17627                ? mForegroundInfo.mTintInfo.mTintMode : null;
17628    }
17629
17630    private void applyForegroundTint() {
17631        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17632                && mForegroundInfo.mTintInfo != null) {
17633            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17634            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17635                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17636
17637                if (tintInfo.mHasTintList) {
17638                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17639                }
17640
17641                if (tintInfo.mHasTintMode) {
17642                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17643                }
17644
17645                // The drawable (or one of its children) may not have been
17646                // stateful before applying the tint, so let's try again.
17647                if (mForegroundInfo.mDrawable.isStateful()) {
17648                    mForegroundInfo.mDrawable.setState(getDrawableState());
17649                }
17650            }
17651        }
17652    }
17653
17654    /**
17655     * Draw any foreground content for this view.
17656     *
17657     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17658     * drawable or other view-specific decorations. The foreground is drawn on top of the
17659     * primary view content.</p>
17660     *
17661     * @param canvas canvas to draw into
17662     */
17663    public void onDrawForeground(Canvas canvas) {
17664        onDrawScrollIndicators(canvas);
17665        onDrawScrollBars(canvas);
17666
17667        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17668        if (foreground != null) {
17669            if (mForegroundInfo.mBoundsChanged) {
17670                mForegroundInfo.mBoundsChanged = false;
17671                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17672                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17673
17674                if (mForegroundInfo.mInsidePadding) {
17675                    selfBounds.set(0, 0, getWidth(), getHeight());
17676                } else {
17677                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17678                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17679                }
17680
17681                final int ld = getLayoutDirection();
17682                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17683                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17684                foreground.setBounds(overlayBounds);
17685            }
17686
17687            foreground.draw(canvas);
17688        }
17689    }
17690
17691    /**
17692     * Sets the padding. The view may add on the space required to display
17693     * the scrollbars, depending on the style and visibility of the scrollbars.
17694     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17695     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17696     * from the values set in this call.
17697     *
17698     * @attr ref android.R.styleable#View_padding
17699     * @attr ref android.R.styleable#View_paddingBottom
17700     * @attr ref android.R.styleable#View_paddingLeft
17701     * @attr ref android.R.styleable#View_paddingRight
17702     * @attr ref android.R.styleable#View_paddingTop
17703     * @param left the left padding in pixels
17704     * @param top the top padding in pixels
17705     * @param right the right padding in pixels
17706     * @param bottom the bottom padding in pixels
17707     */
17708    public void setPadding(int left, int top, int right, int bottom) {
17709        resetResolvedPaddingInternal();
17710
17711        mUserPaddingStart = UNDEFINED_PADDING;
17712        mUserPaddingEnd = UNDEFINED_PADDING;
17713
17714        mUserPaddingLeftInitial = left;
17715        mUserPaddingRightInitial = right;
17716
17717        mLeftPaddingDefined = true;
17718        mRightPaddingDefined = true;
17719
17720        internalSetPadding(left, top, right, bottom);
17721    }
17722
17723    /**
17724     * @hide
17725     */
17726    protected void internalSetPadding(int left, int top, int right, int bottom) {
17727        mUserPaddingLeft = left;
17728        mUserPaddingRight = right;
17729        mUserPaddingBottom = bottom;
17730
17731        final int viewFlags = mViewFlags;
17732        boolean changed = false;
17733
17734        // Common case is there are no scroll bars.
17735        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17736            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17737                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17738                        ? 0 : getVerticalScrollbarWidth();
17739                switch (mVerticalScrollbarPosition) {
17740                    case SCROLLBAR_POSITION_DEFAULT:
17741                        if (isLayoutRtl()) {
17742                            left += offset;
17743                        } else {
17744                            right += offset;
17745                        }
17746                        break;
17747                    case SCROLLBAR_POSITION_RIGHT:
17748                        right += offset;
17749                        break;
17750                    case SCROLLBAR_POSITION_LEFT:
17751                        left += offset;
17752                        break;
17753                }
17754            }
17755            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17756                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17757                        ? 0 : getHorizontalScrollbarHeight();
17758            }
17759        }
17760
17761        if (mPaddingLeft != left) {
17762            changed = true;
17763            mPaddingLeft = left;
17764        }
17765        if (mPaddingTop != top) {
17766            changed = true;
17767            mPaddingTop = top;
17768        }
17769        if (mPaddingRight != right) {
17770            changed = true;
17771            mPaddingRight = right;
17772        }
17773        if (mPaddingBottom != bottom) {
17774            changed = true;
17775            mPaddingBottom = bottom;
17776        }
17777
17778        if (changed) {
17779            requestLayout();
17780            invalidateOutline();
17781        }
17782    }
17783
17784    /**
17785     * Sets the relative padding. The view may add on the space required to display
17786     * the scrollbars, depending on the style and visibility of the scrollbars.
17787     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17788     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17789     * from the values set in this call.
17790     *
17791     * @attr ref android.R.styleable#View_padding
17792     * @attr ref android.R.styleable#View_paddingBottom
17793     * @attr ref android.R.styleable#View_paddingStart
17794     * @attr ref android.R.styleable#View_paddingEnd
17795     * @attr ref android.R.styleable#View_paddingTop
17796     * @param start the start padding in pixels
17797     * @param top the top padding in pixels
17798     * @param end the end padding in pixels
17799     * @param bottom the bottom padding in pixels
17800     */
17801    public void setPaddingRelative(int start, int top, int end, int bottom) {
17802        resetResolvedPaddingInternal();
17803
17804        mUserPaddingStart = start;
17805        mUserPaddingEnd = end;
17806        mLeftPaddingDefined = true;
17807        mRightPaddingDefined = true;
17808
17809        switch(getLayoutDirection()) {
17810            case LAYOUT_DIRECTION_RTL:
17811                mUserPaddingLeftInitial = end;
17812                mUserPaddingRightInitial = start;
17813                internalSetPadding(end, top, start, bottom);
17814                break;
17815            case LAYOUT_DIRECTION_LTR:
17816            default:
17817                mUserPaddingLeftInitial = start;
17818                mUserPaddingRightInitial = end;
17819                internalSetPadding(start, top, end, bottom);
17820        }
17821    }
17822
17823    /**
17824     * Returns the top padding of this view.
17825     *
17826     * @return the top padding in pixels
17827     */
17828    public int getPaddingTop() {
17829        return mPaddingTop;
17830    }
17831
17832    /**
17833     * Returns the bottom padding of this view. If there are inset and enabled
17834     * scrollbars, this value may include the space required to display the
17835     * scrollbars as well.
17836     *
17837     * @return the bottom padding in pixels
17838     */
17839    public int getPaddingBottom() {
17840        return mPaddingBottom;
17841    }
17842
17843    /**
17844     * Returns the left padding of this view. If there are inset and enabled
17845     * scrollbars, this value may include the space required to display the
17846     * scrollbars as well.
17847     *
17848     * @return the left padding in pixels
17849     */
17850    public int getPaddingLeft() {
17851        if (!isPaddingResolved()) {
17852            resolvePadding();
17853        }
17854        return mPaddingLeft;
17855    }
17856
17857    /**
17858     * Returns the start padding of this view depending on its resolved layout direction.
17859     * If there are inset and enabled scrollbars, this value may include the space
17860     * required to display the scrollbars as well.
17861     *
17862     * @return the start padding in pixels
17863     */
17864    public int getPaddingStart() {
17865        if (!isPaddingResolved()) {
17866            resolvePadding();
17867        }
17868        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17869                mPaddingRight : mPaddingLeft;
17870    }
17871
17872    /**
17873     * Returns the right padding of this view. If there are inset and enabled
17874     * scrollbars, this value may include the space required to display the
17875     * scrollbars as well.
17876     *
17877     * @return the right padding in pixels
17878     */
17879    public int getPaddingRight() {
17880        if (!isPaddingResolved()) {
17881            resolvePadding();
17882        }
17883        return mPaddingRight;
17884    }
17885
17886    /**
17887     * Returns the end padding of this view depending on its resolved layout direction.
17888     * If there are inset and enabled scrollbars, this value may include the space
17889     * required to display the scrollbars as well.
17890     *
17891     * @return the end padding in pixels
17892     */
17893    public int getPaddingEnd() {
17894        if (!isPaddingResolved()) {
17895            resolvePadding();
17896        }
17897        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17898                mPaddingLeft : mPaddingRight;
17899    }
17900
17901    /**
17902     * Return if the padding has been set through relative values
17903     * {@link #setPaddingRelative(int, int, int, int)} or through
17904     * @attr ref android.R.styleable#View_paddingStart or
17905     * @attr ref android.R.styleable#View_paddingEnd
17906     *
17907     * @return true if the padding is relative or false if it is not.
17908     */
17909    public boolean isPaddingRelative() {
17910        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17911    }
17912
17913    Insets computeOpticalInsets() {
17914        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17915    }
17916
17917    /**
17918     * @hide
17919     */
17920    public void resetPaddingToInitialValues() {
17921        if (isRtlCompatibilityMode()) {
17922            mPaddingLeft = mUserPaddingLeftInitial;
17923            mPaddingRight = mUserPaddingRightInitial;
17924            return;
17925        }
17926        if (isLayoutRtl()) {
17927            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17928            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17929        } else {
17930            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17931            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17932        }
17933    }
17934
17935    /**
17936     * @hide
17937     */
17938    public Insets getOpticalInsets() {
17939        if (mLayoutInsets == null) {
17940            mLayoutInsets = computeOpticalInsets();
17941        }
17942        return mLayoutInsets;
17943    }
17944
17945    /**
17946     * Set this view's optical insets.
17947     *
17948     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17949     * property. Views that compute their own optical insets should call it as part of measurement.
17950     * This method does not request layout. If you are setting optical insets outside of
17951     * measure/layout itself you will want to call requestLayout() yourself.
17952     * </p>
17953     * @hide
17954     */
17955    public void setOpticalInsets(Insets insets) {
17956        mLayoutInsets = insets;
17957    }
17958
17959    /**
17960     * Changes the selection state of this view. A view can be selected or not.
17961     * Note that selection is not the same as focus. Views are typically
17962     * selected in the context of an AdapterView like ListView or GridView;
17963     * the selected view is the view that is highlighted.
17964     *
17965     * @param selected true if the view must be selected, false otherwise
17966     */
17967    public void setSelected(boolean selected) {
17968        //noinspection DoubleNegation
17969        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17970            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17971            if (!selected) resetPressedState();
17972            invalidate(true);
17973            refreshDrawableState();
17974            dispatchSetSelected(selected);
17975            if (selected) {
17976                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17977            } else {
17978                notifyViewAccessibilityStateChangedIfNeeded(
17979                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17980            }
17981        }
17982    }
17983
17984    /**
17985     * Dispatch setSelected to all of this View's children.
17986     *
17987     * @see #setSelected(boolean)
17988     *
17989     * @param selected The new selected state
17990     */
17991    protected void dispatchSetSelected(boolean selected) {
17992    }
17993
17994    /**
17995     * Indicates the selection state of this view.
17996     *
17997     * @return true if the view is selected, false otherwise
17998     */
17999    @ViewDebug.ExportedProperty
18000    public boolean isSelected() {
18001        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18002    }
18003
18004    /**
18005     * Changes the activated state of this view. A view can be activated or not.
18006     * Note that activation is not the same as selection.  Selection is
18007     * a transient property, representing the view (hierarchy) the user is
18008     * currently interacting with.  Activation is a longer-term state that the
18009     * user can move views in and out of.  For example, in a list view with
18010     * single or multiple selection enabled, the views in the current selection
18011     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18012     * here.)  The activated state is propagated down to children of the view it
18013     * is set on.
18014     *
18015     * @param activated true if the view must be activated, false otherwise
18016     */
18017    public void setActivated(boolean activated) {
18018        //noinspection DoubleNegation
18019        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18020            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18021            invalidate(true);
18022            refreshDrawableState();
18023            dispatchSetActivated(activated);
18024        }
18025    }
18026
18027    /**
18028     * Dispatch setActivated to all of this View's children.
18029     *
18030     * @see #setActivated(boolean)
18031     *
18032     * @param activated The new activated state
18033     */
18034    protected void dispatchSetActivated(boolean activated) {
18035    }
18036
18037    /**
18038     * Indicates the activation state of this view.
18039     *
18040     * @return true if the view is activated, false otherwise
18041     */
18042    @ViewDebug.ExportedProperty
18043    public boolean isActivated() {
18044        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18045    }
18046
18047    /**
18048     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18049     * observer can be used to get notifications when global events, like
18050     * layout, happen.
18051     *
18052     * The returned ViewTreeObserver observer is not guaranteed to remain
18053     * valid for the lifetime of this View. If the caller of this method keeps
18054     * a long-lived reference to ViewTreeObserver, it should always check for
18055     * the return value of {@link ViewTreeObserver#isAlive()}.
18056     *
18057     * @return The ViewTreeObserver for this view's hierarchy.
18058     */
18059    public ViewTreeObserver getViewTreeObserver() {
18060        if (mAttachInfo != null) {
18061            return mAttachInfo.mTreeObserver;
18062        }
18063        if (mFloatingTreeObserver == null) {
18064            mFloatingTreeObserver = new ViewTreeObserver();
18065        }
18066        return mFloatingTreeObserver;
18067    }
18068
18069    /**
18070     * <p>Finds the topmost view in the current view hierarchy.</p>
18071     *
18072     * @return the topmost view containing this view
18073     */
18074    public View getRootView() {
18075        if (mAttachInfo != null) {
18076            final View v = mAttachInfo.mRootView;
18077            if (v != null) {
18078                return v;
18079            }
18080        }
18081
18082        View parent = this;
18083
18084        while (parent.mParent != null && parent.mParent instanceof View) {
18085            parent = (View) parent.mParent;
18086        }
18087
18088        return parent;
18089    }
18090
18091    /**
18092     * Transforms a motion event from view-local coordinates to on-screen
18093     * coordinates.
18094     *
18095     * @param ev the view-local motion event
18096     * @return false if the transformation could not be applied
18097     * @hide
18098     */
18099    public boolean toGlobalMotionEvent(MotionEvent ev) {
18100        final AttachInfo info = mAttachInfo;
18101        if (info == null) {
18102            return false;
18103        }
18104
18105        final Matrix m = info.mTmpMatrix;
18106        m.set(Matrix.IDENTITY_MATRIX);
18107        transformMatrixToGlobal(m);
18108        ev.transform(m);
18109        return true;
18110    }
18111
18112    /**
18113     * Transforms a motion event from on-screen coordinates to view-local
18114     * coordinates.
18115     *
18116     * @param ev the on-screen motion event
18117     * @return false if the transformation could not be applied
18118     * @hide
18119     */
18120    public boolean toLocalMotionEvent(MotionEvent ev) {
18121        final AttachInfo info = mAttachInfo;
18122        if (info == null) {
18123            return false;
18124        }
18125
18126        final Matrix m = info.mTmpMatrix;
18127        m.set(Matrix.IDENTITY_MATRIX);
18128        transformMatrixToLocal(m);
18129        ev.transform(m);
18130        return true;
18131    }
18132
18133    /**
18134     * Modifies the input matrix such that it maps view-local coordinates to
18135     * on-screen coordinates.
18136     *
18137     * @param m input matrix to modify
18138     * @hide
18139     */
18140    public void transformMatrixToGlobal(Matrix m) {
18141        final ViewParent parent = mParent;
18142        if (parent instanceof View) {
18143            final View vp = (View) parent;
18144            vp.transformMatrixToGlobal(m);
18145            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
18146        } else if (parent instanceof ViewRootImpl) {
18147            final ViewRootImpl vr = (ViewRootImpl) parent;
18148            vr.transformMatrixToGlobal(m);
18149            m.preTranslate(0, -vr.mCurScrollY);
18150        }
18151
18152        m.preTranslate(mLeft, mTop);
18153
18154        if (!hasIdentityMatrix()) {
18155            m.preConcat(getMatrix());
18156        }
18157    }
18158
18159    /**
18160     * Modifies the input matrix such that it maps on-screen coordinates to
18161     * view-local coordinates.
18162     *
18163     * @param m input matrix to modify
18164     * @hide
18165     */
18166    public void transformMatrixToLocal(Matrix m) {
18167        final ViewParent parent = mParent;
18168        if (parent instanceof View) {
18169            final View vp = (View) parent;
18170            vp.transformMatrixToLocal(m);
18171            m.postTranslate(vp.mScrollX, vp.mScrollY);
18172        } else if (parent instanceof ViewRootImpl) {
18173            final ViewRootImpl vr = (ViewRootImpl) parent;
18174            vr.transformMatrixToLocal(m);
18175            m.postTranslate(0, vr.mCurScrollY);
18176        }
18177
18178        m.postTranslate(-mLeft, -mTop);
18179
18180        if (!hasIdentityMatrix()) {
18181            m.postConcat(getInverseMatrix());
18182        }
18183    }
18184
18185    /**
18186     * @hide
18187     */
18188    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
18189            @ViewDebug.IntToString(from = 0, to = "x"),
18190            @ViewDebug.IntToString(from = 1, to = "y")
18191    })
18192    public int[] getLocationOnScreen() {
18193        int[] location = new int[2];
18194        getLocationOnScreen(location);
18195        return location;
18196    }
18197
18198    /**
18199     * <p>Computes the coordinates of this view on the screen. The argument
18200     * must be an array of two integers. After the method returns, the array
18201     * contains the x and y location in that order.</p>
18202     *
18203     * @param location an array of two integers in which to hold the coordinates
18204     */
18205    public void getLocationOnScreen(@Size(2) int[] location) {
18206        getLocationInWindow(location);
18207
18208        final AttachInfo info = mAttachInfo;
18209        if (info != null) {
18210            location[0] += info.mWindowLeft;
18211            location[1] += info.mWindowTop;
18212        }
18213    }
18214
18215    /**
18216     * <p>Computes the coordinates of this view in its window. The argument
18217     * must be an array of two integers. After the method returns, the array
18218     * contains the x and y location in that order.</p>
18219     *
18220     * @param location an array of two integers in which to hold the coordinates
18221     */
18222    public void getLocationInWindow(@Size(2) int[] location) {
18223        if (location == null || location.length < 2) {
18224            throw new IllegalArgumentException("location must be an array of two integers");
18225        }
18226
18227        if (mAttachInfo == null) {
18228            // When the view is not attached to a window, this method does not make sense
18229            location[0] = location[1] = 0;
18230            return;
18231        }
18232
18233        float[] position = mAttachInfo.mTmpTransformLocation;
18234        position[0] = position[1] = 0.0f;
18235
18236        if (!hasIdentityMatrix()) {
18237            getMatrix().mapPoints(position);
18238        }
18239
18240        position[0] += mLeft;
18241        position[1] += mTop;
18242
18243        ViewParent viewParent = mParent;
18244        while (viewParent instanceof View) {
18245            final View view = (View) viewParent;
18246
18247            position[0] -= view.mScrollX;
18248            position[1] -= view.mScrollY;
18249
18250            if (!view.hasIdentityMatrix()) {
18251                view.getMatrix().mapPoints(position);
18252            }
18253
18254            position[0] += view.mLeft;
18255            position[1] += view.mTop;
18256
18257            viewParent = view.mParent;
18258         }
18259
18260        if (viewParent instanceof ViewRootImpl) {
18261            // *cough*
18262            final ViewRootImpl vr = (ViewRootImpl) viewParent;
18263            position[1] -= vr.mCurScrollY;
18264        }
18265
18266        location[0] = (int) (position[0] + 0.5f);
18267        location[1] = (int) (position[1] + 0.5f);
18268    }
18269
18270    /**
18271     * {@hide}
18272     * @param id the id of the view to be found
18273     * @return the view of the specified id, null if cannot be found
18274     */
18275    protected View findViewTraversal(@IdRes int id) {
18276        if (id == mID) {
18277            return this;
18278        }
18279        return null;
18280    }
18281
18282    /**
18283     * {@hide}
18284     * @param tag the tag of the view to be found
18285     * @return the view of specified tag, null if cannot be found
18286     */
18287    protected View findViewWithTagTraversal(Object tag) {
18288        if (tag != null && tag.equals(mTag)) {
18289            return this;
18290        }
18291        return null;
18292    }
18293
18294    /**
18295     * {@hide}
18296     * @param predicate The predicate to evaluate.
18297     * @param childToSkip If not null, ignores this child during the recursive traversal.
18298     * @return The first view that matches the predicate or null.
18299     */
18300    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
18301        if (predicate.apply(this)) {
18302            return this;
18303        }
18304        return null;
18305    }
18306
18307    /**
18308     * Look for a child view with the given id.  If this view has the given
18309     * id, return this view.
18310     *
18311     * @param id The id to search for.
18312     * @return The view that has the given id in the hierarchy or null
18313     */
18314    @Nullable
18315    public final View findViewById(@IdRes int id) {
18316        if (id < 0) {
18317            return null;
18318        }
18319        return findViewTraversal(id);
18320    }
18321
18322    /**
18323     * Finds a view by its unuque and stable accessibility id.
18324     *
18325     * @param accessibilityId The searched accessibility id.
18326     * @return The found view.
18327     */
18328    final View findViewByAccessibilityId(int accessibilityId) {
18329        if (accessibilityId < 0) {
18330            return null;
18331        }
18332        View view = findViewByAccessibilityIdTraversal(accessibilityId);
18333        if (view != null) {
18334            return view.includeForAccessibility() ? view : null;
18335        }
18336        return null;
18337    }
18338
18339    /**
18340     * Performs the traversal to find a view by its unuque and stable accessibility id.
18341     *
18342     * <strong>Note:</strong>This method does not stop at the root namespace
18343     * boundary since the user can touch the screen at an arbitrary location
18344     * potentially crossing the root namespace bounday which will send an
18345     * accessibility event to accessibility services and they should be able
18346     * to obtain the event source. Also accessibility ids are guaranteed to be
18347     * unique in the window.
18348     *
18349     * @param accessibilityId The accessibility id.
18350     * @return The found view.
18351     *
18352     * @hide
18353     */
18354    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
18355        if (getAccessibilityViewId() == accessibilityId) {
18356            return this;
18357        }
18358        return null;
18359    }
18360
18361    /**
18362     * Look for a child view with the given tag.  If this view has the given
18363     * tag, return this view.
18364     *
18365     * @param tag The tag to search for, using "tag.equals(getTag())".
18366     * @return The View that has the given tag in the hierarchy or null
18367     */
18368    public final View findViewWithTag(Object tag) {
18369        if (tag == null) {
18370            return null;
18371        }
18372        return findViewWithTagTraversal(tag);
18373    }
18374
18375    /**
18376     * {@hide}
18377     * Look for a child view that matches the specified predicate.
18378     * If this view matches the predicate, return this view.
18379     *
18380     * @param predicate The predicate to evaluate.
18381     * @return The first view that matches the predicate or null.
18382     */
18383    public final View findViewByPredicate(Predicate<View> predicate) {
18384        return findViewByPredicateTraversal(predicate, null);
18385    }
18386
18387    /**
18388     * {@hide}
18389     * Look for a child view that matches the specified predicate,
18390     * starting with the specified view and its descendents and then
18391     * recusively searching the ancestors and siblings of that view
18392     * until this view is reached.
18393     *
18394     * This method is useful in cases where the predicate does not match
18395     * a single unique view (perhaps multiple views use the same id)
18396     * and we are trying to find the view that is "closest" in scope to the
18397     * starting view.
18398     *
18399     * @param start The view to start from.
18400     * @param predicate The predicate to evaluate.
18401     * @return The first view that matches the predicate or null.
18402     */
18403    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
18404        View childToSkip = null;
18405        for (;;) {
18406            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
18407            if (view != null || start == this) {
18408                return view;
18409            }
18410
18411            ViewParent parent = start.getParent();
18412            if (parent == null || !(parent instanceof View)) {
18413                return null;
18414            }
18415
18416            childToSkip = start;
18417            start = (View) parent;
18418        }
18419    }
18420
18421    /**
18422     * Sets the identifier for this view. The identifier does not have to be
18423     * unique in this view's hierarchy. The identifier should be a positive
18424     * number.
18425     *
18426     * @see #NO_ID
18427     * @see #getId()
18428     * @see #findViewById(int)
18429     *
18430     * @param id a number used to identify the view
18431     *
18432     * @attr ref android.R.styleable#View_id
18433     */
18434    public void setId(@IdRes int id) {
18435        mID = id;
18436        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
18437            mID = generateViewId();
18438        }
18439    }
18440
18441    /**
18442     * {@hide}
18443     *
18444     * @param isRoot true if the view belongs to the root namespace, false
18445     *        otherwise
18446     */
18447    public void setIsRootNamespace(boolean isRoot) {
18448        if (isRoot) {
18449            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
18450        } else {
18451            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
18452        }
18453    }
18454
18455    /**
18456     * {@hide}
18457     *
18458     * @return true if the view belongs to the root namespace, false otherwise
18459     */
18460    public boolean isRootNamespace() {
18461        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
18462    }
18463
18464    /**
18465     * Returns this view's identifier.
18466     *
18467     * @return a positive integer used to identify the view or {@link #NO_ID}
18468     *         if the view has no ID
18469     *
18470     * @see #setId(int)
18471     * @see #findViewById(int)
18472     * @attr ref android.R.styleable#View_id
18473     */
18474    @IdRes
18475    @ViewDebug.CapturedViewProperty
18476    public int getId() {
18477        return mID;
18478    }
18479
18480    /**
18481     * Returns this view's tag.
18482     *
18483     * @return the Object stored in this view as a tag, or {@code null} if not
18484     *         set
18485     *
18486     * @see #setTag(Object)
18487     * @see #getTag(int)
18488     */
18489    @ViewDebug.ExportedProperty
18490    public Object getTag() {
18491        return mTag;
18492    }
18493
18494    /**
18495     * Sets the tag associated with this view. A tag can be used to mark
18496     * a view in its hierarchy and does not have to be unique within the
18497     * hierarchy. Tags can also be used to store data within a view without
18498     * resorting to another data structure.
18499     *
18500     * @param tag an Object to tag the view with
18501     *
18502     * @see #getTag()
18503     * @see #setTag(int, Object)
18504     */
18505    public void setTag(final Object tag) {
18506        mTag = tag;
18507    }
18508
18509    /**
18510     * Returns the tag associated with this view and the specified key.
18511     *
18512     * @param key The key identifying the tag
18513     *
18514     * @return the Object stored in this view as a tag, or {@code null} if not
18515     *         set
18516     *
18517     * @see #setTag(int, Object)
18518     * @see #getTag()
18519     */
18520    public Object getTag(int key) {
18521        if (mKeyedTags != null) return mKeyedTags.get(key);
18522        return null;
18523    }
18524
18525    /**
18526     * Sets a tag associated with this view and a key. A tag can be used
18527     * to mark a view in its hierarchy and does not have to be unique within
18528     * the hierarchy. Tags can also be used to store data within a view
18529     * without resorting to another data structure.
18530     *
18531     * The specified key should be an id declared in the resources of the
18532     * application to ensure it is unique (see the <a
18533     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
18534     * Keys identified as belonging to
18535     * the Android framework or not associated with any package will cause
18536     * an {@link IllegalArgumentException} to be thrown.
18537     *
18538     * @param key The key identifying the tag
18539     * @param tag An Object to tag the view with
18540     *
18541     * @throws IllegalArgumentException If they specified key is not valid
18542     *
18543     * @see #setTag(Object)
18544     * @see #getTag(int)
18545     */
18546    public void setTag(int key, final Object tag) {
18547        // If the package id is 0x00 or 0x01, it's either an undefined package
18548        // or a framework id
18549        if ((key >>> 24) < 2) {
18550            throw new IllegalArgumentException("The key must be an application-specific "
18551                    + "resource id.");
18552        }
18553
18554        setKeyedTag(key, tag);
18555    }
18556
18557    /**
18558     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
18559     * framework id.
18560     *
18561     * @hide
18562     */
18563    public void setTagInternal(int key, Object tag) {
18564        if ((key >>> 24) != 0x1) {
18565            throw new IllegalArgumentException("The key must be a framework-specific "
18566                    + "resource id.");
18567        }
18568
18569        setKeyedTag(key, tag);
18570    }
18571
18572    private void setKeyedTag(int key, Object tag) {
18573        if (mKeyedTags == null) {
18574            mKeyedTags = new SparseArray<Object>(2);
18575        }
18576
18577        mKeyedTags.put(key, tag);
18578    }
18579
18580    /**
18581     * Prints information about this view in the log output, with the tag
18582     * {@link #VIEW_LOG_TAG}.
18583     *
18584     * @hide
18585     */
18586    public void debug() {
18587        debug(0);
18588    }
18589
18590    /**
18591     * Prints information about this view in the log output, with the tag
18592     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
18593     * indentation defined by the <code>depth</code>.
18594     *
18595     * @param depth the indentation level
18596     *
18597     * @hide
18598     */
18599    protected void debug(int depth) {
18600        String output = debugIndent(depth - 1);
18601
18602        output += "+ " + this;
18603        int id = getId();
18604        if (id != -1) {
18605            output += " (id=" + id + ")";
18606        }
18607        Object tag = getTag();
18608        if (tag != null) {
18609            output += " (tag=" + tag + ")";
18610        }
18611        Log.d(VIEW_LOG_TAG, output);
18612
18613        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
18614            output = debugIndent(depth) + " FOCUSED";
18615            Log.d(VIEW_LOG_TAG, output);
18616        }
18617
18618        output = debugIndent(depth);
18619        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
18620                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
18621                + "} ";
18622        Log.d(VIEW_LOG_TAG, output);
18623
18624        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
18625                || mPaddingBottom != 0) {
18626            output = debugIndent(depth);
18627            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
18628                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
18629            Log.d(VIEW_LOG_TAG, output);
18630        }
18631
18632        output = debugIndent(depth);
18633        output += "mMeasureWidth=" + mMeasuredWidth +
18634                " mMeasureHeight=" + mMeasuredHeight;
18635        Log.d(VIEW_LOG_TAG, output);
18636
18637        output = debugIndent(depth);
18638        if (mLayoutParams == null) {
18639            output += "BAD! no layout params";
18640        } else {
18641            output = mLayoutParams.debug(output);
18642        }
18643        Log.d(VIEW_LOG_TAG, output);
18644
18645        output = debugIndent(depth);
18646        output += "flags={";
18647        output += View.printFlags(mViewFlags);
18648        output += "}";
18649        Log.d(VIEW_LOG_TAG, output);
18650
18651        output = debugIndent(depth);
18652        output += "privateFlags={";
18653        output += View.printPrivateFlags(mPrivateFlags);
18654        output += "}";
18655        Log.d(VIEW_LOG_TAG, output);
18656    }
18657
18658    /**
18659     * Creates a string of whitespaces used for indentation.
18660     *
18661     * @param depth the indentation level
18662     * @return a String containing (depth * 2 + 3) * 2 white spaces
18663     *
18664     * @hide
18665     */
18666    protected static String debugIndent(int depth) {
18667        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18668        for (int i = 0; i < (depth * 2) + 3; i++) {
18669            spaces.append(' ').append(' ');
18670        }
18671        return spaces.toString();
18672    }
18673
18674    /**
18675     * <p>Return the offset of the widget's text baseline from the widget's top
18676     * boundary. If this widget does not support baseline alignment, this
18677     * method returns -1. </p>
18678     *
18679     * @return the offset of the baseline within the widget's bounds or -1
18680     *         if baseline alignment is not supported
18681     */
18682    @ViewDebug.ExportedProperty(category = "layout")
18683    public int getBaseline() {
18684        return -1;
18685    }
18686
18687    /**
18688     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18689     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18690     * a layout pass.
18691     *
18692     * @return whether the view hierarchy is currently undergoing a layout pass
18693     */
18694    public boolean isInLayout() {
18695        ViewRootImpl viewRoot = getViewRootImpl();
18696        return (viewRoot != null && viewRoot.isInLayout());
18697    }
18698
18699    /**
18700     * Call this when something has changed which has invalidated the
18701     * layout of this view. This will schedule a layout pass of the view
18702     * tree. This should not be called while the view hierarchy is currently in a layout
18703     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18704     * end of the current layout pass (and then layout will run again) or after the current
18705     * frame is drawn and the next layout occurs.
18706     *
18707     * <p>Subclasses which override this method should call the superclass method to
18708     * handle possible request-during-layout errors correctly.</p>
18709     */
18710    @CallSuper
18711    public void requestLayout() {
18712        if (mMeasureCache != null) mMeasureCache.clear();
18713
18714        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18715            // Only trigger request-during-layout logic if this is the view requesting it,
18716            // not the views in its parent hierarchy
18717            ViewRootImpl viewRoot = getViewRootImpl();
18718            if (viewRoot != null && viewRoot.isInLayout()) {
18719                if (!viewRoot.requestLayoutDuringLayout(this)) {
18720                    return;
18721                }
18722            }
18723            mAttachInfo.mViewRequestingLayout = this;
18724        }
18725
18726        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18727        mPrivateFlags |= PFLAG_INVALIDATED;
18728
18729        if (mParent != null && !mParent.isLayoutRequested()) {
18730            mParent.requestLayout();
18731        }
18732        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18733            mAttachInfo.mViewRequestingLayout = null;
18734        }
18735    }
18736
18737    /**
18738     * Forces this view to be laid out during the next layout pass.
18739     * This method does not call requestLayout() or forceLayout()
18740     * on the parent.
18741     */
18742    public void forceLayout() {
18743        if (mMeasureCache != null) mMeasureCache.clear();
18744
18745        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18746        mPrivateFlags |= PFLAG_INVALIDATED;
18747    }
18748
18749    /**
18750     * <p>
18751     * This is called to find out how big a view should be. The parent
18752     * supplies constraint information in the width and height parameters.
18753     * </p>
18754     *
18755     * <p>
18756     * The actual measurement work of a view is performed in
18757     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18758     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18759     * </p>
18760     *
18761     *
18762     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18763     *        parent
18764     * @param heightMeasureSpec Vertical space requirements as imposed by the
18765     *        parent
18766     *
18767     * @see #onMeasure(int, int)
18768     */
18769    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18770        boolean optical = isLayoutModeOptical(this);
18771        if (optical != isLayoutModeOptical(mParent)) {
18772            Insets insets = getOpticalInsets();
18773            int oWidth  = insets.left + insets.right;
18774            int oHeight = insets.top  + insets.bottom;
18775            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18776            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18777        }
18778
18779        // Suppress sign extension for the low bytes
18780        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18781        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18782
18783        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18784        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18785                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18786        final boolean matchingSize = isExactly &&
18787                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18788                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18789        if (forceLayout || !matchingSize &&
18790                (widthMeasureSpec != mOldWidthMeasureSpec ||
18791                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18792
18793            // first clears the measured dimension flag
18794            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18795
18796            resolveRtlPropertiesIfNeeded();
18797
18798            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18799            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18800                // measure ourselves, this should set the measured dimension flag back
18801                onMeasure(widthMeasureSpec, heightMeasureSpec);
18802                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18803            } else {
18804                long value = mMeasureCache.valueAt(cacheIndex);
18805                // Casting a long to int drops the high 32 bits, no mask needed
18806                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18807                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18808            }
18809
18810            // flag not set, setMeasuredDimension() was not invoked, we raise
18811            // an exception to warn the developer
18812            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18813                throw new IllegalStateException("View with id " + getId() + ": "
18814                        + getClass().getName() + "#onMeasure() did not set the"
18815                        + " measured dimension by calling"
18816                        + " setMeasuredDimension()");
18817            }
18818
18819            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18820        }
18821
18822        mOldWidthMeasureSpec = widthMeasureSpec;
18823        mOldHeightMeasureSpec = heightMeasureSpec;
18824
18825        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18826                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18827    }
18828
18829    /**
18830     * <p>
18831     * Measure the view and its content to determine the measured width and the
18832     * measured height. This method is invoked by {@link #measure(int, int)} and
18833     * should be overridden by subclasses to provide accurate and efficient
18834     * measurement of their contents.
18835     * </p>
18836     *
18837     * <p>
18838     * <strong>CONTRACT:</strong> When overriding this method, you
18839     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18840     * measured width and height of this view. Failure to do so will trigger an
18841     * <code>IllegalStateException</code>, thrown by
18842     * {@link #measure(int, int)}. Calling the superclass'
18843     * {@link #onMeasure(int, int)} is a valid use.
18844     * </p>
18845     *
18846     * <p>
18847     * The base class implementation of measure defaults to the background size,
18848     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18849     * override {@link #onMeasure(int, int)} to provide better measurements of
18850     * their content.
18851     * </p>
18852     *
18853     * <p>
18854     * If this method is overridden, it is the subclass's responsibility to make
18855     * sure the measured height and width are at least the view's minimum height
18856     * and width ({@link #getSuggestedMinimumHeight()} and
18857     * {@link #getSuggestedMinimumWidth()}).
18858     * </p>
18859     *
18860     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18861     *                         The requirements are encoded with
18862     *                         {@link android.view.View.MeasureSpec}.
18863     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18864     *                         The requirements are encoded with
18865     *                         {@link android.view.View.MeasureSpec}.
18866     *
18867     * @see #getMeasuredWidth()
18868     * @see #getMeasuredHeight()
18869     * @see #setMeasuredDimension(int, int)
18870     * @see #getSuggestedMinimumHeight()
18871     * @see #getSuggestedMinimumWidth()
18872     * @see android.view.View.MeasureSpec#getMode(int)
18873     * @see android.view.View.MeasureSpec#getSize(int)
18874     */
18875    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18876        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18877                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18878    }
18879
18880    /**
18881     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18882     * measured width and measured height. Failing to do so will trigger an
18883     * exception at measurement time.</p>
18884     *
18885     * @param measuredWidth The measured width of this view.  May be a complex
18886     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18887     * {@link #MEASURED_STATE_TOO_SMALL}.
18888     * @param measuredHeight The measured height of this view.  May be a complex
18889     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18890     * {@link #MEASURED_STATE_TOO_SMALL}.
18891     */
18892    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18893        boolean optical = isLayoutModeOptical(this);
18894        if (optical != isLayoutModeOptical(mParent)) {
18895            Insets insets = getOpticalInsets();
18896            int opticalWidth  = insets.left + insets.right;
18897            int opticalHeight = insets.top  + insets.bottom;
18898
18899            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18900            measuredHeight += optical ? opticalHeight : -opticalHeight;
18901        }
18902        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18903    }
18904
18905    /**
18906     * Sets the measured dimension without extra processing for things like optical bounds.
18907     * Useful for reapplying consistent values that have already been cooked with adjustments
18908     * for optical bounds, etc. such as those from the measurement cache.
18909     *
18910     * @param measuredWidth The measured width of this view.  May be a complex
18911     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18912     * {@link #MEASURED_STATE_TOO_SMALL}.
18913     * @param measuredHeight The measured height of this view.  May be a complex
18914     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18915     * {@link #MEASURED_STATE_TOO_SMALL}.
18916     */
18917    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18918        mMeasuredWidth = measuredWidth;
18919        mMeasuredHeight = measuredHeight;
18920
18921        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18922    }
18923
18924    /**
18925     * Merge two states as returned by {@link #getMeasuredState()}.
18926     * @param curState The current state as returned from a view or the result
18927     * of combining multiple views.
18928     * @param newState The new view state to combine.
18929     * @return Returns a new integer reflecting the combination of the two
18930     * states.
18931     */
18932    public static int combineMeasuredStates(int curState, int newState) {
18933        return curState | newState;
18934    }
18935
18936    /**
18937     * Version of {@link #resolveSizeAndState(int, int, int)}
18938     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18939     */
18940    public static int resolveSize(int size, int measureSpec) {
18941        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18942    }
18943
18944    /**
18945     * Utility to reconcile a desired size and state, with constraints imposed
18946     * by a MeasureSpec. Will take the desired size, unless a different size
18947     * is imposed by the constraints. The returned value is a compound integer,
18948     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18949     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18950     * resulting size is smaller than the size the view wants to be.
18951     *
18952     * @param size How big the view wants to be.
18953     * @param measureSpec Constraints imposed by the parent.
18954     * @param childMeasuredState Size information bit mask for the view's
18955     *                           children.
18956     * @return Size information bit mask as defined by
18957     *         {@link #MEASURED_SIZE_MASK} and
18958     *         {@link #MEASURED_STATE_TOO_SMALL}.
18959     */
18960    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18961        final int specMode = MeasureSpec.getMode(measureSpec);
18962        final int specSize = MeasureSpec.getSize(measureSpec);
18963        final int result;
18964        switch (specMode) {
18965            case MeasureSpec.AT_MOST:
18966                if (specSize < size) {
18967                    result = specSize | MEASURED_STATE_TOO_SMALL;
18968                } else {
18969                    result = size;
18970                }
18971                break;
18972            case MeasureSpec.EXACTLY:
18973                result = specSize;
18974                break;
18975            case MeasureSpec.UNSPECIFIED:
18976            default:
18977                result = size;
18978        }
18979        return result | (childMeasuredState & MEASURED_STATE_MASK);
18980    }
18981
18982    /**
18983     * Utility to return a default size. Uses the supplied size if the
18984     * MeasureSpec imposed no constraints. Will get larger if allowed
18985     * by the MeasureSpec.
18986     *
18987     * @param size Default size for this view
18988     * @param measureSpec Constraints imposed by the parent
18989     * @return The size this view should be.
18990     */
18991    public static int getDefaultSize(int size, int measureSpec) {
18992        int result = size;
18993        int specMode = MeasureSpec.getMode(measureSpec);
18994        int specSize = MeasureSpec.getSize(measureSpec);
18995
18996        switch (specMode) {
18997        case MeasureSpec.UNSPECIFIED:
18998            result = size;
18999            break;
19000        case MeasureSpec.AT_MOST:
19001        case MeasureSpec.EXACTLY:
19002            result = specSize;
19003            break;
19004        }
19005        return result;
19006    }
19007
19008    /**
19009     * Returns the suggested minimum height that the view should use. This
19010     * returns the maximum of the view's minimum height
19011     * and the background's minimum height
19012     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19013     * <p>
19014     * When being used in {@link #onMeasure(int, int)}, the caller should still
19015     * ensure the returned height is within the requirements of the parent.
19016     *
19017     * @return The suggested minimum height of the view.
19018     */
19019    protected int getSuggestedMinimumHeight() {
19020        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19021
19022    }
19023
19024    /**
19025     * Returns the suggested minimum width that the view should use. This
19026     * returns the maximum of the view's minimum width
19027     * and the background's minimum width
19028     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19029     * <p>
19030     * When being used in {@link #onMeasure(int, int)}, the caller should still
19031     * ensure the returned width is within the requirements of the parent.
19032     *
19033     * @return The suggested minimum width of the view.
19034     */
19035    protected int getSuggestedMinimumWidth() {
19036        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19037    }
19038
19039    /**
19040     * Returns the minimum height of the view.
19041     *
19042     * @return the minimum height the view will try to be.
19043     *
19044     * @see #setMinimumHeight(int)
19045     *
19046     * @attr ref android.R.styleable#View_minHeight
19047     */
19048    public int getMinimumHeight() {
19049        return mMinHeight;
19050    }
19051
19052    /**
19053     * Sets the minimum height of the view. It is not guaranteed the view will
19054     * be able to achieve this minimum height (for example, if its parent layout
19055     * constrains it with less available height).
19056     *
19057     * @param minHeight The minimum height the view will try to be.
19058     *
19059     * @see #getMinimumHeight()
19060     *
19061     * @attr ref android.R.styleable#View_minHeight
19062     */
19063    public void setMinimumHeight(int minHeight) {
19064        mMinHeight = minHeight;
19065        requestLayout();
19066    }
19067
19068    /**
19069     * Returns the minimum width of the view.
19070     *
19071     * @return the minimum width the view will try to be.
19072     *
19073     * @see #setMinimumWidth(int)
19074     *
19075     * @attr ref android.R.styleable#View_minWidth
19076     */
19077    public int getMinimumWidth() {
19078        return mMinWidth;
19079    }
19080
19081    /**
19082     * Sets the minimum width of the view. It is not guaranteed the view will
19083     * be able to achieve this minimum width (for example, if its parent layout
19084     * constrains it with less available width).
19085     *
19086     * @param minWidth The minimum width the view will try to be.
19087     *
19088     * @see #getMinimumWidth()
19089     *
19090     * @attr ref android.R.styleable#View_minWidth
19091     */
19092    public void setMinimumWidth(int minWidth) {
19093        mMinWidth = minWidth;
19094        requestLayout();
19095
19096    }
19097
19098    /**
19099     * Get the animation currently associated with this view.
19100     *
19101     * @return The animation that is currently playing or
19102     *         scheduled to play for this view.
19103     */
19104    public Animation getAnimation() {
19105        return mCurrentAnimation;
19106    }
19107
19108    /**
19109     * Start the specified animation now.
19110     *
19111     * @param animation the animation to start now
19112     */
19113    public void startAnimation(Animation animation) {
19114        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
19115        setAnimation(animation);
19116        invalidateParentCaches();
19117        invalidate(true);
19118    }
19119
19120    /**
19121     * Cancels any animations for this view.
19122     */
19123    public void clearAnimation() {
19124        if (mCurrentAnimation != null) {
19125            mCurrentAnimation.detach();
19126        }
19127        mCurrentAnimation = null;
19128        invalidateParentIfNeeded();
19129    }
19130
19131    /**
19132     * Sets the next animation to play for this view.
19133     * If you want the animation to play immediately, use
19134     * {@link #startAnimation(android.view.animation.Animation)} instead.
19135     * This method provides allows fine-grained
19136     * control over the start time and invalidation, but you
19137     * must make sure that 1) the animation has a start time set, and
19138     * 2) the view's parent (which controls animations on its children)
19139     * will be invalidated when the animation is supposed to
19140     * start.
19141     *
19142     * @param animation The next animation, or null.
19143     */
19144    public void setAnimation(Animation animation) {
19145        mCurrentAnimation = animation;
19146
19147        if (animation != null) {
19148            // If the screen is off assume the animation start time is now instead of
19149            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
19150            // would cause the animation to start when the screen turns back on
19151            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
19152                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
19153                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
19154            }
19155            animation.reset();
19156        }
19157    }
19158
19159    /**
19160     * Invoked by a parent ViewGroup to notify the start of the animation
19161     * currently associated with this view. If you override this method,
19162     * always call super.onAnimationStart();
19163     *
19164     * @see #setAnimation(android.view.animation.Animation)
19165     * @see #getAnimation()
19166     */
19167    @CallSuper
19168    protected void onAnimationStart() {
19169        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
19170    }
19171
19172    /**
19173     * Invoked by a parent ViewGroup to notify the end of the animation
19174     * currently associated with this view. If you override this method,
19175     * always call super.onAnimationEnd();
19176     *
19177     * @see #setAnimation(android.view.animation.Animation)
19178     * @see #getAnimation()
19179     */
19180    @CallSuper
19181    protected void onAnimationEnd() {
19182        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
19183    }
19184
19185    /**
19186     * Invoked if there is a Transform that involves alpha. Subclass that can
19187     * draw themselves with the specified alpha should return true, and then
19188     * respect that alpha when their onDraw() is called. If this returns false
19189     * then the view may be redirected to draw into an offscreen buffer to
19190     * fulfill the request, which will look fine, but may be slower than if the
19191     * subclass handles it internally. The default implementation returns false.
19192     *
19193     * @param alpha The alpha (0..255) to apply to the view's drawing
19194     * @return true if the view can draw with the specified alpha.
19195     */
19196    protected boolean onSetAlpha(int alpha) {
19197        return false;
19198    }
19199
19200    /**
19201     * This is used by the RootView to perform an optimization when
19202     * the view hierarchy contains one or several SurfaceView.
19203     * SurfaceView is always considered transparent, but its children are not,
19204     * therefore all View objects remove themselves from the global transparent
19205     * region (passed as a parameter to this function).
19206     *
19207     * @param region The transparent region for this ViewAncestor (window).
19208     *
19209     * @return Returns true if the effective visibility of the view at this
19210     * point is opaque, regardless of the transparent region; returns false
19211     * if it is possible for underlying windows to be seen behind the view.
19212     *
19213     * {@hide}
19214     */
19215    public boolean gatherTransparentRegion(Region region) {
19216        final AttachInfo attachInfo = mAttachInfo;
19217        if (region != null && attachInfo != null) {
19218            final int pflags = mPrivateFlags;
19219            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
19220                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
19221                // remove it from the transparent region.
19222                final int[] location = attachInfo.mTransparentLocation;
19223                getLocationInWindow(location);
19224                region.op(location[0], location[1], location[0] + mRight - mLeft,
19225                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
19226            } else {
19227                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
19228                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
19229                    // the background drawable's non-transparent parts from this transparent region.
19230                    applyDrawableToTransparentRegion(mBackground, region);
19231                }
19232                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19233                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
19234                    // Similarly, we remove the foreground drawable's non-transparent parts.
19235                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
19236                }
19237            }
19238        }
19239        return true;
19240    }
19241
19242    /**
19243     * Play a sound effect for this view.
19244     *
19245     * <p>The framework will play sound effects for some built in actions, such as
19246     * clicking, but you may wish to play these effects in your widget,
19247     * for instance, for internal navigation.
19248     *
19249     * <p>The sound effect will only be played if sound effects are enabled by the user, and
19250     * {@link #isSoundEffectsEnabled()} is true.
19251     *
19252     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
19253     */
19254    public void playSoundEffect(int soundConstant) {
19255        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
19256            return;
19257        }
19258        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
19259    }
19260
19261    /**
19262     * BZZZTT!!1!
19263     *
19264     * <p>Provide haptic feedback to the user for this view.
19265     *
19266     * <p>The framework will provide haptic feedback for some built in actions,
19267     * such as long presses, but you may wish to provide feedback for your
19268     * own widget.
19269     *
19270     * <p>The feedback will only be performed if
19271     * {@link #isHapticFeedbackEnabled()} is true.
19272     *
19273     * @param feedbackConstant One of the constants defined in
19274     * {@link HapticFeedbackConstants}
19275     */
19276    public boolean performHapticFeedback(int feedbackConstant) {
19277        return performHapticFeedback(feedbackConstant, 0);
19278    }
19279
19280    /**
19281     * BZZZTT!!1!
19282     *
19283     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
19284     *
19285     * @param feedbackConstant One of the constants defined in
19286     * {@link HapticFeedbackConstants}
19287     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
19288     */
19289    public boolean performHapticFeedback(int feedbackConstant, int flags) {
19290        if (mAttachInfo == null) {
19291            return false;
19292        }
19293        //noinspection SimplifiableIfStatement
19294        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
19295                && !isHapticFeedbackEnabled()) {
19296            return false;
19297        }
19298        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
19299                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
19300    }
19301
19302    /**
19303     * Request that the visibility of the status bar or other screen/window
19304     * decorations be changed.
19305     *
19306     * <p>This method is used to put the over device UI into temporary modes
19307     * where the user's attention is focused more on the application content,
19308     * by dimming or hiding surrounding system affordances.  This is typically
19309     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
19310     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
19311     * to be placed behind the action bar (and with these flags other system
19312     * affordances) so that smooth transitions between hiding and showing them
19313     * can be done.
19314     *
19315     * <p>Two representative examples of the use of system UI visibility is
19316     * implementing a content browsing application (like a magazine reader)
19317     * and a video playing application.
19318     *
19319     * <p>The first code shows a typical implementation of a View in a content
19320     * browsing application.  In this implementation, the application goes
19321     * into a content-oriented mode by hiding the status bar and action bar,
19322     * and putting the navigation elements into lights out mode.  The user can
19323     * then interact with content while in this mode.  Such an application should
19324     * provide an easy way for the user to toggle out of the mode (such as to
19325     * check information in the status bar or access notifications).  In the
19326     * implementation here, this is done simply by tapping on the content.
19327     *
19328     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
19329     *      content}
19330     *
19331     * <p>This second code sample shows a typical implementation of a View
19332     * in a video playing application.  In this situation, while the video is
19333     * playing the application would like to go into a complete full-screen mode,
19334     * to use as much of the display as possible for the video.  When in this state
19335     * the user can not interact with the application; the system intercepts
19336     * touching on the screen to pop the UI out of full screen mode.  See
19337     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
19338     *
19339     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
19340     *      content}
19341     *
19342     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19343     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
19344     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
19345     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
19346     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
19347     */
19348    public void setSystemUiVisibility(int visibility) {
19349        if (visibility != mSystemUiVisibility) {
19350            mSystemUiVisibility = visibility;
19351            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
19352                mParent.recomputeViewAttributes(this);
19353            }
19354        }
19355    }
19356
19357    /**
19358     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
19359     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19360     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
19361     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
19362     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
19363     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
19364     */
19365    public int getSystemUiVisibility() {
19366        return mSystemUiVisibility;
19367    }
19368
19369    /**
19370     * Returns the current system UI visibility that is currently set for
19371     * the entire window.  This is the combination of the
19372     * {@link #setSystemUiVisibility(int)} values supplied by all of the
19373     * views in the window.
19374     */
19375    public int getWindowSystemUiVisibility() {
19376        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
19377    }
19378
19379    /**
19380     * Override to find out when the window's requested system UI visibility
19381     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
19382     * This is different from the callbacks received through
19383     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
19384     * in that this is only telling you about the local request of the window,
19385     * not the actual values applied by the system.
19386     */
19387    public void onWindowSystemUiVisibilityChanged(int visible) {
19388    }
19389
19390    /**
19391     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
19392     * the view hierarchy.
19393     */
19394    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
19395        onWindowSystemUiVisibilityChanged(visible);
19396    }
19397
19398    /**
19399     * Set a listener to receive callbacks when the visibility of the system bar changes.
19400     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
19401     */
19402    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
19403        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
19404        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
19405            mParent.recomputeViewAttributes(this);
19406        }
19407    }
19408
19409    /**
19410     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
19411     * the view hierarchy.
19412     */
19413    public void dispatchSystemUiVisibilityChanged(int visibility) {
19414        ListenerInfo li = mListenerInfo;
19415        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
19416            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
19417                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
19418        }
19419    }
19420
19421    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
19422        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
19423        if (val != mSystemUiVisibility) {
19424            setSystemUiVisibility(val);
19425            return true;
19426        }
19427        return false;
19428    }
19429
19430    /** @hide */
19431    public void setDisabledSystemUiVisibility(int flags) {
19432        if (mAttachInfo != null) {
19433            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
19434                mAttachInfo.mDisabledSystemUiVisibility = flags;
19435                if (mParent != null) {
19436                    mParent.recomputeViewAttributes(this);
19437                }
19438            }
19439        }
19440    }
19441
19442    /**
19443     * Creates an image that the system displays during the drag and drop
19444     * operation. This is called a &quot;drag shadow&quot;. The default implementation
19445     * for a DragShadowBuilder based on a View returns an image that has exactly the same
19446     * appearance as the given View. The default also positions the center of the drag shadow
19447     * directly under the touch point. If no View is provided (the constructor with no parameters
19448     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
19449     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
19450     * default is an invisible drag shadow.
19451     * <p>
19452     * You are not required to use the View you provide to the constructor as the basis of the
19453     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
19454     * anything you want as the drag shadow.
19455     * </p>
19456     * <p>
19457     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
19458     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
19459     *  size and position of the drag shadow. It uses this data to construct a
19460     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
19461     *  so that your application can draw the shadow image in the Canvas.
19462     * </p>
19463     *
19464     * <div class="special reference">
19465     * <h3>Developer Guides</h3>
19466     * <p>For a guide to implementing drag and drop features, read the
19467     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19468     * </div>
19469     */
19470    public static class DragShadowBuilder {
19471        private final WeakReference<View> mView;
19472
19473        /**
19474         * Constructs a shadow image builder based on a View. By default, the resulting drag
19475         * shadow will have the same appearance and dimensions as the View, with the touch point
19476         * over the center of the View.
19477         * @param view A View. Any View in scope can be used.
19478         */
19479        public DragShadowBuilder(View view) {
19480            mView = new WeakReference<View>(view);
19481        }
19482
19483        /**
19484         * Construct a shadow builder object with no associated View.  This
19485         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
19486         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
19487         * to supply the drag shadow's dimensions and appearance without
19488         * reference to any View object. If they are not overridden, then the result is an
19489         * invisible drag shadow.
19490         */
19491        public DragShadowBuilder() {
19492            mView = new WeakReference<View>(null);
19493        }
19494
19495        /**
19496         * Returns the View object that had been passed to the
19497         * {@link #View.DragShadowBuilder(View)}
19498         * constructor.  If that View parameter was {@code null} or if the
19499         * {@link #View.DragShadowBuilder()}
19500         * constructor was used to instantiate the builder object, this method will return
19501         * null.
19502         *
19503         * @return The View object associate with this builder object.
19504         */
19505        @SuppressWarnings({"JavadocReference"})
19506        final public View getView() {
19507            return mView.get();
19508        }
19509
19510        /**
19511         * Provides the metrics for the shadow image. These include the dimensions of
19512         * the shadow image, and the point within that shadow that should
19513         * be centered under the touch location while dragging.
19514         * <p>
19515         * The default implementation sets the dimensions of the shadow to be the
19516         * same as the dimensions of the View itself and centers the shadow under
19517         * the touch point.
19518         * </p>
19519         *
19520         * @param shadowSize A {@link android.graphics.Point} containing the width and height
19521         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
19522         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
19523         * image.
19524         *
19525         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
19526         * shadow image that should be underneath the touch point during the drag and drop
19527         * operation. Your application must set {@link android.graphics.Point#x} to the
19528         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
19529         */
19530        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
19531            final View view = mView.get();
19532            if (view != null) {
19533                shadowSize.set(view.getWidth(), view.getHeight());
19534                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
19535            } else {
19536                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
19537            }
19538        }
19539
19540        /**
19541         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
19542         * based on the dimensions it received from the
19543         * {@link #onProvideShadowMetrics(Point, Point)} callback.
19544         *
19545         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
19546         */
19547        public void onDrawShadow(Canvas canvas) {
19548            final View view = mView.get();
19549            if (view != null) {
19550                view.draw(canvas);
19551            } else {
19552                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
19553            }
19554        }
19555    }
19556
19557    /**
19558     * Starts a drag and drop operation. When your application calls this method, it passes a
19559     * {@link android.view.View.DragShadowBuilder} object to the system. The
19560     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
19561     * to get metrics for the drag shadow, and then calls the object's
19562     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
19563     * <p>
19564     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
19565     *  drag events to all the View objects in your application that are currently visible. It does
19566     *  this either by calling the View object's drag listener (an implementation of
19567     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
19568     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
19569     *  Both are passed a {@link android.view.DragEvent} object that has a
19570     *  {@link android.view.DragEvent#getAction()} value of
19571     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
19572     * </p>
19573     * <p>
19574     * Your application can invoke startDrag() on any attached View object. The View object does not
19575     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
19576     * be related to the View the user selected for dragging.
19577     * </p>
19578     * @param data A {@link android.content.ClipData} object pointing to the data to be
19579     * transferred by the drag and drop operation.
19580     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
19581     * drag shadow.
19582     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
19583     * drop operation. This Object is put into every DragEvent object sent by the system during the
19584     * current drag.
19585     * <p>
19586     * myLocalState is a lightweight mechanism for the sending information from the dragged View
19587     * to the target Views. For example, it can contain flags that differentiate between a
19588     * a copy operation and a move operation.
19589     * </p>
19590     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
19591     * so the parameter should be set to 0.
19592     * @return {@code true} if the method completes successfully, or
19593     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
19594     * do a drag, and so no drag operation is in progress.
19595     */
19596    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
19597            Object myLocalState, int flags) {
19598        if (ViewDebug.DEBUG_DRAG) {
19599            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
19600        }
19601        boolean okay = false;
19602
19603        Point shadowSize = new Point();
19604        Point shadowTouchPoint = new Point();
19605        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
19606
19607        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
19608                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
19609            throw new IllegalStateException("Drag shadow dimensions must not be negative");
19610        }
19611
19612        if (ViewDebug.DEBUG_DRAG) {
19613            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
19614                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
19615        }
19616        Surface surface = new Surface();
19617        try {
19618            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
19619                    flags, shadowSize.x, shadowSize.y, surface);
19620            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
19621                    + " surface=" + surface);
19622            if (token != null) {
19623                Canvas canvas = surface.lockCanvas(null);
19624                try {
19625                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
19626                    shadowBuilder.onDrawShadow(canvas);
19627                } finally {
19628                    surface.unlockCanvasAndPost(canvas);
19629                }
19630
19631                final ViewRootImpl root = getViewRootImpl();
19632
19633                // Cache the local state object for delivery with DragEvents
19634                root.setLocalDragState(myLocalState);
19635
19636                // repurpose 'shadowSize' for the last touch point
19637                root.getLastTouchPoint(shadowSize);
19638
19639                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19640                        shadowSize.x, shadowSize.y,
19641                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19642                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19643
19644                // Off and running!  Release our local surface instance; the drag
19645                // shadow surface is now managed by the system process.
19646                surface.release();
19647            }
19648        } catch (Exception e) {
19649            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19650            surface.destroy();
19651        }
19652
19653        return okay;
19654    }
19655
19656    /**
19657     * Handles drag events sent by the system following a call to
19658     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19659     *<p>
19660     * When the system calls this method, it passes a
19661     * {@link android.view.DragEvent} object. A call to
19662     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19663     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19664     * operation.
19665     * @param event The {@link android.view.DragEvent} sent by the system.
19666     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19667     * in DragEvent, indicating the type of drag event represented by this object.
19668     * @return {@code true} if the method was successful, otherwise {@code false}.
19669     * <p>
19670     *  The method should return {@code true} in response to an action type of
19671     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19672     *  operation.
19673     * </p>
19674     * <p>
19675     *  The method should also return {@code true} in response to an action type of
19676     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19677     *  {@code false} if it didn't.
19678     * </p>
19679     */
19680    public boolean onDragEvent(DragEvent event) {
19681        return false;
19682    }
19683
19684    /**
19685     * Detects if this View is enabled and has a drag event listener.
19686     * If both are true, then it calls the drag event listener with the
19687     * {@link android.view.DragEvent} it received. If the drag event listener returns
19688     * {@code true}, then dispatchDragEvent() returns {@code true}.
19689     * <p>
19690     * For all other cases, the method calls the
19691     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19692     * method and returns its result.
19693     * </p>
19694     * <p>
19695     * This ensures that a drag event is always consumed, even if the View does not have a drag
19696     * event listener. However, if the View has a listener and the listener returns true, then
19697     * onDragEvent() is not called.
19698     * </p>
19699     */
19700    public boolean dispatchDragEvent(DragEvent event) {
19701        ListenerInfo li = mListenerInfo;
19702        //noinspection SimplifiableIfStatement
19703        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19704                && li.mOnDragListener.onDrag(this, event)) {
19705            return true;
19706        }
19707        return onDragEvent(event);
19708    }
19709
19710    boolean canAcceptDrag() {
19711        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19712    }
19713
19714    /**
19715     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19716     * it is ever exposed at all.
19717     * @hide
19718     */
19719    public void onCloseSystemDialogs(String reason) {
19720    }
19721
19722    /**
19723     * Given a Drawable whose bounds have been set to draw into this view,
19724     * update a Region being computed for
19725     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19726     * that any non-transparent parts of the Drawable are removed from the
19727     * given transparent region.
19728     *
19729     * @param dr The Drawable whose transparency is to be applied to the region.
19730     * @param region A Region holding the current transparency information,
19731     * where any parts of the region that are set are considered to be
19732     * transparent.  On return, this region will be modified to have the
19733     * transparency information reduced by the corresponding parts of the
19734     * Drawable that are not transparent.
19735     * {@hide}
19736     */
19737    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19738        if (DBG) {
19739            Log.i("View", "Getting transparent region for: " + this);
19740        }
19741        final Region r = dr.getTransparentRegion();
19742        final Rect db = dr.getBounds();
19743        final AttachInfo attachInfo = mAttachInfo;
19744        if (r != null && attachInfo != null) {
19745            final int w = getRight()-getLeft();
19746            final int h = getBottom()-getTop();
19747            if (db.left > 0) {
19748                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19749                r.op(0, 0, db.left, h, Region.Op.UNION);
19750            }
19751            if (db.right < w) {
19752                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19753                r.op(db.right, 0, w, h, Region.Op.UNION);
19754            }
19755            if (db.top > 0) {
19756                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19757                r.op(0, 0, w, db.top, Region.Op.UNION);
19758            }
19759            if (db.bottom < h) {
19760                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19761                r.op(0, db.bottom, w, h, Region.Op.UNION);
19762            }
19763            final int[] location = attachInfo.mTransparentLocation;
19764            getLocationInWindow(location);
19765            r.translate(location[0], location[1]);
19766            region.op(r, Region.Op.INTERSECT);
19767        } else {
19768            region.op(db, Region.Op.DIFFERENCE);
19769        }
19770    }
19771
19772    private void checkForLongClick(int delayOffset) {
19773        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19774            mHasPerformedLongPress = false;
19775
19776            if (mPendingCheckForLongPress == null) {
19777                mPendingCheckForLongPress = new CheckForLongPress();
19778            }
19779            mPendingCheckForLongPress.rememberWindowAttachCount();
19780            postDelayed(mPendingCheckForLongPress,
19781                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19782        }
19783    }
19784
19785    /**
19786     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19787     * LayoutInflater} class, which provides a full range of options for view inflation.
19788     *
19789     * @param context The Context object for your activity or application.
19790     * @param resource The resource ID to inflate
19791     * @param root A view group that will be the parent.  Used to properly inflate the
19792     * layout_* parameters.
19793     * @see LayoutInflater
19794     */
19795    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19796        LayoutInflater factory = LayoutInflater.from(context);
19797        return factory.inflate(resource, root);
19798    }
19799
19800    /**
19801     * Scroll the view with standard behavior for scrolling beyond the normal
19802     * content boundaries. Views that call this method should override
19803     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19804     * results of an over-scroll operation.
19805     *
19806     * Views can use this method to handle any touch or fling-based scrolling.
19807     *
19808     * @param deltaX Change in X in pixels
19809     * @param deltaY Change in Y in pixels
19810     * @param scrollX Current X scroll value in pixels before applying deltaX
19811     * @param scrollY Current Y scroll value in pixels before applying deltaY
19812     * @param scrollRangeX Maximum content scroll range along the X axis
19813     * @param scrollRangeY Maximum content scroll range along the Y axis
19814     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19815     *          along the X axis.
19816     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19817     *          along the Y axis.
19818     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19819     * @return true if scrolling was clamped to an over-scroll boundary along either
19820     *          axis, false otherwise.
19821     */
19822    @SuppressWarnings({"UnusedParameters"})
19823    protected boolean overScrollBy(int deltaX, int deltaY,
19824            int scrollX, int scrollY,
19825            int scrollRangeX, int scrollRangeY,
19826            int maxOverScrollX, int maxOverScrollY,
19827            boolean isTouchEvent) {
19828        final int overScrollMode = mOverScrollMode;
19829        final boolean canScrollHorizontal =
19830                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19831        final boolean canScrollVertical =
19832                computeVerticalScrollRange() > computeVerticalScrollExtent();
19833        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19834                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19835        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19836                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19837
19838        int newScrollX = scrollX + deltaX;
19839        if (!overScrollHorizontal) {
19840            maxOverScrollX = 0;
19841        }
19842
19843        int newScrollY = scrollY + deltaY;
19844        if (!overScrollVertical) {
19845            maxOverScrollY = 0;
19846        }
19847
19848        // Clamp values if at the limits and record
19849        final int left = -maxOverScrollX;
19850        final int right = maxOverScrollX + scrollRangeX;
19851        final int top = -maxOverScrollY;
19852        final int bottom = maxOverScrollY + scrollRangeY;
19853
19854        boolean clampedX = false;
19855        if (newScrollX > right) {
19856            newScrollX = right;
19857            clampedX = true;
19858        } else if (newScrollX < left) {
19859            newScrollX = left;
19860            clampedX = true;
19861        }
19862
19863        boolean clampedY = false;
19864        if (newScrollY > bottom) {
19865            newScrollY = bottom;
19866            clampedY = true;
19867        } else if (newScrollY < top) {
19868            newScrollY = top;
19869            clampedY = true;
19870        }
19871
19872        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19873
19874        return clampedX || clampedY;
19875    }
19876
19877    /**
19878     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19879     * respond to the results of an over-scroll operation.
19880     *
19881     * @param scrollX New X scroll value in pixels
19882     * @param scrollY New Y scroll value in pixels
19883     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19884     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19885     */
19886    protected void onOverScrolled(int scrollX, int scrollY,
19887            boolean clampedX, boolean clampedY) {
19888        // Intentionally empty.
19889    }
19890
19891    /**
19892     * Returns the over-scroll mode for this view. The result will be
19893     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19894     * (allow over-scrolling only if the view content is larger than the container),
19895     * or {@link #OVER_SCROLL_NEVER}.
19896     *
19897     * @return This view's over-scroll mode.
19898     */
19899    public int getOverScrollMode() {
19900        return mOverScrollMode;
19901    }
19902
19903    /**
19904     * Set the over-scroll mode for this view. Valid over-scroll modes are
19905     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19906     * (allow over-scrolling only if the view content is larger than the container),
19907     * or {@link #OVER_SCROLL_NEVER}.
19908     *
19909     * Setting the over-scroll mode of a view will have an effect only if the
19910     * view is capable of scrolling.
19911     *
19912     * @param overScrollMode The new over-scroll mode for this view.
19913     */
19914    public void setOverScrollMode(int overScrollMode) {
19915        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19916                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19917                overScrollMode != OVER_SCROLL_NEVER) {
19918            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19919        }
19920        mOverScrollMode = overScrollMode;
19921    }
19922
19923    /**
19924     * Enable or disable nested scrolling for this view.
19925     *
19926     * <p>If this property is set to true the view will be permitted to initiate nested
19927     * scrolling operations with a compatible parent view in the current hierarchy. If this
19928     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19929     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19930     * the nested scroll.</p>
19931     *
19932     * @param enabled true to enable nested scrolling, false to disable
19933     *
19934     * @see #isNestedScrollingEnabled()
19935     */
19936    public void setNestedScrollingEnabled(boolean enabled) {
19937        if (enabled) {
19938            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19939        } else {
19940            stopNestedScroll();
19941            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19942        }
19943    }
19944
19945    /**
19946     * Returns true if nested scrolling is enabled for this view.
19947     *
19948     * <p>If nested scrolling is enabled and this View class implementation supports it,
19949     * this view will act as a nested scrolling child view when applicable, forwarding data
19950     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19951     * parent.</p>
19952     *
19953     * @return true if nested scrolling is enabled
19954     *
19955     * @see #setNestedScrollingEnabled(boolean)
19956     */
19957    public boolean isNestedScrollingEnabled() {
19958        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19959                PFLAG3_NESTED_SCROLLING_ENABLED;
19960    }
19961
19962    /**
19963     * Begin a nestable scroll operation along the given axes.
19964     *
19965     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19966     *
19967     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19968     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19969     * In the case of touch scrolling the nested scroll will be terminated automatically in
19970     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19971     * In the event of programmatic scrolling the caller must explicitly call
19972     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19973     *
19974     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19975     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19976     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19977     *
19978     * <p>At each incremental step of the scroll the caller should invoke
19979     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19980     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19981     * parent at least partially consumed the scroll and the caller should adjust the amount it
19982     * scrolls by.</p>
19983     *
19984     * <p>After applying the remainder of the scroll delta the caller should invoke
19985     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19986     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19987     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19988     * </p>
19989     *
19990     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19991     *             {@link #SCROLL_AXIS_VERTICAL}.
19992     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19993     *         the current gesture.
19994     *
19995     * @see #stopNestedScroll()
19996     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19997     * @see #dispatchNestedScroll(int, int, int, int, int[])
19998     */
19999    public boolean startNestedScroll(int axes) {
20000        if (hasNestedScrollingParent()) {
20001            // Already in progress
20002            return true;
20003        }
20004        if (isNestedScrollingEnabled()) {
20005            ViewParent p = getParent();
20006            View child = this;
20007            while (p != null) {
20008                try {
20009                    if (p.onStartNestedScroll(child, this, axes)) {
20010                        mNestedScrollingParent = p;
20011                        p.onNestedScrollAccepted(child, this, axes);
20012                        return true;
20013                    }
20014                } catch (AbstractMethodError e) {
20015                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
20016                            "method onStartNestedScroll", e);
20017                    // Allow the search upward to continue
20018                }
20019                if (p instanceof View) {
20020                    child = (View) p;
20021                }
20022                p = p.getParent();
20023            }
20024        }
20025        return false;
20026    }
20027
20028    /**
20029     * Stop a nested scroll in progress.
20030     *
20031     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
20032     *
20033     * @see #startNestedScroll(int)
20034     */
20035    public void stopNestedScroll() {
20036        if (mNestedScrollingParent != null) {
20037            mNestedScrollingParent.onStopNestedScroll(this);
20038            mNestedScrollingParent = null;
20039        }
20040    }
20041
20042    /**
20043     * Returns true if this view has a nested scrolling parent.
20044     *
20045     * <p>The presence of a nested scrolling parent indicates that this view has initiated
20046     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
20047     *
20048     * @return whether this view has a nested scrolling parent
20049     */
20050    public boolean hasNestedScrollingParent() {
20051        return mNestedScrollingParent != null;
20052    }
20053
20054    /**
20055     * Dispatch one step of a nested scroll in progress.
20056     *
20057     * <p>Implementations of views that support nested scrolling should call this to report
20058     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
20059     * is not currently in progress or nested scrolling is not
20060     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
20061     *
20062     * <p>Compatible View implementations should also call
20063     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
20064     * consuming a component of the scroll event themselves.</p>
20065     *
20066     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
20067     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
20068     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
20069     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
20070     * @param offsetInWindow Optional. If not null, on return this will contain the offset
20071     *                       in local view coordinates of this view from before this operation
20072     *                       to after it completes. View implementations may use this to adjust
20073     *                       expected input coordinate tracking.
20074     * @return true if the event was dispatched, false if it could not be dispatched.
20075     * @see #dispatchNestedPreScroll(int, int, int[], int[])
20076     */
20077    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
20078            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
20079        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20080            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
20081                int startX = 0;
20082                int startY = 0;
20083                if (offsetInWindow != null) {
20084                    getLocationInWindow(offsetInWindow);
20085                    startX = offsetInWindow[0];
20086                    startY = offsetInWindow[1];
20087                }
20088
20089                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
20090                        dxUnconsumed, dyUnconsumed);
20091
20092                if (offsetInWindow != null) {
20093                    getLocationInWindow(offsetInWindow);
20094                    offsetInWindow[0] -= startX;
20095                    offsetInWindow[1] -= startY;
20096                }
20097                return true;
20098            } else if (offsetInWindow != null) {
20099                // No motion, no dispatch. Keep offsetInWindow up to date.
20100                offsetInWindow[0] = 0;
20101                offsetInWindow[1] = 0;
20102            }
20103        }
20104        return false;
20105    }
20106
20107    /**
20108     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
20109     *
20110     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
20111     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
20112     * scrolling operation to consume some or all of the scroll operation before the child view
20113     * consumes it.</p>
20114     *
20115     * @param dx Horizontal scroll distance in pixels
20116     * @param dy Vertical scroll distance in pixels
20117     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
20118     *                 and consumed[1] the consumed dy.
20119     * @param offsetInWindow Optional. If not null, on return this will contain the offset
20120     *                       in local view coordinates of this view from before this operation
20121     *                       to after it completes. View implementations may use this to adjust
20122     *                       expected input coordinate tracking.
20123     * @return true if the parent consumed some or all of the scroll delta
20124     * @see #dispatchNestedScroll(int, int, int, int, int[])
20125     */
20126    public boolean dispatchNestedPreScroll(int dx, int dy,
20127            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
20128        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20129            if (dx != 0 || dy != 0) {
20130                int startX = 0;
20131                int startY = 0;
20132                if (offsetInWindow != null) {
20133                    getLocationInWindow(offsetInWindow);
20134                    startX = offsetInWindow[0];
20135                    startY = offsetInWindow[1];
20136                }
20137
20138                if (consumed == null) {
20139                    if (mTempNestedScrollConsumed == null) {
20140                        mTempNestedScrollConsumed = new int[2];
20141                    }
20142                    consumed = mTempNestedScrollConsumed;
20143                }
20144                consumed[0] = 0;
20145                consumed[1] = 0;
20146                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
20147
20148                if (offsetInWindow != null) {
20149                    getLocationInWindow(offsetInWindow);
20150                    offsetInWindow[0] -= startX;
20151                    offsetInWindow[1] -= startY;
20152                }
20153                return consumed[0] != 0 || consumed[1] != 0;
20154            } else if (offsetInWindow != null) {
20155                offsetInWindow[0] = 0;
20156                offsetInWindow[1] = 0;
20157            }
20158        }
20159        return false;
20160    }
20161
20162    /**
20163     * Dispatch a fling to a nested scrolling parent.
20164     *
20165     * <p>This method should be used to indicate that a nested scrolling child has detected
20166     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
20167     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
20168     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
20169     * along a scrollable axis.</p>
20170     *
20171     * <p>If a nested scrolling child view would normally fling but it is at the edge of
20172     * its own content, it can use this method to delegate the fling to its nested scrolling
20173     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
20174     *
20175     * @param velocityX Horizontal fling velocity in pixels per second
20176     * @param velocityY Vertical fling velocity in pixels per second
20177     * @param consumed true if the child consumed the fling, false otherwise
20178     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
20179     */
20180    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
20181        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20182            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
20183        }
20184        return false;
20185    }
20186
20187    /**
20188     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
20189     *
20190     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
20191     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
20192     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
20193     * before the child view consumes it. If this method returns <code>true</code>, a nested
20194     * parent view consumed the fling and this view should not scroll as a result.</p>
20195     *
20196     * <p>For a better user experience, only one view in a nested scrolling chain should consume
20197     * the fling at a time. If a parent view consumed the fling this method will return false.
20198     * Custom view implementations should account for this in two ways:</p>
20199     *
20200     * <ul>
20201     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
20202     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
20203     *     position regardless.</li>
20204     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
20205     *     even to settle back to a valid idle position.</li>
20206     * </ul>
20207     *
20208     * <p>Views should also not offer fling velocities to nested parent views along an axis
20209     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
20210     * should not offer a horizontal fling velocity to its parents since scrolling along that
20211     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
20212     *
20213     * @param velocityX Horizontal fling velocity in pixels per second
20214     * @param velocityY Vertical fling velocity in pixels per second
20215     * @return true if a nested scrolling parent consumed the fling
20216     */
20217    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
20218        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20219            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
20220        }
20221        return false;
20222    }
20223
20224    /**
20225     * Gets a scale factor that determines the distance the view should scroll
20226     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
20227     * @return The vertical scroll scale factor.
20228     * @hide
20229     */
20230    protected float getVerticalScrollFactor() {
20231        if (mVerticalScrollFactor == 0) {
20232            TypedValue outValue = new TypedValue();
20233            if (!mContext.getTheme().resolveAttribute(
20234                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
20235                throw new IllegalStateException(
20236                        "Expected theme to define listPreferredItemHeight.");
20237            }
20238            mVerticalScrollFactor = outValue.getDimension(
20239                    mContext.getResources().getDisplayMetrics());
20240        }
20241        return mVerticalScrollFactor;
20242    }
20243
20244    /**
20245     * Gets a scale factor that determines the distance the view should scroll
20246     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
20247     * @return The horizontal scroll scale factor.
20248     * @hide
20249     */
20250    protected float getHorizontalScrollFactor() {
20251        // TODO: Should use something else.
20252        return getVerticalScrollFactor();
20253    }
20254
20255    /**
20256     * Return the value specifying the text direction or policy that was set with
20257     * {@link #setTextDirection(int)}.
20258     *
20259     * @return the defined text direction. It can be one of:
20260     *
20261     * {@link #TEXT_DIRECTION_INHERIT},
20262     * {@link #TEXT_DIRECTION_FIRST_STRONG},
20263     * {@link #TEXT_DIRECTION_ANY_RTL},
20264     * {@link #TEXT_DIRECTION_LTR},
20265     * {@link #TEXT_DIRECTION_RTL},
20266     * {@link #TEXT_DIRECTION_LOCALE},
20267     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
20268     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
20269     *
20270     * @attr ref android.R.styleable#View_textDirection
20271     *
20272     * @hide
20273     */
20274    @ViewDebug.ExportedProperty(category = "text", mapping = {
20275            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
20276            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
20277            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
20278            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
20279            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
20280            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
20281            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
20282            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
20283    })
20284    public int getRawTextDirection() {
20285        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
20286    }
20287
20288    /**
20289     * Set the text direction.
20290     *
20291     * @param textDirection the direction to set. Should be one of:
20292     *
20293     * {@link #TEXT_DIRECTION_INHERIT},
20294     * {@link #TEXT_DIRECTION_FIRST_STRONG},
20295     * {@link #TEXT_DIRECTION_ANY_RTL},
20296     * {@link #TEXT_DIRECTION_LTR},
20297     * {@link #TEXT_DIRECTION_RTL},
20298     * {@link #TEXT_DIRECTION_LOCALE}
20299     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
20300     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
20301     *
20302     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
20303     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
20304     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
20305     *
20306     * @attr ref android.R.styleable#View_textDirection
20307     */
20308    public void setTextDirection(int textDirection) {
20309        if (getRawTextDirection() != textDirection) {
20310            // Reset the current text direction and the resolved one
20311            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
20312            resetResolvedTextDirection();
20313            // Set the new text direction
20314            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
20315            // Do resolution
20316            resolveTextDirection();
20317            // Notify change
20318            onRtlPropertiesChanged(getLayoutDirection());
20319            // Refresh
20320            requestLayout();
20321            invalidate(true);
20322        }
20323    }
20324
20325    /**
20326     * Return the resolved text direction.
20327     *
20328     * @return the resolved text direction. Returns one of:
20329     *
20330     * {@link #TEXT_DIRECTION_FIRST_STRONG},
20331     * {@link #TEXT_DIRECTION_ANY_RTL},
20332     * {@link #TEXT_DIRECTION_LTR},
20333     * {@link #TEXT_DIRECTION_RTL},
20334     * {@link #TEXT_DIRECTION_LOCALE},
20335     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
20336     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
20337     *
20338     * @attr ref android.R.styleable#View_textDirection
20339     */
20340    @ViewDebug.ExportedProperty(category = "text", mapping = {
20341            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
20342            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
20343            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
20344            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
20345            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
20346            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
20347            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
20348            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
20349    })
20350    public int getTextDirection() {
20351        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
20352    }
20353
20354    /**
20355     * Resolve the text direction.
20356     *
20357     * @return true if resolution has been done, false otherwise.
20358     *
20359     * @hide
20360     */
20361    public boolean resolveTextDirection() {
20362        // Reset any previous text direction resolution
20363        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
20364
20365        if (hasRtlSupport()) {
20366            // Set resolved text direction flag depending on text direction flag
20367            final int textDirection = getRawTextDirection();
20368            switch(textDirection) {
20369                case TEXT_DIRECTION_INHERIT:
20370                    if (!canResolveTextDirection()) {
20371                        // We cannot do the resolution if there is no parent, so use the default one
20372                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20373                        // Resolution will need to happen again later
20374                        return false;
20375                    }
20376
20377                    // Parent has not yet resolved, so we still return the default
20378                    try {
20379                        if (!mParent.isTextDirectionResolved()) {
20380                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20381                            // Resolution will need to happen again later
20382                            return false;
20383                        }
20384                    } catch (AbstractMethodError e) {
20385                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20386                                " does not fully implement ViewParent", e);
20387                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
20388                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20389                        return true;
20390                    }
20391
20392                    // Set current resolved direction to the same value as the parent's one
20393                    int parentResolvedDirection;
20394                    try {
20395                        parentResolvedDirection = mParent.getTextDirection();
20396                    } catch (AbstractMethodError e) {
20397                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20398                                " does not fully implement ViewParent", e);
20399                        parentResolvedDirection = TEXT_DIRECTION_LTR;
20400                    }
20401                    switch (parentResolvedDirection) {
20402                        case TEXT_DIRECTION_FIRST_STRONG:
20403                        case TEXT_DIRECTION_ANY_RTL:
20404                        case TEXT_DIRECTION_LTR:
20405                        case TEXT_DIRECTION_RTL:
20406                        case TEXT_DIRECTION_LOCALE:
20407                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
20408                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
20409                            mPrivateFlags2 |=
20410                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20411                            break;
20412                        default:
20413                            // Default resolved direction is "first strong" heuristic
20414                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20415                    }
20416                    break;
20417                case TEXT_DIRECTION_FIRST_STRONG:
20418                case TEXT_DIRECTION_ANY_RTL:
20419                case TEXT_DIRECTION_LTR:
20420                case TEXT_DIRECTION_RTL:
20421                case TEXT_DIRECTION_LOCALE:
20422                case TEXT_DIRECTION_FIRST_STRONG_LTR:
20423                case TEXT_DIRECTION_FIRST_STRONG_RTL:
20424                    // Resolved direction is the same as text direction
20425                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20426                    break;
20427                default:
20428                    // Default resolved direction is "first strong" heuristic
20429                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20430            }
20431        } else {
20432            // Default resolved direction is "first strong" heuristic
20433            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20434        }
20435
20436        // Set to resolved
20437        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
20438        return true;
20439    }
20440
20441    /**
20442     * Check if text direction resolution can be done.
20443     *
20444     * @return true if text direction resolution can be done otherwise return false.
20445     */
20446    public boolean canResolveTextDirection() {
20447        switch (getRawTextDirection()) {
20448            case TEXT_DIRECTION_INHERIT:
20449                if (mParent != null) {
20450                    try {
20451                        return mParent.canResolveTextDirection();
20452                    } catch (AbstractMethodError e) {
20453                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20454                                " does not fully implement ViewParent", e);
20455                    }
20456                }
20457                return false;
20458
20459            default:
20460                return true;
20461        }
20462    }
20463
20464    /**
20465     * Reset resolved text direction. Text direction will be resolved during a call to
20466     * {@link #onMeasure(int, int)}.
20467     *
20468     * @hide
20469     */
20470    public void resetResolvedTextDirection() {
20471        // Reset any previous text direction resolution
20472        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
20473        // Set to default value
20474        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20475    }
20476
20477    /**
20478     * @return true if text direction is inherited.
20479     *
20480     * @hide
20481     */
20482    public boolean isTextDirectionInherited() {
20483        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
20484    }
20485
20486    /**
20487     * @return true if text direction is resolved.
20488     */
20489    public boolean isTextDirectionResolved() {
20490        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
20491    }
20492
20493    /**
20494     * Return the value specifying the text alignment or policy that was set with
20495     * {@link #setTextAlignment(int)}.
20496     *
20497     * @return the defined text alignment. It can be one of:
20498     *
20499     * {@link #TEXT_ALIGNMENT_INHERIT},
20500     * {@link #TEXT_ALIGNMENT_GRAVITY},
20501     * {@link #TEXT_ALIGNMENT_CENTER},
20502     * {@link #TEXT_ALIGNMENT_TEXT_START},
20503     * {@link #TEXT_ALIGNMENT_TEXT_END},
20504     * {@link #TEXT_ALIGNMENT_VIEW_START},
20505     * {@link #TEXT_ALIGNMENT_VIEW_END}
20506     *
20507     * @attr ref android.R.styleable#View_textAlignment
20508     *
20509     * @hide
20510     */
20511    @ViewDebug.ExportedProperty(category = "text", mapping = {
20512            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20513            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20514            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20515            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20516            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20517            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20518            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20519    })
20520    @TextAlignment
20521    public int getRawTextAlignment() {
20522        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
20523    }
20524
20525    /**
20526     * Set the text alignment.
20527     *
20528     * @param textAlignment The text alignment to set. Should be one of
20529     *
20530     * {@link #TEXT_ALIGNMENT_INHERIT},
20531     * {@link #TEXT_ALIGNMENT_GRAVITY},
20532     * {@link #TEXT_ALIGNMENT_CENTER},
20533     * {@link #TEXT_ALIGNMENT_TEXT_START},
20534     * {@link #TEXT_ALIGNMENT_TEXT_END},
20535     * {@link #TEXT_ALIGNMENT_VIEW_START},
20536     * {@link #TEXT_ALIGNMENT_VIEW_END}
20537     *
20538     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
20539     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
20540     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
20541     *
20542     * @attr ref android.R.styleable#View_textAlignment
20543     */
20544    public void setTextAlignment(@TextAlignment int textAlignment) {
20545        if (textAlignment != getRawTextAlignment()) {
20546            // Reset the current and resolved text alignment
20547            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
20548            resetResolvedTextAlignment();
20549            // Set the new text alignment
20550            mPrivateFlags2 |=
20551                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
20552            // Do resolution
20553            resolveTextAlignment();
20554            // Notify change
20555            onRtlPropertiesChanged(getLayoutDirection());
20556            // Refresh
20557            requestLayout();
20558            invalidate(true);
20559        }
20560    }
20561
20562    /**
20563     * Return the resolved text alignment.
20564     *
20565     * @return the resolved text alignment. Returns one of:
20566     *
20567     * {@link #TEXT_ALIGNMENT_GRAVITY},
20568     * {@link #TEXT_ALIGNMENT_CENTER},
20569     * {@link #TEXT_ALIGNMENT_TEXT_START},
20570     * {@link #TEXT_ALIGNMENT_TEXT_END},
20571     * {@link #TEXT_ALIGNMENT_VIEW_START},
20572     * {@link #TEXT_ALIGNMENT_VIEW_END}
20573     *
20574     * @attr ref android.R.styleable#View_textAlignment
20575     */
20576    @ViewDebug.ExportedProperty(category = "text", mapping = {
20577            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20578            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20579            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20580            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20581            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20582            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20583            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20584    })
20585    @TextAlignment
20586    public int getTextAlignment() {
20587        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
20588                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
20589    }
20590
20591    /**
20592     * Resolve the text alignment.
20593     *
20594     * @return true if resolution has been done, false otherwise.
20595     *
20596     * @hide
20597     */
20598    public boolean resolveTextAlignment() {
20599        // Reset any previous text alignment resolution
20600        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20601
20602        if (hasRtlSupport()) {
20603            // Set resolved text alignment flag depending on text alignment flag
20604            final int textAlignment = getRawTextAlignment();
20605            switch (textAlignment) {
20606                case TEXT_ALIGNMENT_INHERIT:
20607                    // Check if we can resolve the text alignment
20608                    if (!canResolveTextAlignment()) {
20609                        // We cannot do the resolution if there is no parent so use the default
20610                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20611                        // Resolution will need to happen again later
20612                        return false;
20613                    }
20614
20615                    // Parent has not yet resolved, so we still return the default
20616                    try {
20617                        if (!mParent.isTextAlignmentResolved()) {
20618                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20619                            // Resolution will need to happen again later
20620                            return false;
20621                        }
20622                    } catch (AbstractMethodError e) {
20623                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20624                                " does not fully implement ViewParent", e);
20625                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
20626                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20627                        return true;
20628                    }
20629
20630                    int parentResolvedTextAlignment;
20631                    try {
20632                        parentResolvedTextAlignment = mParent.getTextAlignment();
20633                    } catch (AbstractMethodError e) {
20634                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20635                                " does not fully implement ViewParent", e);
20636                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
20637                    }
20638                    switch (parentResolvedTextAlignment) {
20639                        case TEXT_ALIGNMENT_GRAVITY:
20640                        case TEXT_ALIGNMENT_TEXT_START:
20641                        case TEXT_ALIGNMENT_TEXT_END:
20642                        case TEXT_ALIGNMENT_CENTER:
20643                        case TEXT_ALIGNMENT_VIEW_START:
20644                        case TEXT_ALIGNMENT_VIEW_END:
20645                            // Resolved text alignment is the same as the parent resolved
20646                            // text alignment
20647                            mPrivateFlags2 |=
20648                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20649                            break;
20650                        default:
20651                            // Use default resolved text alignment
20652                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20653                    }
20654                    break;
20655                case TEXT_ALIGNMENT_GRAVITY:
20656                case TEXT_ALIGNMENT_TEXT_START:
20657                case TEXT_ALIGNMENT_TEXT_END:
20658                case TEXT_ALIGNMENT_CENTER:
20659                case TEXT_ALIGNMENT_VIEW_START:
20660                case TEXT_ALIGNMENT_VIEW_END:
20661                    // Resolved text alignment is the same as text alignment
20662                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20663                    break;
20664                default:
20665                    // Use default resolved text alignment
20666                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20667            }
20668        } else {
20669            // Use default resolved text alignment
20670            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20671        }
20672
20673        // Set the resolved
20674        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20675        return true;
20676    }
20677
20678    /**
20679     * Check if text alignment resolution can be done.
20680     *
20681     * @return true if text alignment resolution can be done otherwise return false.
20682     */
20683    public boolean canResolveTextAlignment() {
20684        switch (getRawTextAlignment()) {
20685            case TEXT_DIRECTION_INHERIT:
20686                if (mParent != null) {
20687                    try {
20688                        return mParent.canResolveTextAlignment();
20689                    } catch (AbstractMethodError e) {
20690                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20691                                " does not fully implement ViewParent", e);
20692                    }
20693                }
20694                return false;
20695
20696            default:
20697                return true;
20698        }
20699    }
20700
20701    /**
20702     * Reset resolved text alignment. Text alignment will be resolved during a call to
20703     * {@link #onMeasure(int, int)}.
20704     *
20705     * @hide
20706     */
20707    public void resetResolvedTextAlignment() {
20708        // Reset any previous text alignment resolution
20709        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20710        // Set to default
20711        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20712    }
20713
20714    /**
20715     * @return true if text alignment is inherited.
20716     *
20717     * @hide
20718     */
20719    public boolean isTextAlignmentInherited() {
20720        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20721    }
20722
20723    /**
20724     * @return true if text alignment is resolved.
20725     */
20726    public boolean isTextAlignmentResolved() {
20727        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20728    }
20729
20730    /**
20731     * Generate a value suitable for use in {@link #setId(int)}.
20732     * This value will not collide with ID values generated at build time by aapt for R.id.
20733     *
20734     * @return a generated ID value
20735     */
20736    public static int generateViewId() {
20737        for (;;) {
20738            final int result = sNextGeneratedId.get();
20739            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20740            int newValue = result + 1;
20741            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20742            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20743                return result;
20744            }
20745        }
20746    }
20747
20748    /**
20749     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20750     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20751     *                           a normal View or a ViewGroup with
20752     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20753     * @hide
20754     */
20755    public void captureTransitioningViews(List<View> transitioningViews) {
20756        if (getVisibility() == View.VISIBLE) {
20757            transitioningViews.add(this);
20758        }
20759    }
20760
20761    /**
20762     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20763     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20764     * @hide
20765     */
20766    public void findNamedViews(Map<String, View> namedElements) {
20767        if (getVisibility() == VISIBLE || mGhostView != null) {
20768            String transitionName = getTransitionName();
20769            if (transitionName != null) {
20770                namedElements.put(transitionName, this);
20771            }
20772        }
20773    }
20774
20775    //
20776    // Properties
20777    //
20778    /**
20779     * A Property wrapper around the <code>alpha</code> functionality handled by the
20780     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20781     */
20782    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20783        @Override
20784        public void setValue(View object, float value) {
20785            object.setAlpha(value);
20786        }
20787
20788        @Override
20789        public Float get(View object) {
20790            return object.getAlpha();
20791        }
20792    };
20793
20794    /**
20795     * A Property wrapper around the <code>translationX</code> functionality handled by the
20796     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20797     */
20798    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20799        @Override
20800        public void setValue(View object, float value) {
20801            object.setTranslationX(value);
20802        }
20803
20804                @Override
20805        public Float get(View object) {
20806            return object.getTranslationX();
20807        }
20808    };
20809
20810    /**
20811     * A Property wrapper around the <code>translationY</code> functionality handled by the
20812     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20813     */
20814    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20815        @Override
20816        public void setValue(View object, float value) {
20817            object.setTranslationY(value);
20818        }
20819
20820        @Override
20821        public Float get(View object) {
20822            return object.getTranslationY();
20823        }
20824    };
20825
20826    /**
20827     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20828     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20829     */
20830    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20831        @Override
20832        public void setValue(View object, float value) {
20833            object.setTranslationZ(value);
20834        }
20835
20836        @Override
20837        public Float get(View object) {
20838            return object.getTranslationZ();
20839        }
20840    };
20841
20842    /**
20843     * A Property wrapper around the <code>x</code> functionality handled by the
20844     * {@link View#setX(float)} and {@link View#getX()} methods.
20845     */
20846    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20847        @Override
20848        public void setValue(View object, float value) {
20849            object.setX(value);
20850        }
20851
20852        @Override
20853        public Float get(View object) {
20854            return object.getX();
20855        }
20856    };
20857
20858    /**
20859     * A Property wrapper around the <code>y</code> functionality handled by the
20860     * {@link View#setY(float)} and {@link View#getY()} methods.
20861     */
20862    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20863        @Override
20864        public void setValue(View object, float value) {
20865            object.setY(value);
20866        }
20867
20868        @Override
20869        public Float get(View object) {
20870            return object.getY();
20871        }
20872    };
20873
20874    /**
20875     * A Property wrapper around the <code>z</code> functionality handled by the
20876     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20877     */
20878    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20879        @Override
20880        public void setValue(View object, float value) {
20881            object.setZ(value);
20882        }
20883
20884        @Override
20885        public Float get(View object) {
20886            return object.getZ();
20887        }
20888    };
20889
20890    /**
20891     * A Property wrapper around the <code>rotation</code> functionality handled by the
20892     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20893     */
20894    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20895        @Override
20896        public void setValue(View object, float value) {
20897            object.setRotation(value);
20898        }
20899
20900        @Override
20901        public Float get(View object) {
20902            return object.getRotation();
20903        }
20904    };
20905
20906    /**
20907     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20908     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20909     */
20910    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20911        @Override
20912        public void setValue(View object, float value) {
20913            object.setRotationX(value);
20914        }
20915
20916        @Override
20917        public Float get(View object) {
20918            return object.getRotationX();
20919        }
20920    };
20921
20922    /**
20923     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20924     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20925     */
20926    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20927        @Override
20928        public void setValue(View object, float value) {
20929            object.setRotationY(value);
20930        }
20931
20932        @Override
20933        public Float get(View object) {
20934            return object.getRotationY();
20935        }
20936    };
20937
20938    /**
20939     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20940     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20941     */
20942    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20943        @Override
20944        public void setValue(View object, float value) {
20945            object.setScaleX(value);
20946        }
20947
20948        @Override
20949        public Float get(View object) {
20950            return object.getScaleX();
20951        }
20952    };
20953
20954    /**
20955     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20956     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20957     */
20958    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20959        @Override
20960        public void setValue(View object, float value) {
20961            object.setScaleY(value);
20962        }
20963
20964        @Override
20965        public Float get(View object) {
20966            return object.getScaleY();
20967        }
20968    };
20969
20970    /**
20971     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20972     * Each MeasureSpec represents a requirement for either the width or the height.
20973     * A MeasureSpec is comprised of a size and a mode. There are three possible
20974     * modes:
20975     * <dl>
20976     * <dt>UNSPECIFIED</dt>
20977     * <dd>
20978     * The parent has not imposed any constraint on the child. It can be whatever size
20979     * it wants.
20980     * </dd>
20981     *
20982     * <dt>EXACTLY</dt>
20983     * <dd>
20984     * The parent has determined an exact size for the child. The child is going to be
20985     * given those bounds regardless of how big it wants to be.
20986     * </dd>
20987     *
20988     * <dt>AT_MOST</dt>
20989     * <dd>
20990     * The child can be as large as it wants up to the specified size.
20991     * </dd>
20992     * </dl>
20993     *
20994     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20995     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20996     */
20997    public static class MeasureSpec {
20998        private static final int MODE_SHIFT = 30;
20999        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
21000
21001        /**
21002         * Measure specification mode: The parent has not imposed any constraint
21003         * on the child. It can be whatever size it wants.
21004         */
21005        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
21006
21007        /**
21008         * Measure specification mode: The parent has determined an exact size
21009         * for the child. The child is going to be given those bounds regardless
21010         * of how big it wants to be.
21011         */
21012        public static final int EXACTLY     = 1 << MODE_SHIFT;
21013
21014        /**
21015         * Measure specification mode: The child can be as large as it wants up
21016         * to the specified size.
21017         */
21018        public static final int AT_MOST     = 2 << MODE_SHIFT;
21019
21020        /**
21021         * Creates a measure specification based on the supplied size and mode.
21022         *
21023         * The mode must always be one of the following:
21024         * <ul>
21025         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
21026         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
21027         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
21028         * </ul>
21029         *
21030         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
21031         * implementation was such that the order of arguments did not matter
21032         * and overflow in either value could impact the resulting MeasureSpec.
21033         * {@link android.widget.RelativeLayout} was affected by this bug.
21034         * Apps targeting API levels greater than 17 will get the fixed, more strict
21035         * behavior.</p>
21036         *
21037         * @param size the size of the measure specification
21038         * @param mode the mode of the measure specification
21039         * @return the measure specification based on size and mode
21040         */
21041        public static int makeMeasureSpec(int size, int mode) {
21042            if (sUseBrokenMakeMeasureSpec) {
21043                return size + mode;
21044            } else {
21045                return (size & ~MODE_MASK) | (mode & MODE_MASK);
21046            }
21047        }
21048
21049        /**
21050         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
21051         * will automatically get a size of 0. Older apps expect this.
21052         *
21053         * @hide internal use only for compatibility with system widgets and older apps
21054         */
21055        public static int makeSafeMeasureSpec(int size, int mode) {
21056            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
21057                return 0;
21058            }
21059            return makeMeasureSpec(size, mode);
21060        }
21061
21062        /**
21063         * Extracts the mode from the supplied measure specification.
21064         *
21065         * @param measureSpec the measure specification to extract the mode from
21066         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
21067         *         {@link android.view.View.MeasureSpec#AT_MOST} or
21068         *         {@link android.view.View.MeasureSpec#EXACTLY}
21069         */
21070        public static int getMode(int measureSpec) {
21071            return (measureSpec & MODE_MASK);
21072        }
21073
21074        /**
21075         * Extracts the size from the supplied measure specification.
21076         *
21077         * @param measureSpec the measure specification to extract the size from
21078         * @return the size in pixels defined in the supplied measure specification
21079         */
21080        public static int getSize(int measureSpec) {
21081            return (measureSpec & ~MODE_MASK);
21082        }
21083
21084        static int adjust(int measureSpec, int delta) {
21085            final int mode = getMode(measureSpec);
21086            int size = getSize(measureSpec);
21087            if (mode == UNSPECIFIED) {
21088                // No need to adjust size for UNSPECIFIED mode.
21089                return makeMeasureSpec(size, UNSPECIFIED);
21090            }
21091            size += delta;
21092            if (size < 0) {
21093                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
21094                        ") spec: " + toString(measureSpec) + " delta: " + delta);
21095                size = 0;
21096            }
21097            return makeMeasureSpec(size, mode);
21098        }
21099
21100        /**
21101         * Returns a String representation of the specified measure
21102         * specification.
21103         *
21104         * @param measureSpec the measure specification to convert to a String
21105         * @return a String with the following format: "MeasureSpec: MODE SIZE"
21106         */
21107        public static String toString(int measureSpec) {
21108            int mode = getMode(measureSpec);
21109            int size = getSize(measureSpec);
21110
21111            StringBuilder sb = new StringBuilder("MeasureSpec: ");
21112
21113            if (mode == UNSPECIFIED)
21114                sb.append("UNSPECIFIED ");
21115            else if (mode == EXACTLY)
21116                sb.append("EXACTLY ");
21117            else if (mode == AT_MOST)
21118                sb.append("AT_MOST ");
21119            else
21120                sb.append(mode).append(" ");
21121
21122            sb.append(size);
21123            return sb.toString();
21124        }
21125    }
21126
21127    private final class CheckForLongPress implements Runnable {
21128        private int mOriginalWindowAttachCount;
21129
21130        @Override
21131        public void run() {
21132            if (isPressed() && (mParent != null)
21133                    && mOriginalWindowAttachCount == mWindowAttachCount) {
21134                if (performLongClick()) {
21135                    mHasPerformedLongPress = true;
21136                }
21137            }
21138        }
21139
21140        public void rememberWindowAttachCount() {
21141            mOriginalWindowAttachCount = mWindowAttachCount;
21142        }
21143    }
21144
21145    private final class CheckForTap implements Runnable {
21146        public float x;
21147        public float y;
21148
21149        @Override
21150        public void run() {
21151            mPrivateFlags &= ~PFLAG_PREPRESSED;
21152            setPressed(true, x, y);
21153            checkForLongClick(ViewConfiguration.getTapTimeout());
21154        }
21155    }
21156
21157    private final class PerformClick implements Runnable {
21158        @Override
21159        public void run() {
21160            performClick();
21161        }
21162    }
21163
21164    /**
21165     * This method returns a ViewPropertyAnimator object, which can be used to animate
21166     * specific properties on this View.
21167     *
21168     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
21169     */
21170    public ViewPropertyAnimator animate() {
21171        if (mAnimator == null) {
21172            mAnimator = new ViewPropertyAnimator(this);
21173        }
21174        return mAnimator;
21175    }
21176
21177    /**
21178     * Sets the name of the View to be used to identify Views in Transitions.
21179     * Names should be unique in the View hierarchy.
21180     *
21181     * @param transitionName The name of the View to uniquely identify it for Transitions.
21182     */
21183    public final void setTransitionName(String transitionName) {
21184        mTransitionName = transitionName;
21185    }
21186
21187    /**
21188     * Returns the name of the View to be used to identify Views in Transitions.
21189     * Names should be unique in the View hierarchy.
21190     *
21191     * <p>This returns null if the View has not been given a name.</p>
21192     *
21193     * @return The name used of the View to be used to identify Views in Transitions or null
21194     * if no name has been given.
21195     */
21196    @ViewDebug.ExportedProperty
21197    public String getTransitionName() {
21198        return mTransitionName;
21199    }
21200
21201    /**
21202     * Interface definition for a callback to be invoked when a hardware key event is
21203     * dispatched to this view. The callback will be invoked before the key event is
21204     * given to the view. This is only useful for hardware keyboards; a software input
21205     * method has no obligation to trigger this listener.
21206     */
21207    public interface OnKeyListener {
21208        /**
21209         * Called when a hardware key is dispatched to a view. This allows listeners to
21210         * get a chance to respond before the target view.
21211         * <p>Key presses in software keyboards will generally NOT trigger this method,
21212         * although some may elect to do so in some situations. Do not assume a
21213         * software input method has to be key-based; even if it is, it may use key presses
21214         * in a different way than you expect, so there is no way to reliably catch soft
21215         * input key presses.
21216         *
21217         * @param v The view the key has been dispatched to.
21218         * @param keyCode The code for the physical key that was pressed
21219         * @param event The KeyEvent object containing full information about
21220         *        the event.
21221         * @return True if the listener has consumed the event, false otherwise.
21222         */
21223        boolean onKey(View v, int keyCode, KeyEvent event);
21224    }
21225
21226    /**
21227     * Interface definition for a callback to be invoked when a touch event is
21228     * dispatched to this view. The callback will be invoked before the touch
21229     * event is given to the view.
21230     */
21231    public interface OnTouchListener {
21232        /**
21233         * Called when a touch event is dispatched to a view. This allows listeners to
21234         * get a chance to respond before the target view.
21235         *
21236         * @param v The view the touch event has been dispatched to.
21237         * @param event The MotionEvent object containing full information about
21238         *        the event.
21239         * @return True if the listener has consumed the event, false otherwise.
21240         */
21241        boolean onTouch(View v, MotionEvent event);
21242    }
21243
21244    /**
21245     * Interface definition for a callback to be invoked when a hover event is
21246     * dispatched to this view. The callback will be invoked before the hover
21247     * event is given to the view.
21248     */
21249    public interface OnHoverListener {
21250        /**
21251         * Called when a hover event is dispatched to a view. This allows listeners to
21252         * get a chance to respond before the target view.
21253         *
21254         * @param v The view the hover event has been dispatched to.
21255         * @param event The MotionEvent object containing full information about
21256         *        the event.
21257         * @return True if the listener has consumed the event, false otherwise.
21258         */
21259        boolean onHover(View v, MotionEvent event);
21260    }
21261
21262    /**
21263     * Interface definition for a callback to be invoked when a generic motion event is
21264     * dispatched to this view. The callback will be invoked before the generic motion
21265     * event is given to the view.
21266     */
21267    public interface OnGenericMotionListener {
21268        /**
21269         * Called when a generic motion event is dispatched to a view. This allows listeners to
21270         * get a chance to respond before the target view.
21271         *
21272         * @param v The view the generic motion event has been dispatched to.
21273         * @param event The MotionEvent object containing full information about
21274         *        the event.
21275         * @return True if the listener has consumed the event, false otherwise.
21276         */
21277        boolean onGenericMotion(View v, MotionEvent event);
21278    }
21279
21280    /**
21281     * Interface definition for a callback to be invoked when a view has been clicked and held.
21282     */
21283    public interface OnLongClickListener {
21284        /**
21285         * Called when a view has been clicked and held.
21286         *
21287         * @param v The view that was clicked and held.
21288         *
21289         * @return true if the callback consumed the long click, false otherwise.
21290         */
21291        boolean onLongClick(View v);
21292    }
21293
21294    /**
21295     * Interface definition for a callback to be invoked when a drag is being dispatched
21296     * to this view.  The callback will be invoked before the hosting view's own
21297     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
21298     * onDrag(event) behavior, it should return 'false' from this callback.
21299     *
21300     * <div class="special reference">
21301     * <h3>Developer Guides</h3>
21302     * <p>For a guide to implementing drag and drop features, read the
21303     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21304     * </div>
21305     */
21306    public interface OnDragListener {
21307        /**
21308         * Called when a drag event is dispatched to a view. This allows listeners
21309         * to get a chance to override base View behavior.
21310         *
21311         * @param v The View that received the drag event.
21312         * @param event The {@link android.view.DragEvent} object for the drag event.
21313         * @return {@code true} if the drag event was handled successfully, or {@code false}
21314         * if the drag event was not handled. Note that {@code false} will trigger the View
21315         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
21316         */
21317        boolean onDrag(View v, DragEvent event);
21318    }
21319
21320    /**
21321     * Interface definition for a callback to be invoked when the focus state of
21322     * a view changed.
21323     */
21324    public interface OnFocusChangeListener {
21325        /**
21326         * Called when the focus state of a view has changed.
21327         *
21328         * @param v The view whose state has changed.
21329         * @param hasFocus The new focus state of v.
21330         */
21331        void onFocusChange(View v, boolean hasFocus);
21332    }
21333
21334    /**
21335     * Interface definition for a callback to be invoked when a view is clicked.
21336     */
21337    public interface OnClickListener {
21338        /**
21339         * Called when a view has been clicked.
21340         *
21341         * @param v The view that was clicked.
21342         */
21343        void onClick(View v);
21344    }
21345
21346    /**
21347     * Interface definition for a callback to be invoked when a view is context clicked.
21348     */
21349    public interface OnContextClickListener {
21350        /**
21351         * Called when a view is context clicked.
21352         *
21353         * @param v The view that has been context clicked.
21354         * @return true if the callback consumed the context click, false otherwise.
21355         */
21356        boolean onContextClick(View v);
21357    }
21358
21359    /**
21360     * Interface definition for a callback to be invoked when the context menu
21361     * for this view is being built.
21362     */
21363    public interface OnCreateContextMenuListener {
21364        /**
21365         * Called when the context menu for this view is being built. It is not
21366         * safe to hold onto the menu after this method returns.
21367         *
21368         * @param menu The context menu that is being built
21369         * @param v The view for which the context menu is being built
21370         * @param menuInfo Extra information about the item for which the
21371         *            context menu should be shown. This information will vary
21372         *            depending on the class of v.
21373         */
21374        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
21375    }
21376
21377    /**
21378     * Interface definition for a callback to be invoked when the status bar changes
21379     * visibility.  This reports <strong>global</strong> changes to the system UI
21380     * state, not what the application is requesting.
21381     *
21382     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
21383     */
21384    public interface OnSystemUiVisibilityChangeListener {
21385        /**
21386         * Called when the status bar changes visibility because of a call to
21387         * {@link View#setSystemUiVisibility(int)}.
21388         *
21389         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21390         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
21391         * This tells you the <strong>global</strong> state of these UI visibility
21392         * flags, not what your app is currently applying.
21393         */
21394        public void onSystemUiVisibilityChange(int visibility);
21395    }
21396
21397    /**
21398     * Interface definition for a callback to be invoked when this view is attached
21399     * or detached from its window.
21400     */
21401    public interface OnAttachStateChangeListener {
21402        /**
21403         * Called when the view is attached to a window.
21404         * @param v The view that was attached
21405         */
21406        public void onViewAttachedToWindow(View v);
21407        /**
21408         * Called when the view is detached from a window.
21409         * @param v The view that was detached
21410         */
21411        public void onViewDetachedFromWindow(View v);
21412    }
21413
21414    /**
21415     * Listener for applying window insets on a view in a custom way.
21416     *
21417     * <p>Apps may choose to implement this interface if they want to apply custom policy
21418     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
21419     * is set, its
21420     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
21421     * method will be called instead of the View's own
21422     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
21423     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
21424     * the View's normal behavior as part of its own.</p>
21425     */
21426    public interface OnApplyWindowInsetsListener {
21427        /**
21428         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
21429         * on a View, this listener method will be called instead of the view's own
21430         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
21431         *
21432         * @param v The view applying window insets
21433         * @param insets The insets to apply
21434         * @return The insets supplied, minus any insets that were consumed
21435         */
21436        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
21437    }
21438
21439    private final class UnsetPressedState implements Runnable {
21440        @Override
21441        public void run() {
21442            setPressed(false);
21443        }
21444    }
21445
21446    /**
21447     * Base class for derived classes that want to save and restore their own
21448     * state in {@link android.view.View#onSaveInstanceState()}.
21449     */
21450    public static class BaseSavedState extends AbsSavedState {
21451        String mStartActivityRequestWhoSaved;
21452
21453        /**
21454         * Constructor used when reading from a parcel. Reads the state of the superclass.
21455         *
21456         * @param source
21457         */
21458        public BaseSavedState(Parcel source) {
21459            super(source);
21460            mStartActivityRequestWhoSaved = source.readString();
21461        }
21462
21463        /**
21464         * Constructor called by derived classes when creating their SavedState objects
21465         *
21466         * @param superState The state of the superclass of this view
21467         */
21468        public BaseSavedState(Parcelable superState) {
21469            super(superState);
21470        }
21471
21472        @Override
21473        public void writeToParcel(Parcel out, int flags) {
21474            super.writeToParcel(out, flags);
21475            out.writeString(mStartActivityRequestWhoSaved);
21476        }
21477
21478        public static final Parcelable.Creator<BaseSavedState> CREATOR =
21479                new Parcelable.Creator<BaseSavedState>() {
21480            public BaseSavedState createFromParcel(Parcel in) {
21481                return new BaseSavedState(in);
21482            }
21483
21484            public BaseSavedState[] newArray(int size) {
21485                return new BaseSavedState[size];
21486            }
21487        };
21488    }
21489
21490    /**
21491     * A set of information given to a view when it is attached to its parent
21492     * window.
21493     */
21494    final static class AttachInfo {
21495        interface Callbacks {
21496            void playSoundEffect(int effectId);
21497            boolean performHapticFeedback(int effectId, boolean always);
21498        }
21499
21500        /**
21501         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
21502         * to a Handler. This class contains the target (View) to invalidate and
21503         * the coordinates of the dirty rectangle.
21504         *
21505         * For performance purposes, this class also implements a pool of up to
21506         * POOL_LIMIT objects that get reused. This reduces memory allocations
21507         * whenever possible.
21508         */
21509        static class InvalidateInfo {
21510            private static final int POOL_LIMIT = 10;
21511
21512            private static final SynchronizedPool<InvalidateInfo> sPool =
21513                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
21514
21515            View target;
21516
21517            int left;
21518            int top;
21519            int right;
21520            int bottom;
21521
21522            public static InvalidateInfo obtain() {
21523                InvalidateInfo instance = sPool.acquire();
21524                return (instance != null) ? instance : new InvalidateInfo();
21525            }
21526
21527            public void recycle() {
21528                target = null;
21529                sPool.release(this);
21530            }
21531        }
21532
21533        final IWindowSession mSession;
21534
21535        final IWindow mWindow;
21536
21537        final IBinder mWindowToken;
21538
21539        final Display mDisplay;
21540
21541        final Callbacks mRootCallbacks;
21542
21543        IWindowId mIWindowId;
21544        WindowId mWindowId;
21545
21546        /**
21547         * The top view of the hierarchy.
21548         */
21549        View mRootView;
21550
21551        IBinder mPanelParentWindowToken;
21552
21553        boolean mHardwareAccelerated;
21554        boolean mHardwareAccelerationRequested;
21555        HardwareRenderer mHardwareRenderer;
21556        List<RenderNode> mPendingAnimatingRenderNodes;
21557
21558        /**
21559         * The state of the display to which the window is attached, as reported
21560         * by {@link Display#getState()}.  Note that the display state constants
21561         * declared by {@link Display} do not exactly line up with the screen state
21562         * constants declared by {@link View} (there are more display states than
21563         * screen states).
21564         */
21565        int mDisplayState = Display.STATE_UNKNOWN;
21566
21567        /**
21568         * Scale factor used by the compatibility mode
21569         */
21570        float mApplicationScale;
21571
21572        /**
21573         * Indicates whether the application is in compatibility mode
21574         */
21575        boolean mScalingRequired;
21576
21577        /**
21578         * Left position of this view's window
21579         */
21580        int mWindowLeft;
21581
21582        /**
21583         * Top position of this view's window
21584         */
21585        int mWindowTop;
21586
21587        /**
21588         * Indicates whether views need to use 32-bit drawing caches
21589         */
21590        boolean mUse32BitDrawingCache;
21591
21592        /**
21593         * For windows that are full-screen but using insets to layout inside
21594         * of the screen areas, these are the current insets to appear inside
21595         * the overscan area of the display.
21596         */
21597        final Rect mOverscanInsets = new Rect();
21598
21599        /**
21600         * For windows that are full-screen but using insets to layout inside
21601         * of the screen decorations, these are the current insets for the
21602         * content of the window.
21603         */
21604        final Rect mContentInsets = new Rect();
21605
21606        /**
21607         * For windows that are full-screen but using insets to layout inside
21608         * of the screen decorations, these are the current insets for the
21609         * actual visible parts of the window.
21610         */
21611        final Rect mVisibleInsets = new Rect();
21612
21613        /**
21614         * For windows that are full-screen but using insets to layout inside
21615         * of the screen decorations, these are the current insets for the
21616         * stable system windows.
21617         */
21618        final Rect mStableInsets = new Rect();
21619
21620        /**
21621         * For windows that include areas that are not covered by real surface these are the outsets
21622         * for real surface.
21623         */
21624        final Rect mOutsets = new Rect();
21625
21626        /**
21627         * The internal insets given by this window.  This value is
21628         * supplied by the client (through
21629         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
21630         * be given to the window manager when changed to be used in laying
21631         * out windows behind it.
21632         */
21633        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
21634                = new ViewTreeObserver.InternalInsetsInfo();
21635
21636        /**
21637         * Set to true when mGivenInternalInsets is non-empty.
21638         */
21639        boolean mHasNonEmptyGivenInternalInsets;
21640
21641        /**
21642         * All views in the window's hierarchy that serve as scroll containers,
21643         * used to determine if the window can be resized or must be panned
21644         * to adjust for a soft input area.
21645         */
21646        final ArrayList<View> mScrollContainers = new ArrayList<View>();
21647
21648        final KeyEvent.DispatcherState mKeyDispatchState
21649                = new KeyEvent.DispatcherState();
21650
21651        /**
21652         * Indicates whether the view's window currently has the focus.
21653         */
21654        boolean mHasWindowFocus;
21655
21656        /**
21657         * The current visibility of the window.
21658         */
21659        int mWindowVisibility;
21660
21661        /**
21662         * Indicates the time at which drawing started to occur.
21663         */
21664        long mDrawingTime;
21665
21666        /**
21667         * Indicates whether or not ignoring the DIRTY_MASK flags.
21668         */
21669        boolean mIgnoreDirtyState;
21670
21671        /**
21672         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21673         * to avoid clearing that flag prematurely.
21674         */
21675        boolean mSetIgnoreDirtyState = false;
21676
21677        /**
21678         * Indicates whether the view's window is currently in touch mode.
21679         */
21680        boolean mInTouchMode;
21681
21682        /**
21683         * Indicates whether the view has requested unbuffered input dispatching for the current
21684         * event stream.
21685         */
21686        boolean mUnbufferedDispatchRequested;
21687
21688        /**
21689         * Indicates that ViewAncestor should trigger a global layout change
21690         * the next time it performs a traversal
21691         */
21692        boolean mRecomputeGlobalAttributes;
21693
21694        /**
21695         * Always report new attributes at next traversal.
21696         */
21697        boolean mForceReportNewAttributes;
21698
21699        /**
21700         * Set during a traveral if any views want to keep the screen on.
21701         */
21702        boolean mKeepScreenOn;
21703
21704        /**
21705         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21706         */
21707        int mSystemUiVisibility;
21708
21709        /**
21710         * Hack to force certain system UI visibility flags to be cleared.
21711         */
21712        int mDisabledSystemUiVisibility;
21713
21714        /**
21715         * Last global system UI visibility reported by the window manager.
21716         */
21717        int mGlobalSystemUiVisibility;
21718
21719        /**
21720         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21721         * attached.
21722         */
21723        boolean mHasSystemUiListeners;
21724
21725        /**
21726         * Set if the window has requested to extend into the overscan region
21727         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21728         */
21729        boolean mOverscanRequested;
21730
21731        /**
21732         * Set if the visibility of any views has changed.
21733         */
21734        boolean mViewVisibilityChanged;
21735
21736        /**
21737         * Set to true if a view has been scrolled.
21738         */
21739        boolean mViewScrollChanged;
21740
21741        /**
21742         * Set to true if high contrast mode enabled
21743         */
21744        boolean mHighContrastText;
21745
21746        /**
21747         * Global to the view hierarchy used as a temporary for dealing with
21748         * x/y points in the transparent region computations.
21749         */
21750        final int[] mTransparentLocation = new int[2];
21751
21752        /**
21753         * Global to the view hierarchy used as a temporary for dealing with
21754         * x/y points in the ViewGroup.invalidateChild implementation.
21755         */
21756        final int[] mInvalidateChildLocation = new int[2];
21757
21758        /**
21759         * Global to the view hierarchy used as a temporary for dealng with
21760         * computing absolute on-screen location.
21761         */
21762        final int[] mTmpLocation = new int[2];
21763
21764        /**
21765         * Global to the view hierarchy used as a temporary for dealing with
21766         * x/y location when view is transformed.
21767         */
21768        final float[] mTmpTransformLocation = new float[2];
21769
21770        /**
21771         * The view tree observer used to dispatch global events like
21772         * layout, pre-draw, touch mode change, etc.
21773         */
21774        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21775
21776        /**
21777         * A Canvas used by the view hierarchy to perform bitmap caching.
21778         */
21779        Canvas mCanvas;
21780
21781        /**
21782         * The view root impl.
21783         */
21784        final ViewRootImpl mViewRootImpl;
21785
21786        /**
21787         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21788         * handler can be used to pump events in the UI events queue.
21789         */
21790        final Handler mHandler;
21791
21792        /**
21793         * Temporary for use in computing invalidate rectangles while
21794         * calling up the hierarchy.
21795         */
21796        final Rect mTmpInvalRect = new Rect();
21797
21798        /**
21799         * Temporary for use in computing hit areas with transformed views
21800         */
21801        final RectF mTmpTransformRect = new RectF();
21802
21803        /**
21804         * Temporary for use in computing hit areas with transformed views
21805         */
21806        final RectF mTmpTransformRect1 = new RectF();
21807
21808        /**
21809         * Temporary list of rectanges.
21810         */
21811        final List<RectF> mTmpRectList = new ArrayList<>();
21812
21813        /**
21814         * Temporary for use in transforming invalidation rect
21815         */
21816        final Matrix mTmpMatrix = new Matrix();
21817
21818        /**
21819         * Temporary for use in transforming invalidation rect
21820         */
21821        final Transformation mTmpTransformation = new Transformation();
21822
21823        /**
21824         * Temporary for use in querying outlines from OutlineProviders
21825         */
21826        final Outline mTmpOutline = new Outline();
21827
21828        /**
21829         * Temporary list for use in collecting focusable descendents of a view.
21830         */
21831        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21832
21833        /**
21834         * The id of the window for accessibility purposes.
21835         */
21836        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21837
21838        /**
21839         * Flags related to accessibility processing.
21840         *
21841         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21842         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21843         */
21844        int mAccessibilityFetchFlags;
21845
21846        /**
21847         * The drawable for highlighting accessibility focus.
21848         */
21849        Drawable mAccessibilityFocusDrawable;
21850
21851        /**
21852         * Show where the margins, bounds and layout bounds are for each view.
21853         */
21854        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21855
21856        /**
21857         * Point used to compute visible regions.
21858         */
21859        final Point mPoint = new Point();
21860
21861        /**
21862         * Used to track which View originated a requestLayout() call, used when
21863         * requestLayout() is called during layout.
21864         */
21865        View mViewRequestingLayout;
21866
21867        /**
21868         * Creates a new set of attachment information with the specified
21869         * events handler and thread.
21870         *
21871         * @param handler the events handler the view must use
21872         */
21873        AttachInfo(IWindowSession session, IWindow window, Display display,
21874                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21875            mSession = session;
21876            mWindow = window;
21877            mWindowToken = window.asBinder();
21878            mDisplay = display;
21879            mViewRootImpl = viewRootImpl;
21880            mHandler = handler;
21881            mRootCallbacks = effectPlayer;
21882        }
21883    }
21884
21885    /**
21886     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21887     * is supported. This avoids keeping too many unused fields in most
21888     * instances of View.</p>
21889     */
21890    private static class ScrollabilityCache implements Runnable {
21891
21892        /**
21893         * Scrollbars are not visible
21894         */
21895        public static final int OFF = 0;
21896
21897        /**
21898         * Scrollbars are visible
21899         */
21900        public static final int ON = 1;
21901
21902        /**
21903         * Scrollbars are fading away
21904         */
21905        public static final int FADING = 2;
21906
21907        public boolean fadeScrollBars;
21908
21909        public int fadingEdgeLength;
21910        public int scrollBarDefaultDelayBeforeFade;
21911        public int scrollBarFadeDuration;
21912
21913        public int scrollBarSize;
21914        public ScrollBarDrawable scrollBar;
21915        public float[] interpolatorValues;
21916        public View host;
21917
21918        public final Paint paint;
21919        public final Matrix matrix;
21920        public Shader shader;
21921
21922        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21923
21924        private static final float[] OPAQUE = { 255 };
21925        private static final float[] TRANSPARENT = { 0.0f };
21926
21927        /**
21928         * When fading should start. This time moves into the future every time
21929         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21930         */
21931        public long fadeStartTime;
21932
21933
21934        /**
21935         * The current state of the scrollbars: ON, OFF, or FADING
21936         */
21937        public int state = OFF;
21938
21939        private int mLastColor;
21940
21941        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21942            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21943            scrollBarSize = configuration.getScaledScrollBarSize();
21944            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21945            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21946
21947            paint = new Paint();
21948            matrix = new Matrix();
21949            // use use a height of 1, and then wack the matrix each time we
21950            // actually use it.
21951            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21952            paint.setShader(shader);
21953            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21954
21955            this.host = host;
21956        }
21957
21958        public void setFadeColor(int color) {
21959            if (color != mLastColor) {
21960                mLastColor = color;
21961
21962                if (color != 0) {
21963                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21964                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21965                    paint.setShader(shader);
21966                    // Restore the default transfer mode (src_over)
21967                    paint.setXfermode(null);
21968                } else {
21969                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21970                    paint.setShader(shader);
21971                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21972                }
21973            }
21974        }
21975
21976        public void run() {
21977            long now = AnimationUtils.currentAnimationTimeMillis();
21978            if (now >= fadeStartTime) {
21979
21980                // the animation fades the scrollbars out by changing
21981                // the opacity (alpha) from fully opaque to fully
21982                // transparent
21983                int nextFrame = (int) now;
21984                int framesCount = 0;
21985
21986                Interpolator interpolator = scrollBarInterpolator;
21987
21988                // Start opaque
21989                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21990
21991                // End transparent
21992                nextFrame += scrollBarFadeDuration;
21993                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
21994
21995                state = FADING;
21996
21997                // Kick off the fade animation
21998                host.invalidate(true);
21999            }
22000        }
22001    }
22002
22003    /**
22004     * Resuable callback for sending
22005     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
22006     */
22007    private class SendViewScrolledAccessibilityEvent implements Runnable {
22008        public volatile boolean mIsPending;
22009
22010        public void run() {
22011            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
22012            mIsPending = false;
22013        }
22014    }
22015
22016    /**
22017     * <p>
22018     * This class represents a delegate that can be registered in a {@link View}
22019     * to enhance accessibility support via composition rather via inheritance.
22020     * It is specifically targeted to widget developers that extend basic View
22021     * classes i.e. classes in package android.view, that would like their
22022     * applications to be backwards compatible.
22023     * </p>
22024     * <div class="special reference">
22025     * <h3>Developer Guides</h3>
22026     * <p>For more information about making applications accessible, read the
22027     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
22028     * developer guide.</p>
22029     * </div>
22030     * <p>
22031     * A scenario in which a developer would like to use an accessibility delegate
22032     * is overriding a method introduced in a later API version then the minimal API
22033     * version supported by the application. For example, the method
22034     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
22035     * in API version 4 when the accessibility APIs were first introduced. If a
22036     * developer would like his application to run on API version 4 devices (assuming
22037     * all other APIs used by the application are version 4 or lower) and take advantage
22038     * of this method, instead of overriding the method which would break the application's
22039     * backwards compatibility, he can override the corresponding method in this
22040     * delegate and register the delegate in the target View if the API version of
22041     * the system is high enough i.e. the API version is same or higher to the API
22042     * version that introduced
22043     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
22044     * </p>
22045     * <p>
22046     * Here is an example implementation:
22047     * </p>
22048     * <code><pre><p>
22049     * if (Build.VERSION.SDK_INT >= 14) {
22050     *     // If the API version is equal of higher than the version in
22051     *     // which onInitializeAccessibilityNodeInfo was introduced we
22052     *     // register a delegate with a customized implementation.
22053     *     View view = findViewById(R.id.view_id);
22054     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
22055     *         public void onInitializeAccessibilityNodeInfo(View host,
22056     *                 AccessibilityNodeInfo info) {
22057     *             // Let the default implementation populate the info.
22058     *             super.onInitializeAccessibilityNodeInfo(host, info);
22059     *             // Set some other information.
22060     *             info.setEnabled(host.isEnabled());
22061     *         }
22062     *     });
22063     * }
22064     * </code></pre></p>
22065     * <p>
22066     * This delegate contains methods that correspond to the accessibility methods
22067     * in View. If a delegate has been specified the implementation in View hands
22068     * off handling to the corresponding method in this delegate. The default
22069     * implementation the delegate methods behaves exactly as the corresponding
22070     * method in View for the case of no accessibility delegate been set. Hence,
22071     * to customize the behavior of a View method, clients can override only the
22072     * corresponding delegate method without altering the behavior of the rest
22073     * accessibility related methods of the host view.
22074     * </p>
22075     */
22076    public static class AccessibilityDelegate {
22077
22078        /**
22079         * Sends an accessibility event of the given type. If accessibility is not
22080         * enabled this method has no effect.
22081         * <p>
22082         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
22083         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
22084         * been set.
22085         * </p>
22086         *
22087         * @param host The View hosting the delegate.
22088         * @param eventType The type of the event to send.
22089         *
22090         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
22091         */
22092        public void sendAccessibilityEvent(View host, int eventType) {
22093            host.sendAccessibilityEventInternal(eventType);
22094        }
22095
22096        /**
22097         * Performs the specified accessibility action on the view. For
22098         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
22099         * <p>
22100         * The default implementation behaves as
22101         * {@link View#performAccessibilityAction(int, Bundle)
22102         *  View#performAccessibilityAction(int, Bundle)} for the case of
22103         *  no accessibility delegate been set.
22104         * </p>
22105         *
22106         * @param action The action to perform.
22107         * @return Whether the action was performed.
22108         *
22109         * @see View#performAccessibilityAction(int, Bundle)
22110         *      View#performAccessibilityAction(int, Bundle)
22111         */
22112        public boolean performAccessibilityAction(View host, int action, Bundle args) {
22113            return host.performAccessibilityActionInternal(action, args);
22114        }
22115
22116        /**
22117         * Sends an accessibility event. This method behaves exactly as
22118         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
22119         * empty {@link AccessibilityEvent} and does not perform a check whether
22120         * accessibility is enabled.
22121         * <p>
22122         * The default implementation behaves as
22123         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
22124         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
22125         * the case of no accessibility delegate been set.
22126         * </p>
22127         *
22128         * @param host The View hosting the delegate.
22129         * @param event The event to send.
22130         *
22131         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
22132         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
22133         */
22134        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
22135            host.sendAccessibilityEventUncheckedInternal(event);
22136        }
22137
22138        /**
22139         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
22140         * to its children for adding their text content to the event.
22141         * <p>
22142         * The default implementation behaves as
22143         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
22144         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
22145         * the case of no accessibility delegate been set.
22146         * </p>
22147         *
22148         * @param host The View hosting the delegate.
22149         * @param event The event.
22150         * @return True if the event population was completed.
22151         *
22152         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
22153         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
22154         */
22155        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
22156            return host.dispatchPopulateAccessibilityEventInternal(event);
22157        }
22158
22159        /**
22160         * Gives a chance to the host View to populate the accessibility event with its
22161         * text content.
22162         * <p>
22163         * The default implementation behaves as
22164         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
22165         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
22166         * the case of no accessibility delegate been set.
22167         * </p>
22168         *
22169         * @param host The View hosting the delegate.
22170         * @param event The accessibility event which to populate.
22171         *
22172         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
22173         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
22174         */
22175        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
22176            host.onPopulateAccessibilityEventInternal(event);
22177        }
22178
22179        /**
22180         * Initializes an {@link AccessibilityEvent} with information about the
22181         * the host View which is the event source.
22182         * <p>
22183         * The default implementation behaves as
22184         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
22185         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
22186         * the case of no accessibility delegate been set.
22187         * </p>
22188         *
22189         * @param host The View hosting the delegate.
22190         * @param event The event to initialize.
22191         *
22192         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
22193         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
22194         */
22195        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
22196            host.onInitializeAccessibilityEventInternal(event);
22197        }
22198
22199        /**
22200         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
22201         * <p>
22202         * The default implementation behaves as
22203         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
22204         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
22205         * the case of no accessibility delegate been set.
22206         * </p>
22207         *
22208         * @param host The View hosting the delegate.
22209         * @param info The instance to initialize.
22210         *
22211         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
22212         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
22213         */
22214        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
22215            host.onInitializeAccessibilityNodeInfoInternal(info);
22216        }
22217
22218        /**
22219         * Called when a child of the host View has requested sending an
22220         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
22221         * to augment the event.
22222         * <p>
22223         * The default implementation behaves as
22224         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
22225         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
22226         * the case of no accessibility delegate been set.
22227         * </p>
22228         *
22229         * @param host The View hosting the delegate.
22230         * @param child The child which requests sending the event.
22231         * @param event The event to be sent.
22232         * @return True if the event should be sent
22233         *
22234         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
22235         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
22236         */
22237        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
22238                AccessibilityEvent event) {
22239            return host.onRequestSendAccessibilityEventInternal(child, event);
22240        }
22241
22242        /**
22243         * Gets the provider for managing a virtual view hierarchy rooted at this View
22244         * and reported to {@link android.accessibilityservice.AccessibilityService}s
22245         * that explore the window content.
22246         * <p>
22247         * The default implementation behaves as
22248         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
22249         * the case of no accessibility delegate been set.
22250         * </p>
22251         *
22252         * @return The provider.
22253         *
22254         * @see AccessibilityNodeProvider
22255         */
22256        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
22257            return null;
22258        }
22259
22260        /**
22261         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
22262         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
22263         * This method is responsible for obtaining an accessibility node info from a
22264         * pool of reusable instances and calling
22265         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
22266         * view to initialize the former.
22267         * <p>
22268         * <strong>Note:</strong> The client is responsible for recycling the obtained
22269         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
22270         * creation.
22271         * </p>
22272         * <p>
22273         * The default implementation behaves as
22274         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
22275         * the case of no accessibility delegate been set.
22276         * </p>
22277         * @return A populated {@link AccessibilityNodeInfo}.
22278         *
22279         * @see AccessibilityNodeInfo
22280         *
22281         * @hide
22282         */
22283        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
22284            return host.createAccessibilityNodeInfoInternal();
22285        }
22286    }
22287
22288    private class MatchIdPredicate implements Predicate<View> {
22289        public int mId;
22290
22291        @Override
22292        public boolean apply(View view) {
22293            return (view.mID == mId);
22294        }
22295    }
22296
22297    private class MatchLabelForPredicate implements Predicate<View> {
22298        private int mLabeledId;
22299
22300        @Override
22301        public boolean apply(View view) {
22302            return (view.mLabelForId == mLabeledId);
22303        }
22304    }
22305
22306    private class SendViewStateChangedAccessibilityEvent implements Runnable {
22307        private int mChangeTypes = 0;
22308        private boolean mPosted;
22309        private boolean mPostedWithDelay;
22310        private long mLastEventTimeMillis;
22311
22312        @Override
22313        public void run() {
22314            mPosted = false;
22315            mPostedWithDelay = false;
22316            mLastEventTimeMillis = SystemClock.uptimeMillis();
22317            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
22318                final AccessibilityEvent event = AccessibilityEvent.obtain();
22319                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
22320                event.setContentChangeTypes(mChangeTypes);
22321                sendAccessibilityEventUnchecked(event);
22322            }
22323            mChangeTypes = 0;
22324        }
22325
22326        public void runOrPost(int changeType) {
22327            mChangeTypes |= changeType;
22328
22329            // If this is a live region or the child of a live region, collect
22330            // all events from this frame and send them on the next frame.
22331            if (inLiveRegion()) {
22332                // If we're already posted with a delay, remove that.
22333                if (mPostedWithDelay) {
22334                    removeCallbacks(this);
22335                    mPostedWithDelay = false;
22336                }
22337                // Only post if we're not already posted.
22338                if (!mPosted) {
22339                    post(this);
22340                    mPosted = true;
22341                }
22342                return;
22343            }
22344
22345            if (mPosted) {
22346                return;
22347            }
22348
22349            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
22350            final long minEventIntevalMillis =
22351                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
22352            if (timeSinceLastMillis >= minEventIntevalMillis) {
22353                removeCallbacks(this);
22354                run();
22355            } else {
22356                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
22357                mPostedWithDelay = true;
22358            }
22359        }
22360    }
22361
22362    private boolean inLiveRegion() {
22363        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
22364            return true;
22365        }
22366
22367        ViewParent parent = getParent();
22368        while (parent instanceof View) {
22369            if (((View) parent).getAccessibilityLiveRegion()
22370                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
22371                return true;
22372            }
22373            parent = parent.getParent();
22374        }
22375
22376        return false;
22377    }
22378
22379    /**
22380     * Dump all private flags in readable format, useful for documentation and
22381     * sanity checking.
22382     */
22383    private static void dumpFlags() {
22384        final HashMap<String, String> found = Maps.newHashMap();
22385        try {
22386            for (Field field : View.class.getDeclaredFields()) {
22387                final int modifiers = field.getModifiers();
22388                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
22389                    if (field.getType().equals(int.class)) {
22390                        final int value = field.getInt(null);
22391                        dumpFlag(found, field.getName(), value);
22392                    } else if (field.getType().equals(int[].class)) {
22393                        final int[] values = (int[]) field.get(null);
22394                        for (int i = 0; i < values.length; i++) {
22395                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
22396                        }
22397                    }
22398                }
22399            }
22400        } catch (IllegalAccessException e) {
22401            throw new RuntimeException(e);
22402        }
22403
22404        final ArrayList<String> keys = Lists.newArrayList();
22405        keys.addAll(found.keySet());
22406        Collections.sort(keys);
22407        for (String key : keys) {
22408            Log.d(VIEW_LOG_TAG, found.get(key));
22409        }
22410    }
22411
22412    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
22413        // Sort flags by prefix, then by bits, always keeping unique keys
22414        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
22415        final int prefix = name.indexOf('_');
22416        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
22417        final String output = bits + " " + name;
22418        found.put(key, output);
22419    }
22420
22421    /** {@hide} */
22422    public void encode(@NonNull ViewHierarchyEncoder stream) {
22423        stream.beginObject(this);
22424        encodeProperties(stream);
22425        stream.endObject();
22426    }
22427
22428    /** {@hide} */
22429    @CallSuper
22430    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
22431        Object resolveId = ViewDebug.resolveId(getContext(), mID);
22432        if (resolveId instanceof String) {
22433            stream.addProperty("id", (String) resolveId);
22434        } else {
22435            stream.addProperty("id", mID);
22436        }
22437
22438        stream.addProperty("misc:transformation.alpha",
22439                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
22440        stream.addProperty("misc:transitionName", getTransitionName());
22441
22442        // layout
22443        stream.addProperty("layout:left", mLeft);
22444        stream.addProperty("layout:right", mRight);
22445        stream.addProperty("layout:top", mTop);
22446        stream.addProperty("layout:bottom", mBottom);
22447        stream.addProperty("layout:width", getWidth());
22448        stream.addProperty("layout:height", getHeight());
22449        stream.addProperty("layout:layoutDirection", getLayoutDirection());
22450        stream.addProperty("layout:layoutRtl", isLayoutRtl());
22451        stream.addProperty("layout:hasTransientState", hasTransientState());
22452        stream.addProperty("layout:baseline", getBaseline());
22453
22454        // layout params
22455        ViewGroup.LayoutParams layoutParams = getLayoutParams();
22456        if (layoutParams != null) {
22457            stream.addPropertyKey("layoutParams");
22458            layoutParams.encode(stream);
22459        }
22460
22461        // scrolling
22462        stream.addProperty("scrolling:scrollX", mScrollX);
22463        stream.addProperty("scrolling:scrollY", mScrollY);
22464
22465        // padding
22466        stream.addProperty("padding:paddingLeft", mPaddingLeft);
22467        stream.addProperty("padding:paddingRight", mPaddingRight);
22468        stream.addProperty("padding:paddingTop", mPaddingTop);
22469        stream.addProperty("padding:paddingBottom", mPaddingBottom);
22470        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
22471        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
22472        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
22473        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
22474        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
22475
22476        // measurement
22477        stream.addProperty("measurement:minHeight", mMinHeight);
22478        stream.addProperty("measurement:minWidth", mMinWidth);
22479        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
22480        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
22481
22482        // drawing
22483        stream.addProperty("drawing:elevation", getElevation());
22484        stream.addProperty("drawing:translationX", getTranslationX());
22485        stream.addProperty("drawing:translationY", getTranslationY());
22486        stream.addProperty("drawing:translationZ", getTranslationZ());
22487        stream.addProperty("drawing:rotation", getRotation());
22488        stream.addProperty("drawing:rotationX", getRotationX());
22489        stream.addProperty("drawing:rotationY", getRotationY());
22490        stream.addProperty("drawing:scaleX", getScaleX());
22491        stream.addProperty("drawing:scaleY", getScaleY());
22492        stream.addProperty("drawing:pivotX", getPivotX());
22493        stream.addProperty("drawing:pivotY", getPivotY());
22494        stream.addProperty("drawing:opaque", isOpaque());
22495        stream.addProperty("drawing:alpha", getAlpha());
22496        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
22497        stream.addProperty("drawing:shadow", hasShadow());
22498        stream.addProperty("drawing:solidColor", getSolidColor());
22499        stream.addProperty("drawing:layerType", mLayerType);
22500        stream.addProperty("drawing:willNotDraw", willNotDraw());
22501        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
22502        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
22503        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
22504        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
22505
22506        // focus
22507        stream.addProperty("focus:hasFocus", hasFocus());
22508        stream.addProperty("focus:isFocused", isFocused());
22509        stream.addProperty("focus:isFocusable", isFocusable());
22510        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
22511
22512        stream.addProperty("misc:clickable", isClickable());
22513        stream.addProperty("misc:pressed", isPressed());
22514        stream.addProperty("misc:selected", isSelected());
22515        stream.addProperty("misc:touchMode", isInTouchMode());
22516        stream.addProperty("misc:hovered", isHovered());
22517        stream.addProperty("misc:activated", isActivated());
22518
22519        stream.addProperty("misc:visibility", getVisibility());
22520        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
22521        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
22522
22523        stream.addProperty("misc:enabled", isEnabled());
22524        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
22525        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
22526
22527        // theme attributes
22528        Resources.Theme theme = getContext().getTheme();
22529        if (theme != null) {
22530            stream.addPropertyKey("theme");
22531            theme.encode(stream);
22532        }
22533
22534        // view attribute information
22535        int n = mAttributes != null ? mAttributes.length : 0;
22536        stream.addProperty("meta:__attrCount__", n/2);
22537        for (int i = 0; i < n; i += 2) {
22538            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
22539        }
22540
22541        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
22542
22543        // text
22544        stream.addProperty("text:textDirection", getTextDirection());
22545        stream.addProperty("text:textAlignment", getTextAlignment());
22546
22547        // accessibility
22548        CharSequence contentDescription = getContentDescription();
22549        stream.addProperty("accessibility:contentDescription",
22550                contentDescription == null ? "" : contentDescription.toString());
22551        stream.addProperty("accessibility:labelFor", getLabelFor());
22552        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
22553    }
22554}
22555