View.java revision afaed06cda3473c3e182a48cf1a1a78c8a005055
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     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3598     */
3599    private float mVerticalScrollFactor;
3600
3601    /**
3602     * Position of the vertical scroll bar.
3603     */
3604    private int mVerticalScrollbarPosition;
3605
3606    /**
3607     * Position the scroll bar at the default position as determined by the system.
3608     */
3609    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3610
3611    /**
3612     * Position the scroll bar along the left edge.
3613     */
3614    public static final int SCROLLBAR_POSITION_LEFT = 1;
3615
3616    /**
3617     * Position the scroll bar along the right edge.
3618     */
3619    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3620
3621    /**
3622     * Indicates that the view does not have a layer.
3623     *
3624     * @see #getLayerType()
3625     * @see #setLayerType(int, android.graphics.Paint)
3626     * @see #LAYER_TYPE_SOFTWARE
3627     * @see #LAYER_TYPE_HARDWARE
3628     */
3629    public static final int LAYER_TYPE_NONE = 0;
3630
3631    /**
3632     * <p>Indicates that the view has a software layer. A software layer is backed
3633     * by a bitmap and causes the view to be rendered using Android's software
3634     * rendering pipeline, even if hardware acceleration is enabled.</p>
3635     *
3636     * <p>Software layers have various usages:</p>
3637     * <p>When the application is not using hardware acceleration, a software layer
3638     * is useful to apply a specific color filter and/or blending mode and/or
3639     * translucency to a view and all its children.</p>
3640     * <p>When the application is using hardware acceleration, a software layer
3641     * is useful to render drawing primitives not supported by the hardware
3642     * accelerated pipeline. It can also be used to cache a complex view tree
3643     * into a texture and reduce the complexity of drawing operations. For instance,
3644     * when animating a complex view tree with a translation, a software layer can
3645     * be used to render the view tree only once.</p>
3646     * <p>Software layers should be avoided when the affected view tree updates
3647     * often. Every update will require to re-render the software layer, which can
3648     * potentially be slow (particularly when hardware acceleration is turned on
3649     * since the layer will have to be uploaded into a hardware texture after every
3650     * update.)</p>
3651     *
3652     * @see #getLayerType()
3653     * @see #setLayerType(int, android.graphics.Paint)
3654     * @see #LAYER_TYPE_NONE
3655     * @see #LAYER_TYPE_HARDWARE
3656     */
3657    public static final int LAYER_TYPE_SOFTWARE = 1;
3658
3659    /**
3660     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3661     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3662     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3663     * rendering pipeline, but only if hardware acceleration is turned on for the
3664     * view hierarchy. When hardware acceleration is turned off, hardware layers
3665     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3666     *
3667     * <p>A hardware layer is useful to apply a specific color filter and/or
3668     * blending mode and/or translucency to a view and all its children.</p>
3669     * <p>A hardware layer can be used to cache a complex view tree into a
3670     * texture and reduce the complexity of drawing operations. For instance,
3671     * when animating a complex view tree with a translation, a hardware layer can
3672     * be used to render the view tree only once.</p>
3673     * <p>A hardware layer can also be used to increase the rendering quality when
3674     * rotation transformations are applied on a view. It can also be used to
3675     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3676     *
3677     * @see #getLayerType()
3678     * @see #setLayerType(int, android.graphics.Paint)
3679     * @see #LAYER_TYPE_NONE
3680     * @see #LAYER_TYPE_SOFTWARE
3681     */
3682    public static final int LAYER_TYPE_HARDWARE = 2;
3683
3684    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3685            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3686            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3687            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3688    })
3689    int mLayerType = LAYER_TYPE_NONE;
3690    Paint mLayerPaint;
3691
3692    /**
3693     * Set to true when drawing cache is enabled and cannot be created.
3694     *
3695     * @hide
3696     */
3697    public boolean mCachingFailed;
3698    private Bitmap mDrawingCache;
3699    private Bitmap mUnscaledDrawingCache;
3700
3701    /**
3702     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3703     * <p>
3704     * When non-null and valid, this is expected to contain an up-to-date copy
3705     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3706     * cleanup.
3707     */
3708    final RenderNode mRenderNode;
3709
3710    /**
3711     * Set to true when the view is sending hover accessibility events because it
3712     * is the innermost hovered view.
3713     */
3714    private boolean mSendingHoverAccessibilityEvents;
3715
3716    /**
3717     * Delegate for injecting accessibility functionality.
3718     */
3719    AccessibilityDelegate mAccessibilityDelegate;
3720
3721    /**
3722     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3723     * and add/remove objects to/from the overlay directly through the Overlay methods.
3724     */
3725    ViewOverlay mOverlay;
3726
3727    /**
3728     * The currently active parent view for receiving delegated nested scrolling events.
3729     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3730     * by {@link #stopNestedScroll()} at the same point where we clear
3731     * requestDisallowInterceptTouchEvent.
3732     */
3733    private ViewParent mNestedScrollingParent;
3734
3735    /**
3736     * Consistency verifier for debugging purposes.
3737     * @hide
3738     */
3739    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3740            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3741                    new InputEventConsistencyVerifier(this, 0) : null;
3742
3743    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3744
3745    private int[] mTempNestedScrollConsumed;
3746
3747    /**
3748     * An overlay is going to draw this View instead of being drawn as part of this
3749     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3750     * when this view is invalidated.
3751     */
3752    GhostView mGhostView;
3753
3754    /**
3755     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3756     * @hide
3757     */
3758    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3759    public String[] mAttributes;
3760
3761    /**
3762     * Maps a Resource id to its name.
3763     */
3764    private static SparseArray<String> mAttributeMap;
3765
3766    /**
3767     * @hide
3768     */
3769    String mStartActivityRequestWho;
3770
3771    /**
3772     * Simple constructor to use when creating a view from code.
3773     *
3774     * @param context The Context the view is running in, through which it can
3775     *        access the current theme, resources, etc.
3776     */
3777    public View(Context context) {
3778        mContext = context;
3779        mResources = context != null ? context.getResources() : null;
3780        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3781        // Set some flags defaults
3782        mPrivateFlags2 =
3783                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3784                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3785                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3786                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3787                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3788                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3789        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3790        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3791        mUserPaddingStart = UNDEFINED_PADDING;
3792        mUserPaddingEnd = UNDEFINED_PADDING;
3793        mRenderNode = RenderNode.create(getClass().getName(), this);
3794
3795        if (!sCompatibilityDone && context != null) {
3796            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3797
3798            // Older apps may need this compatibility hack for measurement.
3799            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3800
3801            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3802            // of whether a layout was requested on that View.
3803            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3804
3805            Canvas.sCompatibilityRestore = targetSdkVersion < MNC;
3806
3807            // In MNC and newer, our widgets can pass a "hint" value in the size
3808            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
3809            // know what the expected parent size is going to be, so e.g. list items can size
3810            // themselves at 1/3 the size of their container. It breaks older apps though,
3811            // specifically apps that use some popular open source libraries.
3812            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < MNC;
3813
3814            sCompatibilityDone = true;
3815        }
3816    }
3817
3818    /**
3819     * Constructor that is called when inflating a view from XML. This is called
3820     * when a view is being constructed from an XML file, supplying attributes
3821     * that were specified in the XML file. This version uses a default style of
3822     * 0, so the only attribute values applied are those in the Context's Theme
3823     * and the given AttributeSet.
3824     *
3825     * <p>
3826     * The method onFinishInflate() will be called after all children have been
3827     * added.
3828     *
3829     * @param context The Context the view is running in, through which it can
3830     *        access the current theme, resources, etc.
3831     * @param attrs The attributes of the XML tag that is inflating the view.
3832     * @see #View(Context, AttributeSet, int)
3833     */
3834    public View(Context context, @Nullable AttributeSet attrs) {
3835        this(context, attrs, 0);
3836    }
3837
3838    /**
3839     * Perform inflation from XML and apply a class-specific base style from a
3840     * theme attribute. This constructor of View allows subclasses to use their
3841     * own base style when they are inflating. For example, a Button class's
3842     * constructor would call this version of the super class constructor and
3843     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3844     * allows the theme's button style to modify all of the base view attributes
3845     * (in particular its background) as well as the Button class's attributes.
3846     *
3847     * @param context The Context the view is running in, through which it can
3848     *        access the current theme, resources, etc.
3849     * @param attrs The attributes of the XML tag that is inflating the view.
3850     * @param defStyleAttr An attribute in the current theme that contains a
3851     *        reference to a style resource that supplies default values for
3852     *        the view. Can be 0 to not look for defaults.
3853     * @see #View(Context, AttributeSet)
3854     */
3855    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
3856        this(context, attrs, defStyleAttr, 0);
3857    }
3858
3859    /**
3860     * Perform inflation from XML and apply a class-specific base style from a
3861     * theme attribute or style resource. This constructor of View allows
3862     * subclasses to use their own base style when they are inflating.
3863     * <p>
3864     * When determining the final value of a particular attribute, there are
3865     * four inputs that come into play:
3866     * <ol>
3867     * <li>Any attribute values in the given AttributeSet.
3868     * <li>The style resource specified in the AttributeSet (named "style").
3869     * <li>The default style specified by <var>defStyleAttr</var>.
3870     * <li>The default style specified by <var>defStyleRes</var>.
3871     * <li>The base values in this theme.
3872     * </ol>
3873     * <p>
3874     * Each of these inputs is considered in-order, with the first listed taking
3875     * precedence over the following ones. In other words, if in the
3876     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3877     * , then the button's text will <em>always</em> be black, regardless of
3878     * what is specified in any of the styles.
3879     *
3880     * @param context The Context the view is running in, through which it can
3881     *        access the current theme, resources, etc.
3882     * @param attrs The attributes of the XML tag that is inflating the view.
3883     * @param defStyleAttr An attribute in the current theme that contains a
3884     *        reference to a style resource that supplies default values for
3885     *        the view. Can be 0 to not look for defaults.
3886     * @param defStyleRes A resource identifier of a style resource that
3887     *        supplies default values for the view, used only if
3888     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3889     *        to not look for defaults.
3890     * @see #View(Context, AttributeSet, int)
3891     */
3892    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3893        this(context);
3894
3895        final TypedArray a = context.obtainStyledAttributes(
3896                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3897
3898        if (mDebugViewAttributes) {
3899            saveAttributeData(attrs, a);
3900        }
3901
3902        Drawable background = null;
3903
3904        int leftPadding = -1;
3905        int topPadding = -1;
3906        int rightPadding = -1;
3907        int bottomPadding = -1;
3908        int startPadding = UNDEFINED_PADDING;
3909        int endPadding = UNDEFINED_PADDING;
3910
3911        int padding = -1;
3912
3913        int viewFlagValues = 0;
3914        int viewFlagMasks = 0;
3915
3916        boolean setScrollContainer = false;
3917
3918        int x = 0;
3919        int y = 0;
3920
3921        float tx = 0;
3922        float ty = 0;
3923        float tz = 0;
3924        float elevation = 0;
3925        float rotation = 0;
3926        float rotationX = 0;
3927        float rotationY = 0;
3928        float sx = 1f;
3929        float sy = 1f;
3930        boolean transformSet = false;
3931
3932        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3933        int overScrollMode = mOverScrollMode;
3934        boolean initializeScrollbars = false;
3935        boolean initializeScrollIndicators = false;
3936
3937        boolean startPaddingDefined = false;
3938        boolean endPaddingDefined = false;
3939        boolean leftPaddingDefined = false;
3940        boolean rightPaddingDefined = false;
3941
3942        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3943
3944        final int N = a.getIndexCount();
3945        for (int i = 0; i < N; i++) {
3946            int attr = a.getIndex(i);
3947            switch (attr) {
3948                case com.android.internal.R.styleable.View_background:
3949                    background = a.getDrawable(attr);
3950                    break;
3951                case com.android.internal.R.styleable.View_padding:
3952                    padding = a.getDimensionPixelSize(attr, -1);
3953                    mUserPaddingLeftInitial = padding;
3954                    mUserPaddingRightInitial = padding;
3955                    leftPaddingDefined = true;
3956                    rightPaddingDefined = true;
3957                    break;
3958                 case com.android.internal.R.styleable.View_paddingLeft:
3959                    leftPadding = a.getDimensionPixelSize(attr, -1);
3960                    mUserPaddingLeftInitial = leftPadding;
3961                    leftPaddingDefined = true;
3962                    break;
3963                case com.android.internal.R.styleable.View_paddingTop:
3964                    topPadding = a.getDimensionPixelSize(attr, -1);
3965                    break;
3966                case com.android.internal.R.styleable.View_paddingRight:
3967                    rightPadding = a.getDimensionPixelSize(attr, -1);
3968                    mUserPaddingRightInitial = rightPadding;
3969                    rightPaddingDefined = true;
3970                    break;
3971                case com.android.internal.R.styleable.View_paddingBottom:
3972                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3973                    break;
3974                case com.android.internal.R.styleable.View_paddingStart:
3975                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3976                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3977                    break;
3978                case com.android.internal.R.styleable.View_paddingEnd:
3979                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3980                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3981                    break;
3982                case com.android.internal.R.styleable.View_scrollX:
3983                    x = a.getDimensionPixelOffset(attr, 0);
3984                    break;
3985                case com.android.internal.R.styleable.View_scrollY:
3986                    y = a.getDimensionPixelOffset(attr, 0);
3987                    break;
3988                case com.android.internal.R.styleable.View_alpha:
3989                    setAlpha(a.getFloat(attr, 1f));
3990                    break;
3991                case com.android.internal.R.styleable.View_transformPivotX:
3992                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3993                    break;
3994                case com.android.internal.R.styleable.View_transformPivotY:
3995                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3996                    break;
3997                case com.android.internal.R.styleable.View_translationX:
3998                    tx = a.getDimensionPixelOffset(attr, 0);
3999                    transformSet = true;
4000                    break;
4001                case com.android.internal.R.styleable.View_translationY:
4002                    ty = a.getDimensionPixelOffset(attr, 0);
4003                    transformSet = true;
4004                    break;
4005                case com.android.internal.R.styleable.View_translationZ:
4006                    tz = a.getDimensionPixelOffset(attr, 0);
4007                    transformSet = true;
4008                    break;
4009                case com.android.internal.R.styleable.View_elevation:
4010                    elevation = a.getDimensionPixelOffset(attr, 0);
4011                    transformSet = true;
4012                    break;
4013                case com.android.internal.R.styleable.View_rotation:
4014                    rotation = a.getFloat(attr, 0);
4015                    transformSet = true;
4016                    break;
4017                case com.android.internal.R.styleable.View_rotationX:
4018                    rotationX = a.getFloat(attr, 0);
4019                    transformSet = true;
4020                    break;
4021                case com.android.internal.R.styleable.View_rotationY:
4022                    rotationY = a.getFloat(attr, 0);
4023                    transformSet = true;
4024                    break;
4025                case com.android.internal.R.styleable.View_scaleX:
4026                    sx = a.getFloat(attr, 1f);
4027                    transformSet = true;
4028                    break;
4029                case com.android.internal.R.styleable.View_scaleY:
4030                    sy = a.getFloat(attr, 1f);
4031                    transformSet = true;
4032                    break;
4033                case com.android.internal.R.styleable.View_id:
4034                    mID = a.getResourceId(attr, NO_ID);
4035                    break;
4036                case com.android.internal.R.styleable.View_tag:
4037                    mTag = a.getText(attr);
4038                    break;
4039                case com.android.internal.R.styleable.View_fitsSystemWindows:
4040                    if (a.getBoolean(attr, false)) {
4041                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4042                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4043                    }
4044                    break;
4045                case com.android.internal.R.styleable.View_focusable:
4046                    if (a.getBoolean(attr, false)) {
4047                        viewFlagValues |= FOCUSABLE;
4048                        viewFlagMasks |= FOCUSABLE_MASK;
4049                    }
4050                    break;
4051                case com.android.internal.R.styleable.View_focusableInTouchMode:
4052                    if (a.getBoolean(attr, false)) {
4053                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4054                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4055                    }
4056                    break;
4057                case com.android.internal.R.styleable.View_clickable:
4058                    if (a.getBoolean(attr, false)) {
4059                        viewFlagValues |= CLICKABLE;
4060                        viewFlagMasks |= CLICKABLE;
4061                    }
4062                    break;
4063                case com.android.internal.R.styleable.View_longClickable:
4064                    if (a.getBoolean(attr, false)) {
4065                        viewFlagValues |= LONG_CLICKABLE;
4066                        viewFlagMasks |= LONG_CLICKABLE;
4067                    }
4068                    break;
4069                case com.android.internal.R.styleable.View_contextClickable:
4070                    if (a.getBoolean(attr, false)) {
4071                        viewFlagValues |= CONTEXT_CLICKABLE;
4072                        viewFlagMasks |= CONTEXT_CLICKABLE;
4073                    }
4074                    break;
4075                case com.android.internal.R.styleable.View_saveEnabled:
4076                    if (!a.getBoolean(attr, true)) {
4077                        viewFlagValues |= SAVE_DISABLED;
4078                        viewFlagMasks |= SAVE_DISABLED_MASK;
4079                    }
4080                    break;
4081                case com.android.internal.R.styleable.View_duplicateParentState:
4082                    if (a.getBoolean(attr, false)) {
4083                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4084                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4085                    }
4086                    break;
4087                case com.android.internal.R.styleable.View_visibility:
4088                    final int visibility = a.getInt(attr, 0);
4089                    if (visibility != 0) {
4090                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4091                        viewFlagMasks |= VISIBILITY_MASK;
4092                    }
4093                    break;
4094                case com.android.internal.R.styleable.View_layoutDirection:
4095                    // Clear any layout direction flags (included resolved bits) already set
4096                    mPrivateFlags2 &=
4097                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4098                    // Set the layout direction flags depending on the value of the attribute
4099                    final int layoutDirection = a.getInt(attr, -1);
4100                    final int value = (layoutDirection != -1) ?
4101                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4102                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4103                    break;
4104                case com.android.internal.R.styleable.View_drawingCacheQuality:
4105                    final int cacheQuality = a.getInt(attr, 0);
4106                    if (cacheQuality != 0) {
4107                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4108                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4109                    }
4110                    break;
4111                case com.android.internal.R.styleable.View_contentDescription:
4112                    setContentDescription(a.getString(attr));
4113                    break;
4114                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4115                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4116                    break;
4117                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4118                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4119                    break;
4120                case com.android.internal.R.styleable.View_labelFor:
4121                    setLabelFor(a.getResourceId(attr, NO_ID));
4122                    break;
4123                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4124                    if (!a.getBoolean(attr, true)) {
4125                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4126                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4127                    }
4128                    break;
4129                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4130                    if (!a.getBoolean(attr, true)) {
4131                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4132                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4133                    }
4134                    break;
4135                case R.styleable.View_scrollbars:
4136                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4137                    if (scrollbars != SCROLLBARS_NONE) {
4138                        viewFlagValues |= scrollbars;
4139                        viewFlagMasks |= SCROLLBARS_MASK;
4140                        initializeScrollbars = true;
4141                    }
4142                    break;
4143                //noinspection deprecation
4144                case R.styleable.View_fadingEdge:
4145                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4146                        // Ignore the attribute starting with ICS
4147                        break;
4148                    }
4149                    // With builds < ICS, fall through and apply fading edges
4150                case R.styleable.View_requiresFadingEdge:
4151                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4152                    if (fadingEdge != FADING_EDGE_NONE) {
4153                        viewFlagValues |= fadingEdge;
4154                        viewFlagMasks |= FADING_EDGE_MASK;
4155                        initializeFadingEdgeInternal(a);
4156                    }
4157                    break;
4158                case R.styleable.View_scrollbarStyle:
4159                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4160                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4161                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4162                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4163                    }
4164                    break;
4165                case R.styleable.View_isScrollContainer:
4166                    setScrollContainer = true;
4167                    if (a.getBoolean(attr, false)) {
4168                        setScrollContainer(true);
4169                    }
4170                    break;
4171                case com.android.internal.R.styleable.View_keepScreenOn:
4172                    if (a.getBoolean(attr, false)) {
4173                        viewFlagValues |= KEEP_SCREEN_ON;
4174                        viewFlagMasks |= KEEP_SCREEN_ON;
4175                    }
4176                    break;
4177                case R.styleable.View_filterTouchesWhenObscured:
4178                    if (a.getBoolean(attr, false)) {
4179                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4180                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4181                    }
4182                    break;
4183                case R.styleable.View_nextFocusLeft:
4184                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4185                    break;
4186                case R.styleable.View_nextFocusRight:
4187                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4188                    break;
4189                case R.styleable.View_nextFocusUp:
4190                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4191                    break;
4192                case R.styleable.View_nextFocusDown:
4193                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4194                    break;
4195                case R.styleable.View_nextFocusForward:
4196                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4197                    break;
4198                case R.styleable.View_minWidth:
4199                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4200                    break;
4201                case R.styleable.View_minHeight:
4202                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4203                    break;
4204                case R.styleable.View_onClick:
4205                    if (context.isRestricted()) {
4206                        throw new IllegalStateException("The android:onClick attribute cannot "
4207                                + "be used within a restricted context");
4208                    }
4209
4210                    final String handlerName = a.getString(attr);
4211                    if (handlerName != null) {
4212                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4213                    }
4214                    break;
4215                case R.styleable.View_overScrollMode:
4216                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4217                    break;
4218                case R.styleable.View_verticalScrollbarPosition:
4219                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4220                    break;
4221                case R.styleable.View_layerType:
4222                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4223                    break;
4224                case R.styleable.View_textDirection:
4225                    // Clear any text direction flag already set
4226                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4227                    // Set the text direction flags depending on the value of the attribute
4228                    final int textDirection = a.getInt(attr, -1);
4229                    if (textDirection != -1) {
4230                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4231                    }
4232                    break;
4233                case R.styleable.View_textAlignment:
4234                    // Clear any text alignment flag already set
4235                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4236                    // Set the text alignment flag depending on the value of the attribute
4237                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4238                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4239                    break;
4240                case R.styleable.View_importantForAccessibility:
4241                    setImportantForAccessibility(a.getInt(attr,
4242                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4243                    break;
4244                case R.styleable.View_accessibilityLiveRegion:
4245                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4246                    break;
4247                case R.styleable.View_transitionName:
4248                    setTransitionName(a.getString(attr));
4249                    break;
4250                case R.styleable.View_nestedScrollingEnabled:
4251                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4252                    break;
4253                case R.styleable.View_stateListAnimator:
4254                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4255                            a.getResourceId(attr, 0)));
4256                    break;
4257                case R.styleable.View_backgroundTint:
4258                    // This will get applied later during setBackground().
4259                    if (mBackgroundTint == null) {
4260                        mBackgroundTint = new TintInfo();
4261                    }
4262                    mBackgroundTint.mTintList = a.getColorStateList(
4263                            R.styleable.View_backgroundTint);
4264                    mBackgroundTint.mHasTintList = true;
4265                    break;
4266                case R.styleable.View_backgroundTintMode:
4267                    // This will get applied later during setBackground().
4268                    if (mBackgroundTint == null) {
4269                        mBackgroundTint = new TintInfo();
4270                    }
4271                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4272                            R.styleable.View_backgroundTintMode, -1), null);
4273                    mBackgroundTint.mHasTintMode = true;
4274                    break;
4275                case R.styleable.View_outlineProvider:
4276                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4277                            PROVIDER_BACKGROUND));
4278                    break;
4279                case R.styleable.View_foreground:
4280                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4281                        setForeground(a.getDrawable(attr));
4282                    }
4283                    break;
4284                case R.styleable.View_foregroundGravity:
4285                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4286                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4287                    }
4288                    break;
4289                case R.styleable.View_foregroundTintMode:
4290                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4291                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4292                    }
4293                    break;
4294                case R.styleable.View_foregroundTint:
4295                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4296                        setForegroundTintList(a.getColorStateList(attr));
4297                    }
4298                    break;
4299                case R.styleable.View_foregroundInsidePadding:
4300                    if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) {
4301                        if (mForegroundInfo == null) {
4302                            mForegroundInfo = new ForegroundInfo();
4303                        }
4304                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4305                                mForegroundInfo.mInsidePadding);
4306                    }
4307                    break;
4308                case R.styleable.View_scrollIndicators:
4309                    final int scrollIndicators =
4310                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4311                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4312                    if (scrollIndicators != 0) {
4313                        mPrivateFlags3 |= scrollIndicators;
4314                        initializeScrollIndicators = true;
4315                    }
4316                    break;
4317            }
4318        }
4319
4320        setOverScrollMode(overScrollMode);
4321
4322        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4323        // the resolved layout direction). Those cached values will be used later during padding
4324        // resolution.
4325        mUserPaddingStart = startPadding;
4326        mUserPaddingEnd = endPadding;
4327
4328        if (background != null) {
4329            setBackground(background);
4330        }
4331
4332        // setBackground above will record that padding is currently provided by the background.
4333        // If we have padding specified via xml, record that here instead and use it.
4334        mLeftPaddingDefined = leftPaddingDefined;
4335        mRightPaddingDefined = rightPaddingDefined;
4336
4337        if (padding >= 0) {
4338            leftPadding = padding;
4339            topPadding = padding;
4340            rightPadding = padding;
4341            bottomPadding = padding;
4342            mUserPaddingLeftInitial = padding;
4343            mUserPaddingRightInitial = padding;
4344        }
4345
4346        if (isRtlCompatibilityMode()) {
4347            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4348            // left / right padding are used if defined (meaning here nothing to do). If they are not
4349            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4350            // start / end and resolve them as left / right (layout direction is not taken into account).
4351            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4352            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4353            // defined.
4354            if (!mLeftPaddingDefined && startPaddingDefined) {
4355                leftPadding = startPadding;
4356            }
4357            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4358            if (!mRightPaddingDefined && endPaddingDefined) {
4359                rightPadding = endPadding;
4360            }
4361            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4362        } else {
4363            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4364            // values defined. Otherwise, left /right values are used.
4365            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4366            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4367            // defined.
4368            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4369
4370            if (mLeftPaddingDefined && !hasRelativePadding) {
4371                mUserPaddingLeftInitial = leftPadding;
4372            }
4373            if (mRightPaddingDefined && !hasRelativePadding) {
4374                mUserPaddingRightInitial = rightPadding;
4375            }
4376        }
4377
4378        internalSetPadding(
4379                mUserPaddingLeftInitial,
4380                topPadding >= 0 ? topPadding : mPaddingTop,
4381                mUserPaddingRightInitial,
4382                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4383
4384        if (viewFlagMasks != 0) {
4385            setFlags(viewFlagValues, viewFlagMasks);
4386        }
4387
4388        if (initializeScrollbars) {
4389            initializeScrollbarsInternal(a);
4390        }
4391
4392        if (initializeScrollIndicators) {
4393            initializeScrollIndicatorsInternal();
4394        }
4395
4396        a.recycle();
4397
4398        // Needs to be called after mViewFlags is set
4399        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4400            recomputePadding();
4401        }
4402
4403        if (x != 0 || y != 0) {
4404            scrollTo(x, y);
4405        }
4406
4407        if (transformSet) {
4408            setTranslationX(tx);
4409            setTranslationY(ty);
4410            setTranslationZ(tz);
4411            setElevation(elevation);
4412            setRotation(rotation);
4413            setRotationX(rotationX);
4414            setRotationY(rotationY);
4415            setScaleX(sx);
4416            setScaleY(sy);
4417        }
4418
4419        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4420            setScrollContainer(true);
4421        }
4422
4423        computeOpaqueFlags();
4424    }
4425
4426    /**
4427     * An implementation of OnClickListener that attempts to lazily load a
4428     * named click handling method from a parent or ancestor context.
4429     */
4430    private static class DeclaredOnClickListener implements OnClickListener {
4431        private final View mHostView;
4432        private final String mMethodName;
4433
4434        private Method mMethod;
4435
4436        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4437            mHostView = hostView;
4438            mMethodName = methodName;
4439        }
4440
4441        @Override
4442        public void onClick(@NonNull View v) {
4443            if (mMethod == null) {
4444                mMethod = resolveMethod(mHostView.getContext(), mMethodName);
4445            }
4446
4447            try {
4448                mMethod.invoke(mHostView.getContext(), v);
4449            } catch (IllegalAccessException e) {
4450                throw new IllegalStateException(
4451                        "Could not execute non-public method for android:onClick", e);
4452            } catch (InvocationTargetException e) {
4453                throw new IllegalStateException(
4454                        "Could not execute method for android:onClick", e);
4455            }
4456        }
4457
4458        @NonNull
4459        private Method resolveMethod(@Nullable Context context, @NonNull String name) {
4460            while (context != null) {
4461                try {
4462                    if (!context.isRestricted()) {
4463                        return context.getClass().getMethod(mMethodName, View.class);
4464                    }
4465                } catch (NoSuchMethodException e) {
4466                    // Failed to find method, keep searching up the hierarchy.
4467                }
4468
4469                if (context instanceof ContextWrapper) {
4470                    context = ((ContextWrapper) context).getBaseContext();
4471                } else {
4472                    // Can't search up the hierarchy, null out and fail.
4473                    context = null;
4474                }
4475            }
4476
4477            final int id = mHostView.getId();
4478            final String idText = id == NO_ID ? "" : " with id '"
4479                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4480            throw new IllegalStateException("Could not find method " + mMethodName
4481                    + "(View) in a parent or ancestor Context for android:onClick "
4482                    + "attribute defined on view " + mHostView.getClass() + idText);
4483        }
4484    }
4485
4486    /**
4487     * Non-public constructor for use in testing
4488     */
4489    View() {
4490        mResources = null;
4491        mRenderNode = RenderNode.create(getClass().getName(), this);
4492    }
4493
4494    private static SparseArray<String> getAttributeMap() {
4495        if (mAttributeMap == null) {
4496            mAttributeMap = new SparseArray<>();
4497        }
4498        return mAttributeMap;
4499    }
4500
4501    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4502        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4503        final int indexCount = t.getIndexCount();
4504        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4505
4506        int i = 0;
4507
4508        // Store raw XML attributes.
4509        for (int j = 0; j < attrsCount; ++j) {
4510            attributes[i] = attrs.getAttributeName(j);
4511            attributes[i + 1] = attrs.getAttributeValue(j);
4512            i += 2;
4513        }
4514
4515        // Store resolved styleable attributes.
4516        final Resources res = t.getResources();
4517        final SparseArray<String> attributeMap = getAttributeMap();
4518        for (int j = 0; j < indexCount; ++j) {
4519            final int index = t.getIndex(j);
4520            if (!t.hasValueOrEmpty(index)) {
4521                // Value is undefined. Skip it.
4522                continue;
4523            }
4524
4525            final int resourceId = t.getResourceId(index, 0);
4526            if (resourceId == 0) {
4527                // Value is not a reference. Skip it.
4528                continue;
4529            }
4530
4531            String resourceName = attributeMap.get(resourceId);
4532            if (resourceName == null) {
4533                try {
4534                    resourceName = res.getResourceName(resourceId);
4535                } catch (Resources.NotFoundException e) {
4536                    resourceName = "0x" + Integer.toHexString(resourceId);
4537                }
4538                attributeMap.put(resourceId, resourceName);
4539            }
4540
4541            attributes[i] = resourceName;
4542            attributes[i + 1] = t.getString(index);
4543            i += 2;
4544        }
4545
4546        // Trim to fit contents.
4547        final String[] trimmed = new String[i];
4548        System.arraycopy(attributes, 0, trimmed, 0, i);
4549        mAttributes = trimmed;
4550    }
4551
4552    public String toString() {
4553        StringBuilder out = new StringBuilder(128);
4554        out.append(getClass().getName());
4555        out.append('{');
4556        out.append(Integer.toHexString(System.identityHashCode(this)));
4557        out.append(' ');
4558        switch (mViewFlags&VISIBILITY_MASK) {
4559            case VISIBLE: out.append('V'); break;
4560            case INVISIBLE: out.append('I'); break;
4561            case GONE: out.append('G'); break;
4562            default: out.append('.'); break;
4563        }
4564        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4565        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4566        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4567        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4568        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4569        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4570        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4571        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4572        out.append(' ');
4573        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4574        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4575        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4576        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4577            out.append('p');
4578        } else {
4579            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4580        }
4581        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4582        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4583        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4584        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4585        out.append(' ');
4586        out.append(mLeft);
4587        out.append(',');
4588        out.append(mTop);
4589        out.append('-');
4590        out.append(mRight);
4591        out.append(',');
4592        out.append(mBottom);
4593        final int id = getId();
4594        if (id != NO_ID) {
4595            out.append(" #");
4596            out.append(Integer.toHexString(id));
4597            final Resources r = mResources;
4598            if (Resources.resourceHasPackage(id) && r != null) {
4599                try {
4600                    String pkgname;
4601                    switch (id&0xff000000) {
4602                        case 0x7f000000:
4603                            pkgname="app";
4604                            break;
4605                        case 0x01000000:
4606                            pkgname="android";
4607                            break;
4608                        default:
4609                            pkgname = r.getResourcePackageName(id);
4610                            break;
4611                    }
4612                    String typename = r.getResourceTypeName(id);
4613                    String entryname = r.getResourceEntryName(id);
4614                    out.append(" ");
4615                    out.append(pkgname);
4616                    out.append(":");
4617                    out.append(typename);
4618                    out.append("/");
4619                    out.append(entryname);
4620                } catch (Resources.NotFoundException e) {
4621                }
4622            }
4623        }
4624        out.append("}");
4625        return out.toString();
4626    }
4627
4628    /**
4629     * <p>
4630     * Initializes the fading edges from a given set of styled attributes. This
4631     * method should be called by subclasses that need fading edges and when an
4632     * instance of these subclasses is created programmatically rather than
4633     * being inflated from XML. This method is automatically called when the XML
4634     * is inflated.
4635     * </p>
4636     *
4637     * @param a the styled attributes set to initialize the fading edges from
4638     *
4639     * @removed
4640     */
4641    protected void initializeFadingEdge(TypedArray a) {
4642        // This method probably shouldn't have been included in the SDK to begin with.
4643        // It relies on 'a' having been initialized using an attribute filter array that is
4644        // not publicly available to the SDK. The old method has been renamed
4645        // to initializeFadingEdgeInternal and hidden for framework use only;
4646        // this one initializes using defaults to make it safe to call for apps.
4647
4648        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4649
4650        initializeFadingEdgeInternal(arr);
4651
4652        arr.recycle();
4653    }
4654
4655    /**
4656     * <p>
4657     * Initializes the fading edges from a given set of styled attributes. This
4658     * method should be called by subclasses that need fading edges and when an
4659     * instance of these subclasses is created programmatically rather than
4660     * being inflated from XML. This method is automatically called when the XML
4661     * is inflated.
4662     * </p>
4663     *
4664     * @param a the styled attributes set to initialize the fading edges from
4665     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4666     */
4667    protected void initializeFadingEdgeInternal(TypedArray a) {
4668        initScrollCache();
4669
4670        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4671                R.styleable.View_fadingEdgeLength,
4672                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4673    }
4674
4675    /**
4676     * Returns the size of the vertical faded edges used to indicate that more
4677     * content in this view is visible.
4678     *
4679     * @return The size in pixels of the vertical faded edge or 0 if vertical
4680     *         faded edges are not enabled for this view.
4681     * @attr ref android.R.styleable#View_fadingEdgeLength
4682     */
4683    public int getVerticalFadingEdgeLength() {
4684        if (isVerticalFadingEdgeEnabled()) {
4685            ScrollabilityCache cache = mScrollCache;
4686            if (cache != null) {
4687                return cache.fadingEdgeLength;
4688            }
4689        }
4690        return 0;
4691    }
4692
4693    /**
4694     * Set the size of the faded edge used to indicate that more content in this
4695     * view is available.  Will not change whether the fading edge is enabled; use
4696     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4697     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4698     * for the vertical or horizontal fading edges.
4699     *
4700     * @param length The size in pixels of the faded edge used to indicate that more
4701     *        content in this view is visible.
4702     */
4703    public void setFadingEdgeLength(int length) {
4704        initScrollCache();
4705        mScrollCache.fadingEdgeLength = length;
4706    }
4707
4708    /**
4709     * Returns the size of the horizontal faded edges used to indicate that more
4710     * content in this view is visible.
4711     *
4712     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4713     *         faded edges are not enabled for this view.
4714     * @attr ref android.R.styleable#View_fadingEdgeLength
4715     */
4716    public int getHorizontalFadingEdgeLength() {
4717        if (isHorizontalFadingEdgeEnabled()) {
4718            ScrollabilityCache cache = mScrollCache;
4719            if (cache != null) {
4720                return cache.fadingEdgeLength;
4721            }
4722        }
4723        return 0;
4724    }
4725
4726    /**
4727     * Returns the width of the vertical scrollbar.
4728     *
4729     * @return The width in pixels of the vertical scrollbar or 0 if there
4730     *         is no vertical scrollbar.
4731     */
4732    public int getVerticalScrollbarWidth() {
4733        ScrollabilityCache cache = mScrollCache;
4734        if (cache != null) {
4735            ScrollBarDrawable scrollBar = cache.scrollBar;
4736            if (scrollBar != null) {
4737                int size = scrollBar.getSize(true);
4738                if (size <= 0) {
4739                    size = cache.scrollBarSize;
4740                }
4741                return size;
4742            }
4743            return 0;
4744        }
4745        return 0;
4746    }
4747
4748    /**
4749     * Returns the height of the horizontal scrollbar.
4750     *
4751     * @return The height in pixels of the horizontal scrollbar or 0 if
4752     *         there is no horizontal scrollbar.
4753     */
4754    protected int getHorizontalScrollbarHeight() {
4755        ScrollabilityCache cache = mScrollCache;
4756        if (cache != null) {
4757            ScrollBarDrawable scrollBar = cache.scrollBar;
4758            if (scrollBar != null) {
4759                int size = scrollBar.getSize(false);
4760                if (size <= 0) {
4761                    size = cache.scrollBarSize;
4762                }
4763                return size;
4764            }
4765            return 0;
4766        }
4767        return 0;
4768    }
4769
4770    /**
4771     * <p>
4772     * Initializes the scrollbars from a given set of styled attributes. This
4773     * method should be called by subclasses that need scrollbars and when an
4774     * instance of these subclasses is created programmatically rather than
4775     * being inflated from XML. This method is automatically called when the XML
4776     * is inflated.
4777     * </p>
4778     *
4779     * @param a the styled attributes set to initialize the scrollbars from
4780     *
4781     * @removed
4782     */
4783    protected void initializeScrollbars(TypedArray a) {
4784        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4785        // using the View filter array which is not available to the SDK. As such, internal
4786        // framework usage now uses initializeScrollbarsInternal and we grab a default
4787        // TypedArray with the right filter instead here.
4788        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4789
4790        initializeScrollbarsInternal(arr);
4791
4792        // We ignored the method parameter. Recycle the one we actually did use.
4793        arr.recycle();
4794    }
4795
4796    /**
4797     * <p>
4798     * Initializes the scrollbars from a given set of styled attributes. This
4799     * method should be called by subclasses that need scrollbars and when an
4800     * instance of these subclasses is created programmatically rather than
4801     * being inflated from XML. This method is automatically called when the XML
4802     * is inflated.
4803     * </p>
4804     *
4805     * @param a the styled attributes set to initialize the scrollbars from
4806     * @hide
4807     */
4808    protected void initializeScrollbarsInternal(TypedArray a) {
4809        initScrollCache();
4810
4811        final ScrollabilityCache scrollabilityCache = mScrollCache;
4812
4813        if (scrollabilityCache.scrollBar == null) {
4814            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4815            scrollabilityCache.scrollBar.setCallback(this);
4816            scrollabilityCache.scrollBar.setState(getDrawableState());
4817        }
4818
4819        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4820
4821        if (!fadeScrollbars) {
4822            scrollabilityCache.state = ScrollabilityCache.ON;
4823        }
4824        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4825
4826
4827        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4828                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4829                        .getScrollBarFadeDuration());
4830        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4831                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4832                ViewConfiguration.getScrollDefaultDelay());
4833
4834
4835        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4836                com.android.internal.R.styleable.View_scrollbarSize,
4837                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4838
4839        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4840        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4841
4842        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4843        if (thumb != null) {
4844            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4845        }
4846
4847        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4848                false);
4849        if (alwaysDraw) {
4850            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4851        }
4852
4853        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4854        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4855
4856        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4857        if (thumb != null) {
4858            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4859        }
4860
4861        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4862                false);
4863        if (alwaysDraw) {
4864            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4865        }
4866
4867        // Apply layout direction to the new Drawables if needed
4868        final int layoutDirection = getLayoutDirection();
4869        if (track != null) {
4870            track.setLayoutDirection(layoutDirection);
4871        }
4872        if (thumb != null) {
4873            thumb.setLayoutDirection(layoutDirection);
4874        }
4875
4876        // Re-apply user/background padding so that scrollbar(s) get added
4877        resolvePadding();
4878    }
4879
4880    private void initializeScrollIndicatorsInternal() {
4881        // Some day maybe we'll break this into top/left/start/etc. and let the
4882        // client control it. Until then, you can have any scroll indicator you
4883        // want as long as it's a 1dp foreground-colored rectangle.
4884        if (mScrollIndicatorDrawable == null) {
4885            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
4886        }
4887    }
4888
4889    /**
4890     * <p>
4891     * Initalizes the scrollability cache if necessary.
4892     * </p>
4893     */
4894    private void initScrollCache() {
4895        if (mScrollCache == null) {
4896            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4897        }
4898    }
4899
4900    private ScrollabilityCache getScrollCache() {
4901        initScrollCache();
4902        return mScrollCache;
4903    }
4904
4905    /**
4906     * Set the position of the vertical scroll bar. Should be one of
4907     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4908     * {@link #SCROLLBAR_POSITION_RIGHT}.
4909     *
4910     * @param position Where the vertical scroll bar should be positioned.
4911     */
4912    public void setVerticalScrollbarPosition(int position) {
4913        if (mVerticalScrollbarPosition != position) {
4914            mVerticalScrollbarPosition = position;
4915            computeOpaqueFlags();
4916            resolvePadding();
4917        }
4918    }
4919
4920    /**
4921     * @return The position where the vertical scroll bar will show, if applicable.
4922     * @see #setVerticalScrollbarPosition(int)
4923     */
4924    public int getVerticalScrollbarPosition() {
4925        return mVerticalScrollbarPosition;
4926    }
4927
4928    /**
4929     * Sets the state of all scroll indicators.
4930     * <p>
4931     * See {@link #setScrollIndicators(int, int)} for usage information.
4932     *
4933     * @param indicators a bitmask of indicators that should be enabled, or
4934     *                   {@code 0} to disable all indicators
4935     * @see #setScrollIndicators(int, int)
4936     * @see #getScrollIndicators()
4937     * @attr ref android.R.styleable#View_scrollIndicators
4938     */
4939    public void setScrollIndicators(@ScrollIndicators int indicators) {
4940        setScrollIndicators(indicators,
4941                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
4942    }
4943
4944    /**
4945     * Sets the state of the scroll indicators specified by the mask. To change
4946     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
4947     * <p>
4948     * When a scroll indicator is enabled, it will be displayed if the view
4949     * can scroll in the direction of the indicator.
4950     * <p>
4951     * Multiple indicator types may be enabled or disabled by passing the
4952     * logical OR of the desired types. If multiple types are specified, they
4953     * will all be set to the same enabled state.
4954     * <p>
4955     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
4956     *
4957     * @param indicators the indicator direction, or the logical OR of multiple
4958     *             indicator directions. One or more of:
4959     *             <ul>
4960     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
4961     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
4962     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
4963     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
4964     *               <li>{@link #SCROLL_INDICATOR_START}</li>
4965     *               <li>{@link #SCROLL_INDICATOR_END}</li>
4966     *             </ul>
4967     * @see #setScrollIndicators(int)
4968     * @see #getScrollIndicators()
4969     * @attr ref android.R.styleable#View_scrollIndicators
4970     */
4971    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
4972        // Shift and sanitize mask.
4973        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
4974        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
4975
4976        // Shift and mask indicators.
4977        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
4978        indicators &= mask;
4979
4980        // Merge with non-masked flags.
4981        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
4982
4983        if (mPrivateFlags3 != updatedFlags) {
4984            mPrivateFlags3 = updatedFlags;
4985
4986            if (indicators != 0) {
4987                initializeScrollIndicatorsInternal();
4988            }
4989            invalidate();
4990        }
4991    }
4992
4993    /**
4994     * Returns a bitmask representing the enabled scroll indicators.
4995     * <p>
4996     * For example, if the top and left scroll indicators are enabled and all
4997     * other indicators are disabled, the return value will be
4998     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
4999     * <p>
5000     * To check whether the bottom scroll indicator is enabled, use the value
5001     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5002     *
5003     * @return a bitmask representing the enabled scroll indicators
5004     */
5005    @ScrollIndicators
5006    public int getScrollIndicators() {
5007        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5008                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5009    }
5010
5011    ListenerInfo getListenerInfo() {
5012        if (mListenerInfo != null) {
5013            return mListenerInfo;
5014        }
5015        mListenerInfo = new ListenerInfo();
5016        return mListenerInfo;
5017    }
5018
5019    /**
5020     * Register a callback to be invoked when the scroll X or Y positions of
5021     * this view change.
5022     * <p>
5023     * <b>Note:</b> Some views handle scrolling independently from View and may
5024     * have their own separate listeners for scroll-type events. For example,
5025     * {@link android.widget.ListView ListView} allows clients to register an
5026     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5027     * to listen for changes in list scroll position.
5028     *
5029     * @param l The listener to notify when the scroll X or Y position changes.
5030     * @see android.view.View#getScrollX()
5031     * @see android.view.View#getScrollY()
5032     */
5033    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5034        getListenerInfo().mOnScrollChangeListener = l;
5035    }
5036
5037    /**
5038     * Register a callback to be invoked when focus of this view changed.
5039     *
5040     * @param l The callback that will run.
5041     */
5042    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5043        getListenerInfo().mOnFocusChangeListener = l;
5044    }
5045
5046    /**
5047     * Add a listener that will be called when the bounds of the view change due to
5048     * layout processing.
5049     *
5050     * @param listener The listener that will be called when layout bounds change.
5051     */
5052    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5053        ListenerInfo li = getListenerInfo();
5054        if (li.mOnLayoutChangeListeners == null) {
5055            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5056        }
5057        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5058            li.mOnLayoutChangeListeners.add(listener);
5059        }
5060    }
5061
5062    /**
5063     * Remove a listener for layout changes.
5064     *
5065     * @param listener The listener for layout bounds change.
5066     */
5067    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5068        ListenerInfo li = mListenerInfo;
5069        if (li == null || li.mOnLayoutChangeListeners == null) {
5070            return;
5071        }
5072        li.mOnLayoutChangeListeners.remove(listener);
5073    }
5074
5075    /**
5076     * Add a listener for attach state changes.
5077     *
5078     * This listener will be called whenever this view is attached or detached
5079     * from a window. Remove the listener using
5080     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5081     *
5082     * @param listener Listener to attach
5083     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5084     */
5085    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5086        ListenerInfo li = getListenerInfo();
5087        if (li.mOnAttachStateChangeListeners == null) {
5088            li.mOnAttachStateChangeListeners
5089                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5090        }
5091        li.mOnAttachStateChangeListeners.add(listener);
5092    }
5093
5094    /**
5095     * Remove a listener for attach state changes. The listener will receive no further
5096     * notification of window attach/detach events.
5097     *
5098     * @param listener Listener to remove
5099     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5100     */
5101    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5102        ListenerInfo li = mListenerInfo;
5103        if (li == null || li.mOnAttachStateChangeListeners == null) {
5104            return;
5105        }
5106        li.mOnAttachStateChangeListeners.remove(listener);
5107    }
5108
5109    /**
5110     * Returns the focus-change callback registered for this view.
5111     *
5112     * @return The callback, or null if one is not registered.
5113     */
5114    public OnFocusChangeListener getOnFocusChangeListener() {
5115        ListenerInfo li = mListenerInfo;
5116        return li != null ? li.mOnFocusChangeListener : null;
5117    }
5118
5119    /**
5120     * Register a callback to be invoked when this view is clicked. If this view is not
5121     * clickable, it becomes clickable.
5122     *
5123     * @param l The callback that will run
5124     *
5125     * @see #setClickable(boolean)
5126     */
5127    public void setOnClickListener(@Nullable OnClickListener l) {
5128        if (!isClickable()) {
5129            setClickable(true);
5130        }
5131        getListenerInfo().mOnClickListener = l;
5132    }
5133
5134    /**
5135     * Return whether this view has an attached OnClickListener.  Returns
5136     * true if there is a listener, false if there is none.
5137     */
5138    public boolean hasOnClickListeners() {
5139        ListenerInfo li = mListenerInfo;
5140        return (li != null && li.mOnClickListener != null);
5141    }
5142
5143    /**
5144     * Register a callback to be invoked when this view is clicked and held. If this view is not
5145     * long clickable, it becomes long clickable.
5146     *
5147     * @param l The callback that will run
5148     *
5149     * @see #setLongClickable(boolean)
5150     */
5151    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5152        if (!isLongClickable()) {
5153            setLongClickable(true);
5154        }
5155        getListenerInfo().mOnLongClickListener = l;
5156    }
5157
5158    /**
5159     * Register a callback to be invoked when this view is context clicked. If the view is not
5160     * context clickable, it becomes context clickable.
5161     *
5162     * @param l The callback that will run
5163     * @see #setContextClickable(boolean)
5164     */
5165    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5166        if (!isContextClickable()) {
5167            setContextClickable(true);
5168        }
5169        getListenerInfo().mOnContextClickListener = l;
5170    }
5171
5172    /**
5173     * Register a callback to be invoked when the context menu for this view is
5174     * being built. If this view is not long clickable, it becomes long clickable.
5175     *
5176     * @param l The callback that will run
5177     *
5178     */
5179    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5180        if (!isLongClickable()) {
5181            setLongClickable(true);
5182        }
5183        getListenerInfo().mOnCreateContextMenuListener = l;
5184    }
5185
5186    /**
5187     * Call this view's OnClickListener, if it is defined.  Performs all normal
5188     * actions associated with clicking: reporting accessibility event, playing
5189     * a sound, etc.
5190     *
5191     * @return True there was an assigned OnClickListener that was called, false
5192     *         otherwise is returned.
5193     */
5194    public boolean performClick() {
5195        final boolean result;
5196        final ListenerInfo li = mListenerInfo;
5197        if (li != null && li.mOnClickListener != null) {
5198            playSoundEffect(SoundEffectConstants.CLICK);
5199            li.mOnClickListener.onClick(this);
5200            result = true;
5201        } else {
5202            result = false;
5203        }
5204
5205        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5206        return result;
5207    }
5208
5209    /**
5210     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5211     * this only calls the listener, and does not do any associated clicking
5212     * actions like reporting an accessibility event.
5213     *
5214     * @return True there was an assigned OnClickListener that was called, false
5215     *         otherwise is returned.
5216     */
5217    public boolean callOnClick() {
5218        ListenerInfo li = mListenerInfo;
5219        if (li != null && li.mOnClickListener != null) {
5220            li.mOnClickListener.onClick(this);
5221            return true;
5222        }
5223        return false;
5224    }
5225
5226    /**
5227     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
5228     * OnLongClickListener did not consume the event.
5229     *
5230     * @return True if one of the above receivers consumed the event, false otherwise.
5231     */
5232    public boolean performLongClick() {
5233        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5234
5235        boolean handled = false;
5236        ListenerInfo li = mListenerInfo;
5237        if (li != null && li.mOnLongClickListener != null) {
5238            handled = li.mOnLongClickListener.onLongClick(View.this);
5239        }
5240        if (!handled) {
5241            handled = showContextMenu();
5242        }
5243        if (handled) {
5244            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5245        }
5246        return handled;
5247    }
5248
5249    /**
5250     * Call this view's OnContextClickListener, if it is defined.
5251     *
5252     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5253     *         otherwise.
5254     */
5255    public boolean performContextClick() {
5256        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5257
5258        boolean handled = false;
5259        ListenerInfo li = mListenerInfo;
5260        if (li != null && li.mOnContextClickListener != null) {
5261            handled = li.mOnContextClickListener.onContextClick(View.this);
5262        }
5263        if (handled) {
5264            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5265        }
5266        return handled;
5267    }
5268
5269    /**
5270     * Performs button-related actions during a touch down event.
5271     *
5272     * @param event The event.
5273     * @return True if the down was consumed.
5274     *
5275     * @hide
5276     */
5277    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5278        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&
5279            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5280            showContextMenu(event.getX(), event.getY(), event.getMetaState());
5281            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5282            return true;
5283        }
5284        return false;
5285    }
5286
5287    /**
5288     * Bring up the context menu for this view.
5289     *
5290     * @return Whether a context menu was displayed.
5291     */
5292    public boolean showContextMenu() {
5293        return getParent().showContextMenuForChild(this);
5294    }
5295
5296    /**
5297     * Bring up the context menu for this view, referring to the item under the specified point.
5298     *
5299     * @param x The referenced x coordinate.
5300     * @param y The referenced y coordinate.
5301     * @param metaState The keyboard modifiers that were pressed.
5302     * @return Whether a context menu was displayed.
5303     *
5304     * @hide
5305     */
5306    public boolean showContextMenu(float x, float y, int metaState) {
5307        return showContextMenu();
5308    }
5309
5310    /**
5311     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5312     *
5313     * @param callback Callback that will control the lifecycle of the action mode
5314     * @return The new action mode if it is started, null otherwise
5315     *
5316     * @see ActionMode
5317     * @see #startActionMode(android.view.ActionMode.Callback, int)
5318     */
5319    public ActionMode startActionMode(ActionMode.Callback callback) {
5320        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5321    }
5322
5323    /**
5324     * Start an action mode with the given type.
5325     *
5326     * @param callback Callback that will control the lifecycle of the action mode
5327     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5328     * @return The new action mode if it is started, null otherwise
5329     *
5330     * @see ActionMode
5331     */
5332    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5333        ViewParent parent = getParent();
5334        if (parent == null) return null;
5335        try {
5336            return parent.startActionModeForChild(this, callback, type);
5337        } catch (AbstractMethodError ame) {
5338            // Older implementations of custom views might not implement this.
5339            return parent.startActionModeForChild(this, callback);
5340        }
5341    }
5342
5343    /**
5344     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5345     * Context, creating a unique View identifier to retrieve the result.
5346     *
5347     * @param intent The Intent to be started.
5348     * @param requestCode The request code to use.
5349     * @hide
5350     */
5351    public void startActivityForResult(Intent intent, int requestCode) {
5352        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5353        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5354    }
5355
5356    /**
5357     * If this View corresponds to the calling who, dispatches the activity result.
5358     * @param who The identifier for the targeted View to receive the result.
5359     * @param requestCode The integer request code originally supplied to
5360     *                    startActivityForResult(), allowing you to identify who this
5361     *                    result came from.
5362     * @param resultCode The integer result code returned by the child activity
5363     *                   through its setResult().
5364     * @param data An Intent, which can return result data to the caller
5365     *               (various data can be attached to Intent "extras").
5366     * @return {@code true} if the activity result was dispatched.
5367     * @hide
5368     */
5369    public boolean dispatchActivityResult(
5370            String who, int requestCode, int resultCode, Intent data) {
5371        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5372            onActivityResult(requestCode, resultCode, data);
5373            mStartActivityRequestWho = null;
5374            return true;
5375        }
5376        return false;
5377    }
5378
5379    /**
5380     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5381     *
5382     * @param requestCode The integer request code originally supplied to
5383     *                    startActivityForResult(), allowing you to identify who this
5384     *                    result came from.
5385     * @param resultCode The integer result code returned by the child activity
5386     *                   through its setResult().
5387     * @param data An Intent, which can return result data to the caller
5388     *               (various data can be attached to Intent "extras").
5389     * @hide
5390     */
5391    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5392        // Do nothing.
5393    }
5394
5395    /**
5396     * Register a callback to be invoked when a hardware key is pressed in this view.
5397     * Key presses in software input methods will generally not trigger the methods of
5398     * this listener.
5399     * @param l the key listener to attach to this view
5400     */
5401    public void setOnKeyListener(OnKeyListener l) {
5402        getListenerInfo().mOnKeyListener = l;
5403    }
5404
5405    /**
5406     * Register a callback to be invoked when a touch event is sent to this view.
5407     * @param l the touch listener to attach to this view
5408     */
5409    public void setOnTouchListener(OnTouchListener l) {
5410        getListenerInfo().mOnTouchListener = l;
5411    }
5412
5413    /**
5414     * Register a callback to be invoked when a generic motion event is sent to this view.
5415     * @param l the generic motion listener to attach to this view
5416     */
5417    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5418        getListenerInfo().mOnGenericMotionListener = l;
5419    }
5420
5421    /**
5422     * Register a callback to be invoked when a hover event is sent to this view.
5423     * @param l the hover listener to attach to this view
5424     */
5425    public void setOnHoverListener(OnHoverListener l) {
5426        getListenerInfo().mOnHoverListener = l;
5427    }
5428
5429    /**
5430     * Register a drag event listener callback object for this View. The parameter is
5431     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5432     * View, the system calls the
5433     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5434     * @param l An implementation of {@link android.view.View.OnDragListener}.
5435     */
5436    public void setOnDragListener(OnDragListener l) {
5437        getListenerInfo().mOnDragListener = l;
5438    }
5439
5440    /**
5441     * Give this view focus. This will cause
5442     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5443     *
5444     * Note: this does not check whether this {@link View} should get focus, it just
5445     * gives it focus no matter what.  It should only be called internally by framework
5446     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5447     *
5448     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5449     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5450     *        focus moved when requestFocus() is called. It may not always
5451     *        apply, in which case use the default View.FOCUS_DOWN.
5452     * @param previouslyFocusedRect The rectangle of the view that had focus
5453     *        prior in this View's coordinate system.
5454     */
5455    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5456        if (DBG) {
5457            System.out.println(this + " requestFocus()");
5458        }
5459
5460        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5461            mPrivateFlags |= PFLAG_FOCUSED;
5462
5463            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5464
5465            if (mParent != null) {
5466                mParent.requestChildFocus(this, this);
5467            }
5468
5469            if (mAttachInfo != null) {
5470                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5471            }
5472
5473            onFocusChanged(true, direction, previouslyFocusedRect);
5474            refreshDrawableState();
5475        }
5476    }
5477
5478    /**
5479     * Populates <code>outRect</code> with the hotspot bounds. By default,
5480     * the hotspot bounds are identical to the screen bounds.
5481     *
5482     * @param outRect rect to populate with hotspot bounds
5483     * @hide Only for internal use by views and widgets.
5484     */
5485    public void getHotspotBounds(Rect outRect) {
5486        final Drawable background = getBackground();
5487        if (background != null) {
5488            background.getHotspotBounds(outRect);
5489        } else {
5490            getBoundsOnScreen(outRect);
5491        }
5492    }
5493
5494    /**
5495     * Request that a rectangle of this view be visible on the screen,
5496     * scrolling if necessary just enough.
5497     *
5498     * <p>A View should call this if it maintains some notion of which part
5499     * of its content is interesting.  For example, a text editing view
5500     * should call this when its cursor moves.
5501     *
5502     * @param rectangle The rectangle.
5503     * @return Whether any parent scrolled.
5504     */
5505    public boolean requestRectangleOnScreen(Rect rectangle) {
5506        return requestRectangleOnScreen(rectangle, false);
5507    }
5508
5509    /**
5510     * Request that a rectangle of this view be visible on the screen,
5511     * scrolling if necessary just enough.
5512     *
5513     * <p>A View should call this if it maintains some notion of which part
5514     * of its content is interesting.  For example, a text editing view
5515     * should call this when its cursor moves.
5516     *
5517     * <p>When <code>immediate</code> is set to true, scrolling will not be
5518     * animated.
5519     *
5520     * @param rectangle The rectangle.
5521     * @param immediate True to forbid animated scrolling, false otherwise
5522     * @return Whether any parent scrolled.
5523     */
5524    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5525        if (mParent == null) {
5526            return false;
5527        }
5528
5529        View child = this;
5530
5531        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5532        position.set(rectangle);
5533
5534        ViewParent parent = mParent;
5535        boolean scrolled = false;
5536        while (parent != null) {
5537            rectangle.set((int) position.left, (int) position.top,
5538                    (int) position.right, (int) position.bottom);
5539
5540            scrolled |= parent.requestChildRectangleOnScreen(child,
5541                    rectangle, immediate);
5542
5543            if (!child.hasIdentityMatrix()) {
5544                child.getMatrix().mapRect(position);
5545            }
5546
5547            position.offset(child.mLeft, child.mTop);
5548
5549            if (!(parent instanceof View)) {
5550                break;
5551            }
5552
5553            View parentView = (View) parent;
5554
5555            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5556
5557            child = parentView;
5558            parent = child.getParent();
5559        }
5560
5561        return scrolled;
5562    }
5563
5564    /**
5565     * Called when this view wants to give up focus. If focus is cleared
5566     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5567     * <p>
5568     * <strong>Note:</strong> When a View clears focus the framework is trying
5569     * to give focus to the first focusable View from the top. Hence, if this
5570     * View is the first from the top that can take focus, then all callbacks
5571     * related to clearing focus will be invoked after which the framework will
5572     * give focus to this view.
5573     * </p>
5574     */
5575    public void clearFocus() {
5576        if (DBG) {
5577            System.out.println(this + " clearFocus()");
5578        }
5579
5580        clearFocusInternal(null, true, true);
5581    }
5582
5583    /**
5584     * Clears focus from the view, optionally propagating the change up through
5585     * the parent hierarchy and requesting that the root view place new focus.
5586     *
5587     * @param propagate whether to propagate the change up through the parent
5588     *            hierarchy
5589     * @param refocus when propagate is true, specifies whether to request the
5590     *            root view place new focus
5591     */
5592    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5593        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5594            mPrivateFlags &= ~PFLAG_FOCUSED;
5595
5596            if (propagate && mParent != null) {
5597                mParent.clearChildFocus(this);
5598            }
5599
5600            onFocusChanged(false, 0, null);
5601            refreshDrawableState();
5602
5603            if (propagate && (!refocus || !rootViewRequestFocus())) {
5604                notifyGlobalFocusCleared(this);
5605            }
5606        }
5607    }
5608
5609    void notifyGlobalFocusCleared(View oldFocus) {
5610        if (oldFocus != null && mAttachInfo != null) {
5611            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5612        }
5613    }
5614
5615    boolean rootViewRequestFocus() {
5616        final View root = getRootView();
5617        return root != null && root.requestFocus();
5618    }
5619
5620    /**
5621     * Called internally by the view system when a new view is getting focus.
5622     * This is what clears the old focus.
5623     * <p>
5624     * <b>NOTE:</b> The parent view's focused child must be updated manually
5625     * after calling this method. Otherwise, the view hierarchy may be left in
5626     * an inconstent state.
5627     */
5628    void unFocus(View focused) {
5629        if (DBG) {
5630            System.out.println(this + " unFocus()");
5631        }
5632
5633        clearFocusInternal(focused, false, false);
5634    }
5635
5636    /**
5637     * Returns true if this view has focus itself, or is the ancestor of the
5638     * view that has focus.
5639     *
5640     * @return True if this view has or contains focus, false otherwise.
5641     */
5642    @ViewDebug.ExportedProperty(category = "focus")
5643    public boolean hasFocus() {
5644        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5645    }
5646
5647    /**
5648     * Returns true if this view is focusable or if it contains a reachable View
5649     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5650     * is a View whose parents do not block descendants focus.
5651     *
5652     * Only {@link #VISIBLE} views are considered focusable.
5653     *
5654     * @return True if the view is focusable or if the view contains a focusable
5655     *         View, false otherwise.
5656     *
5657     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5658     * @see ViewGroup#getTouchscreenBlocksFocus()
5659     */
5660    public boolean hasFocusable() {
5661        if (!isFocusableInTouchMode()) {
5662            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5663                final ViewGroup g = (ViewGroup) p;
5664                if (g.shouldBlockFocusForTouchscreen()) {
5665                    return false;
5666                }
5667            }
5668        }
5669        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5670    }
5671
5672    /**
5673     * Called by the view system when the focus state of this view changes.
5674     * When the focus change event is caused by directional navigation, direction
5675     * and previouslyFocusedRect provide insight into where the focus is coming from.
5676     * When overriding, be sure to call up through to the super class so that
5677     * the standard focus handling will occur.
5678     *
5679     * @param gainFocus True if the View has focus; false otherwise.
5680     * @param direction The direction focus has moved when requestFocus()
5681     *                  is called to give this view focus. Values are
5682     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5683     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5684     *                  It may not always apply, in which case use the default.
5685     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5686     *        system, of the previously focused view.  If applicable, this will be
5687     *        passed in as finer grained information about where the focus is coming
5688     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5689     */
5690    @CallSuper
5691    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5692            @Nullable Rect previouslyFocusedRect) {
5693        if (gainFocus) {
5694            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5695        } else {
5696            notifyViewAccessibilityStateChangedIfNeeded(
5697                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5698        }
5699
5700        InputMethodManager imm = InputMethodManager.peekInstance();
5701        if (!gainFocus) {
5702            if (isPressed()) {
5703                setPressed(false);
5704            }
5705            if (imm != null && mAttachInfo != null
5706                    && mAttachInfo.mHasWindowFocus) {
5707                imm.focusOut(this);
5708            }
5709            onFocusLost();
5710        } else if (imm != null && mAttachInfo != null
5711                && mAttachInfo.mHasWindowFocus) {
5712            imm.focusIn(this);
5713        }
5714
5715        invalidate(true);
5716        ListenerInfo li = mListenerInfo;
5717        if (li != null && li.mOnFocusChangeListener != null) {
5718            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5719        }
5720
5721        if (mAttachInfo != null) {
5722            mAttachInfo.mKeyDispatchState.reset(this);
5723        }
5724    }
5725
5726    /**
5727     * Sends an accessibility event of the given type. If accessibility is
5728     * not enabled this method has no effect. The default implementation calls
5729     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5730     * to populate information about the event source (this View), then calls
5731     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5732     * populate the text content of the event source including its descendants,
5733     * and last calls
5734     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5735     * on its parent to request sending of the event to interested parties.
5736     * <p>
5737     * If an {@link AccessibilityDelegate} has been specified via calling
5738     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5739     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5740     * responsible for handling this call.
5741     * </p>
5742     *
5743     * @param eventType The type of the event to send, as defined by several types from
5744     * {@link android.view.accessibility.AccessibilityEvent}, such as
5745     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5746     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5747     *
5748     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5749     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5750     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5751     * @see AccessibilityDelegate
5752     */
5753    public void sendAccessibilityEvent(int eventType) {
5754        if (mAccessibilityDelegate != null) {
5755            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5756        } else {
5757            sendAccessibilityEventInternal(eventType);
5758        }
5759    }
5760
5761    /**
5762     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5763     * {@link AccessibilityEvent} to make an announcement which is related to some
5764     * sort of a context change for which none of the events representing UI transitions
5765     * is a good fit. For example, announcing a new page in a book. If accessibility
5766     * is not enabled this method does nothing.
5767     *
5768     * @param text The announcement text.
5769     */
5770    public void announceForAccessibility(CharSequence text) {
5771        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5772            AccessibilityEvent event = AccessibilityEvent.obtain(
5773                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5774            onInitializeAccessibilityEvent(event);
5775            event.getText().add(text);
5776            event.setContentDescription(null);
5777            mParent.requestSendAccessibilityEvent(this, event);
5778        }
5779    }
5780
5781    /**
5782     * @see #sendAccessibilityEvent(int)
5783     *
5784     * Note: Called from the default {@link AccessibilityDelegate}.
5785     *
5786     * @hide
5787     */
5788    public void sendAccessibilityEventInternal(int eventType) {
5789        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5790            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5791        }
5792    }
5793
5794    /**
5795     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5796     * takes as an argument an empty {@link AccessibilityEvent} and does not
5797     * perform a check whether accessibility is enabled.
5798     * <p>
5799     * If an {@link AccessibilityDelegate} has been specified via calling
5800     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5801     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5802     * is responsible for handling this call.
5803     * </p>
5804     *
5805     * @param event The event to send.
5806     *
5807     * @see #sendAccessibilityEvent(int)
5808     */
5809    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5810        if (mAccessibilityDelegate != null) {
5811            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5812        } else {
5813            sendAccessibilityEventUncheckedInternal(event);
5814        }
5815    }
5816
5817    /**
5818     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5819     *
5820     * Note: Called from the default {@link AccessibilityDelegate}.
5821     *
5822     * @hide
5823     */
5824    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5825        if (!isShown()) {
5826            return;
5827        }
5828        onInitializeAccessibilityEvent(event);
5829        // Only a subset of accessibility events populates text content.
5830        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5831            dispatchPopulateAccessibilityEvent(event);
5832        }
5833        // In the beginning we called #isShown(), so we know that getParent() is not null.
5834        getParent().requestSendAccessibilityEvent(this, event);
5835    }
5836
5837    /**
5838     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5839     * to its children for adding their text content to the event. Note that the
5840     * event text is populated in a separate dispatch path since we add to the
5841     * event not only the text of the source but also the text of all its descendants.
5842     * A typical implementation will call
5843     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5844     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5845     * on each child. Override this method if custom population of the event text
5846     * content is required.
5847     * <p>
5848     * If an {@link AccessibilityDelegate} has been specified via calling
5849     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5850     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5851     * is responsible for handling this call.
5852     * </p>
5853     * <p>
5854     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5855     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5856     * </p>
5857     *
5858     * @param event The event.
5859     *
5860     * @return True if the event population was completed.
5861     */
5862    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5863        if (mAccessibilityDelegate != null) {
5864            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5865        } else {
5866            return dispatchPopulateAccessibilityEventInternal(event);
5867        }
5868    }
5869
5870    /**
5871     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5872     *
5873     * Note: Called from the default {@link AccessibilityDelegate}.
5874     *
5875     * @hide
5876     */
5877    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5878        onPopulateAccessibilityEvent(event);
5879        return false;
5880    }
5881
5882    /**
5883     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5884     * giving a chance to this View to populate the accessibility event with its
5885     * text content. While this method is free to modify event
5886     * attributes other than text content, doing so should normally be performed in
5887     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5888     * <p>
5889     * Example: Adding formatted date string to an accessibility event in addition
5890     *          to the text added by the super implementation:
5891     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5892     *     super.onPopulateAccessibilityEvent(event);
5893     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5894     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5895     *         mCurrentDate.getTimeInMillis(), flags);
5896     *     event.getText().add(selectedDateUtterance);
5897     * }</pre>
5898     * <p>
5899     * If an {@link AccessibilityDelegate} has been specified via calling
5900     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5901     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5902     * is responsible for handling this call.
5903     * </p>
5904     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5905     * information to the event, in case the default implementation has basic information to add.
5906     * </p>
5907     *
5908     * @param event The accessibility event which to populate.
5909     *
5910     * @see #sendAccessibilityEvent(int)
5911     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5912     */
5913    @CallSuper
5914    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5915        if (mAccessibilityDelegate != null) {
5916            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5917        } else {
5918            onPopulateAccessibilityEventInternal(event);
5919        }
5920    }
5921
5922    /**
5923     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5924     *
5925     * Note: Called from the default {@link AccessibilityDelegate}.
5926     *
5927     * @hide
5928     */
5929    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5930    }
5931
5932    /**
5933     * Initializes an {@link AccessibilityEvent} with information about
5934     * this View which is the event source. In other words, the source of
5935     * an accessibility event is the view whose state change triggered firing
5936     * the event.
5937     * <p>
5938     * Example: Setting the password property of an event in addition
5939     *          to properties set by the super implementation:
5940     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5941     *     super.onInitializeAccessibilityEvent(event);
5942     *     event.setPassword(true);
5943     * }</pre>
5944     * <p>
5945     * If an {@link AccessibilityDelegate} has been specified via calling
5946     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5947     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5948     * is responsible for handling this call.
5949     * </p>
5950     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5951     * information to the event, in case the default implementation has basic information to add.
5952     * </p>
5953     * @param event The event to initialize.
5954     *
5955     * @see #sendAccessibilityEvent(int)
5956     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5957     */
5958    @CallSuper
5959    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5960        if (mAccessibilityDelegate != null) {
5961            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5962        } else {
5963            onInitializeAccessibilityEventInternal(event);
5964        }
5965    }
5966
5967    /**
5968     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5969     *
5970     * Note: Called from the default {@link AccessibilityDelegate}.
5971     *
5972     * @hide
5973     */
5974    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5975        event.setSource(this);
5976        event.setClassName(getAccessibilityClassName());
5977        event.setPackageName(getContext().getPackageName());
5978        event.setEnabled(isEnabled());
5979        event.setContentDescription(mContentDescription);
5980
5981        switch (event.getEventType()) {
5982            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5983                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5984                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5985                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5986                event.setItemCount(focusablesTempList.size());
5987                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5988                if (mAttachInfo != null) {
5989                    focusablesTempList.clear();
5990                }
5991            } break;
5992            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5993                CharSequence text = getIterableTextForAccessibility();
5994                if (text != null && text.length() > 0) {
5995                    event.setFromIndex(getAccessibilitySelectionStart());
5996                    event.setToIndex(getAccessibilitySelectionEnd());
5997                    event.setItemCount(text.length());
5998                }
5999            } break;
6000        }
6001    }
6002
6003    /**
6004     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6005     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6006     * This method is responsible for obtaining an accessibility node info from a
6007     * pool of reusable instances and calling
6008     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6009     * initialize the former.
6010     * <p>
6011     * Note: The client is responsible for recycling the obtained instance by calling
6012     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6013     * </p>
6014     *
6015     * @return A populated {@link AccessibilityNodeInfo}.
6016     *
6017     * @see AccessibilityNodeInfo
6018     */
6019    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6020        if (mAccessibilityDelegate != null) {
6021            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6022        } else {
6023            return createAccessibilityNodeInfoInternal();
6024        }
6025    }
6026
6027    /**
6028     * @see #createAccessibilityNodeInfo()
6029     *
6030     * @hide
6031     */
6032    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6033        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6034        if (provider != null) {
6035            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6036        } else {
6037            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6038            onInitializeAccessibilityNodeInfo(info);
6039            return info;
6040        }
6041    }
6042
6043    /**
6044     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6045     * The base implementation sets:
6046     * <ul>
6047     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6048     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6049     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6050     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6051     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6052     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6053     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6054     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6055     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6056     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6057     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6058     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6059     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6060     * </ul>
6061     * <p>
6062     * Subclasses should override this method, call the super implementation,
6063     * and set additional attributes.
6064     * </p>
6065     * <p>
6066     * If an {@link AccessibilityDelegate} has been specified via calling
6067     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6068     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6069     * is responsible for handling this call.
6070     * </p>
6071     *
6072     * @param info The instance to initialize.
6073     */
6074    @CallSuper
6075    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6076        if (mAccessibilityDelegate != null) {
6077            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6078        } else {
6079            onInitializeAccessibilityNodeInfoInternal(info);
6080        }
6081    }
6082
6083    /**
6084     * Gets the location of this view in screen coordinates.
6085     *
6086     * @param outRect The output location
6087     * @hide
6088     */
6089    public void getBoundsOnScreen(Rect outRect) {
6090        getBoundsOnScreen(outRect, false);
6091    }
6092
6093    /**
6094     * Gets the location of this view in screen coordinates.
6095     *
6096     * @param outRect The output location
6097     * @param clipToParent Whether to clip child bounds to the parent ones.
6098     * @hide
6099     */
6100    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6101        if (mAttachInfo == null) {
6102            return;
6103        }
6104
6105        RectF position = mAttachInfo.mTmpTransformRect;
6106        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6107
6108        if (!hasIdentityMatrix()) {
6109            getMatrix().mapRect(position);
6110        }
6111
6112        position.offset(mLeft, mTop);
6113
6114        ViewParent parent = mParent;
6115        while (parent instanceof View) {
6116            View parentView = (View) parent;
6117
6118            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6119
6120            if (clipToParent) {
6121                position.left = Math.max(position.left, 0);
6122                position.top = Math.max(position.top, 0);
6123                position.right = Math.min(position.right, parentView.getWidth());
6124                position.bottom = Math.min(position.bottom, parentView.getHeight());
6125            }
6126
6127            if (!parentView.hasIdentityMatrix()) {
6128                parentView.getMatrix().mapRect(position);
6129            }
6130
6131            position.offset(parentView.mLeft, parentView.mTop);
6132
6133            parent = parentView.mParent;
6134        }
6135
6136        if (parent instanceof ViewRootImpl) {
6137            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6138            position.offset(0, -viewRootImpl.mCurScrollY);
6139        }
6140
6141        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6142
6143        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
6144                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
6145    }
6146
6147    /**
6148     * Return the class name of this object to be used for accessibility purposes.
6149     * Subclasses should only override this if they are implementing something that
6150     * should be seen as a completely new class of view when used by accessibility,
6151     * unrelated to the class it is deriving from.  This is used to fill in
6152     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6153     */
6154    public CharSequence getAccessibilityClassName() {
6155        return View.class.getName();
6156    }
6157
6158    /**
6159     * Called when assist structure is being retrieved from a view as part of
6160     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6161     * @param structure Fill in with structured view data.  The default implementation
6162     * fills in all data that can be inferred from the view itself.
6163     */
6164    public void onProvideStructure(ViewStructure structure) {
6165        final int id = mID;
6166        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6167                && (id&0x0000ffff) != 0) {
6168            String pkg, type, entry;
6169            try {
6170                final Resources res = getResources();
6171                entry = res.getResourceEntryName(id);
6172                type = res.getResourceTypeName(id);
6173                pkg = res.getResourcePackageName(id);
6174            } catch (Resources.NotFoundException e) {
6175                entry = type = pkg = null;
6176            }
6177            structure.setId(id, pkg, type, entry);
6178        } else {
6179            structure.setId(id, null, null, null);
6180        }
6181        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6182        structure.setVisibility(getVisibility());
6183        structure.setEnabled(isEnabled());
6184        if (isClickable()) {
6185            structure.setClickable(true);
6186        }
6187        if (isFocusable()) {
6188            structure.setFocusable(true);
6189        }
6190        if (isFocused()) {
6191            structure.setFocused(true);
6192        }
6193        if (isAccessibilityFocused()) {
6194            structure.setAccessibilityFocused(true);
6195        }
6196        if (isSelected()) {
6197            structure.setSelected(true);
6198        }
6199        if (isActivated()) {
6200            structure.setActivated(true);
6201        }
6202        if (isLongClickable()) {
6203            structure.setLongClickable(true);
6204        }
6205        if (this instanceof Checkable) {
6206            structure.setCheckable(true);
6207            if (((Checkable)this).isChecked()) {
6208                structure.setChecked(true);
6209            }
6210        }
6211        if (isContextClickable()) {
6212            structure.setContextClickable(true);
6213        }
6214        structure.setClassName(getAccessibilityClassName().toString());
6215        structure.setContentDescription(getContentDescription());
6216    }
6217
6218    /** @hide */
6219    public void onProvideAssistStructure(ViewStructure structure) {
6220        onProvideStructure(structure);
6221    }
6222
6223    /**
6224     * Called when assist structure is being retrieved from a view as part of
6225     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6226     * generate additional virtual structure under this view.  The defaullt implementation
6227     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6228     * view's virtual accessibility nodes, if any.  You can override this for a more
6229     * optimal implementation providing this data.
6230     */
6231    public void onProvideVirtualStructure(ViewStructure structure) {
6232        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6233        if (provider != null) {
6234            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6235            Log.i("View", "Provider of " + this + ": children=" + info.getChildCount());
6236            structure.setChildCount(1);
6237            ViewStructure root = structure.newChild(0);
6238            populateVirtualStructure(root, provider, info);
6239            info.recycle();
6240        }
6241    }
6242
6243    /** @hide */
6244    public void onProvideVirtualAssistStructure(ViewStructure structure) {
6245        onProvideVirtualStructure(structure);
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        Log.i("View", "vassist " + cname + " @ " + rect.toShortString()
6288                + " text=" + info.getText() + " cd=" + info.getContentDescription());
6289        if (info.getText() != null || info.getError() != null) {
6290            structure.setText(info.getText(), info.getTextSelectionStart(),
6291                    info.getTextSelectionEnd());
6292        }
6293        final int NCHILDREN = info.getChildCount();
6294        if (NCHILDREN > 0) {
6295            structure.setChildCount(NCHILDREN);
6296            for (int i=0; i<NCHILDREN; i++) {
6297                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6298                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6299                ViewStructure child = structure.newChild(i);
6300                populateVirtualStructure(child, provider, cinfo);
6301                cinfo.recycle();
6302            }
6303        }
6304    }
6305
6306    /**
6307     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6308     * implementation calls {@link #onProvideStructure} and
6309     * {@link #onProvideVirtualStructure}.
6310     */
6311    public void dispatchProvideStructure(ViewStructure structure) {
6312        if (!isAssistBlocked()) {
6313            onProvideAssistStructure(structure);
6314            onProvideVirtualAssistStructure(structure);
6315        } else {
6316            structure.setClassName(getAccessibilityClassName().toString());
6317            structure.setAssistBlocked(true);
6318        }
6319    }
6320
6321    /**
6322     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6323     *
6324     * Note: Called from the default {@link AccessibilityDelegate}.
6325     *
6326     * @hide
6327     */
6328    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6329        if (mAttachInfo == null) {
6330            return;
6331        }
6332
6333        Rect bounds = mAttachInfo.mTmpInvalRect;
6334
6335        getDrawingRect(bounds);
6336        info.setBoundsInParent(bounds);
6337
6338        getBoundsOnScreen(bounds, true);
6339        info.setBoundsInScreen(bounds);
6340
6341        ViewParent parent = getParentForAccessibility();
6342        if (parent instanceof View) {
6343            info.setParent((View) parent);
6344        }
6345
6346        if (mID != View.NO_ID) {
6347            View rootView = getRootView();
6348            if (rootView == null) {
6349                rootView = this;
6350            }
6351
6352            View label = rootView.findLabelForView(this, mID);
6353            if (label != null) {
6354                info.setLabeledBy(label);
6355            }
6356
6357            if ((mAttachInfo.mAccessibilityFetchFlags
6358                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6359                    && Resources.resourceHasPackage(mID)) {
6360                try {
6361                    String viewId = getResources().getResourceName(mID);
6362                    info.setViewIdResourceName(viewId);
6363                } catch (Resources.NotFoundException nfe) {
6364                    /* ignore */
6365                }
6366            }
6367        }
6368
6369        if (mLabelForId != View.NO_ID) {
6370            View rootView = getRootView();
6371            if (rootView == null) {
6372                rootView = this;
6373            }
6374            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6375            if (labeled != null) {
6376                info.setLabelFor(labeled);
6377            }
6378        }
6379
6380        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6381            View rootView = getRootView();
6382            if (rootView == null) {
6383                rootView = this;
6384            }
6385            View next = rootView.findViewInsideOutShouldExist(this,
6386                    mAccessibilityTraversalBeforeId);
6387            if (next != null && next.includeForAccessibility()) {
6388                info.setTraversalBefore(next);
6389            }
6390        }
6391
6392        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6393            View rootView = getRootView();
6394            if (rootView == null) {
6395                rootView = this;
6396            }
6397            View next = rootView.findViewInsideOutShouldExist(this,
6398                    mAccessibilityTraversalAfterId);
6399            if (next != null && next.includeForAccessibility()) {
6400                info.setTraversalAfter(next);
6401            }
6402        }
6403
6404        info.setVisibleToUser(isVisibleToUser());
6405
6406        info.setPackageName(mContext.getPackageName());
6407        info.setClassName(getAccessibilityClassName());
6408        info.setContentDescription(getContentDescription());
6409
6410        info.setEnabled(isEnabled());
6411        info.setClickable(isClickable());
6412        info.setFocusable(isFocusable());
6413        info.setFocused(isFocused());
6414        info.setAccessibilityFocused(isAccessibilityFocused());
6415        info.setSelected(isSelected());
6416        info.setLongClickable(isLongClickable());
6417        info.setContextClickable(isContextClickable());
6418        info.setLiveRegion(getAccessibilityLiveRegion());
6419
6420        // TODO: These make sense only if we are in an AdapterView but all
6421        // views can be selected. Maybe from accessibility perspective
6422        // we should report as selectable view in an AdapterView.
6423        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6424        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6425
6426        if (isFocusable()) {
6427            if (isFocused()) {
6428                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6429            } else {
6430                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6431            }
6432        }
6433
6434        if (!isAccessibilityFocused()) {
6435            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6436        } else {
6437            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6438        }
6439
6440        if (isClickable() && isEnabled()) {
6441            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6442        }
6443
6444        if (isLongClickable() && isEnabled()) {
6445            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6446        }
6447
6448        if (isContextClickable() && isEnabled()) {
6449            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6450        }
6451
6452        CharSequence text = getIterableTextForAccessibility();
6453        if (text != null && text.length() > 0) {
6454            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6455
6456            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6457            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6458            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6459            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6460                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6461                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6462        }
6463
6464        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6465    }
6466
6467    private View findLabelForView(View view, int labeledId) {
6468        if (mMatchLabelForPredicate == null) {
6469            mMatchLabelForPredicate = new MatchLabelForPredicate();
6470        }
6471        mMatchLabelForPredicate.mLabeledId = labeledId;
6472        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6473    }
6474
6475    /**
6476     * Computes whether this view is visible to the user. Such a view is
6477     * attached, visible, all its predecessors are visible, it is not clipped
6478     * entirely by its predecessors, and has an alpha greater than zero.
6479     *
6480     * @return Whether the view is visible on the screen.
6481     *
6482     * @hide
6483     */
6484    protected boolean isVisibleToUser() {
6485        return isVisibleToUser(null);
6486    }
6487
6488    /**
6489     * Computes whether the given portion of this view is visible to the user.
6490     * Such a view is attached, visible, all its predecessors are visible,
6491     * has an alpha greater than zero, and the specified portion is not
6492     * clipped entirely by its predecessors.
6493     *
6494     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6495     *                    <code>null</code>, and the entire view will be tested in this case.
6496     *                    When <code>true</code> is returned by the function, the actual visible
6497     *                    region will be stored in this parameter; that is, if boundInView is fully
6498     *                    contained within the view, no modification will be made, otherwise regions
6499     *                    outside of the visible area of the view will be clipped.
6500     *
6501     * @return Whether the specified portion of the view is visible on the screen.
6502     *
6503     * @hide
6504     */
6505    protected boolean isVisibleToUser(Rect boundInView) {
6506        if (mAttachInfo != null) {
6507            // Attached to invisible window means this view is not visible.
6508            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
6509                return false;
6510            }
6511            // An invisible predecessor or one with alpha zero means
6512            // that this view is not visible to the user.
6513            Object current = this;
6514            while (current instanceof View) {
6515                View view = (View) current;
6516                // We have attach info so this view is attached and there is no
6517                // need to check whether we reach to ViewRootImpl on the way up.
6518                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
6519                        view.getVisibility() != VISIBLE) {
6520                    return false;
6521                }
6522                current = view.mParent;
6523            }
6524            // Check if the view is entirely covered by its predecessors.
6525            Rect visibleRect = mAttachInfo.mTmpInvalRect;
6526            Point offset = mAttachInfo.mPoint;
6527            if (!getGlobalVisibleRect(visibleRect, offset)) {
6528                return false;
6529            }
6530            // Check if the visible portion intersects the rectangle of interest.
6531            if (boundInView != null) {
6532                visibleRect.offset(-offset.x, -offset.y);
6533                return boundInView.intersect(visibleRect);
6534            }
6535            return true;
6536        }
6537        return false;
6538    }
6539
6540    /**
6541     * Returns the delegate for implementing accessibility support via
6542     * composition. For more details see {@link AccessibilityDelegate}.
6543     *
6544     * @return The delegate, or null if none set.
6545     *
6546     * @hide
6547     */
6548    public AccessibilityDelegate getAccessibilityDelegate() {
6549        return mAccessibilityDelegate;
6550    }
6551
6552    /**
6553     * Sets a delegate for implementing accessibility support via composition as
6554     * opposed to inheritance. The delegate's primary use is for implementing
6555     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
6556     *
6557     * @param delegate The delegate instance.
6558     *
6559     * @see AccessibilityDelegate
6560     */
6561    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
6562        mAccessibilityDelegate = delegate;
6563    }
6564
6565    /**
6566     * Gets the provider for managing a virtual view hierarchy rooted at this View
6567     * and reported to {@link android.accessibilityservice.AccessibilityService}s
6568     * that explore the window content.
6569     * <p>
6570     * If this method returns an instance, this instance is responsible for managing
6571     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
6572     * View including the one representing the View itself. Similarly the returned
6573     * instance is responsible for performing accessibility actions on any virtual
6574     * view or the root view itself.
6575     * </p>
6576     * <p>
6577     * If an {@link AccessibilityDelegate} has been specified via calling
6578     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6579     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
6580     * is responsible for handling this call.
6581     * </p>
6582     *
6583     * @return The provider.
6584     *
6585     * @see AccessibilityNodeProvider
6586     */
6587    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6588        if (mAccessibilityDelegate != null) {
6589            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6590        } else {
6591            return null;
6592        }
6593    }
6594
6595    /**
6596     * Gets the unique identifier of this view on the screen for accessibility purposes.
6597     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6598     *
6599     * @return The view accessibility id.
6600     *
6601     * @hide
6602     */
6603    public int getAccessibilityViewId() {
6604        if (mAccessibilityViewId == NO_ID) {
6605            mAccessibilityViewId = sNextAccessibilityViewId++;
6606        }
6607        return mAccessibilityViewId;
6608    }
6609
6610    /**
6611     * Gets the unique identifier of the window in which this View reseides.
6612     *
6613     * @return The window accessibility id.
6614     *
6615     * @hide
6616     */
6617    public int getAccessibilityWindowId() {
6618        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6619                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6620    }
6621
6622    /**
6623     * Gets the {@link View} description. It briefly describes the view and is
6624     * primarily used for accessibility support. Set this property to enable
6625     * better accessibility support for your application. This is especially
6626     * true for views that do not have textual representation (For example,
6627     * ImageButton).
6628     *
6629     * @return The content description.
6630     *
6631     * @attr ref android.R.styleable#View_contentDescription
6632     */
6633    @ViewDebug.ExportedProperty(category = "accessibility")
6634    public CharSequence getContentDescription() {
6635        return mContentDescription;
6636    }
6637
6638    /**
6639     * Sets the {@link View} description. It briefly describes the view and is
6640     * primarily used for accessibility support. Set this property to enable
6641     * better accessibility support for your application. This is especially
6642     * true for views that do not have textual representation (For example,
6643     * ImageButton).
6644     *
6645     * @param contentDescription The content description.
6646     *
6647     * @attr ref android.R.styleable#View_contentDescription
6648     */
6649    @RemotableViewMethod
6650    public void setContentDescription(CharSequence contentDescription) {
6651        if (mContentDescription == null) {
6652            if (contentDescription == null) {
6653                return;
6654            }
6655        } else if (mContentDescription.equals(contentDescription)) {
6656            return;
6657        }
6658        mContentDescription = contentDescription;
6659        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6660        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6661            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6662            notifySubtreeAccessibilityStateChangedIfNeeded();
6663        } else {
6664            notifyViewAccessibilityStateChangedIfNeeded(
6665                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6666        }
6667    }
6668
6669    /**
6670     * Sets the id of a view before which this one is visited in accessibility traversal.
6671     * A screen-reader must visit the content of this view before the content of the one
6672     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6673     * will traverse the entire content of B before traversing the entire content of A,
6674     * regardles of what traversal strategy it is using.
6675     * <p>
6676     * Views that do not have specified before/after relationships are traversed in order
6677     * determined by the screen-reader.
6678     * </p>
6679     * <p>
6680     * Setting that this view is before a view that is not important for accessibility
6681     * or if this view is not important for accessibility will have no effect as the
6682     * screen-reader is not aware of unimportant views.
6683     * </p>
6684     *
6685     * @param beforeId The id of a view this one precedes in accessibility traversal.
6686     *
6687     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6688     *
6689     * @see #setImportantForAccessibility(int)
6690     */
6691    @RemotableViewMethod
6692    public void setAccessibilityTraversalBefore(int beforeId) {
6693        if (mAccessibilityTraversalBeforeId == beforeId) {
6694            return;
6695        }
6696        mAccessibilityTraversalBeforeId = beforeId;
6697        notifyViewAccessibilityStateChangedIfNeeded(
6698                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6699    }
6700
6701    /**
6702     * Gets the id of a view before which this one is visited in accessibility traversal.
6703     *
6704     * @return The id of a view this one precedes in accessibility traversal if
6705     *         specified, otherwise {@link #NO_ID}.
6706     *
6707     * @see #setAccessibilityTraversalBefore(int)
6708     */
6709    public int getAccessibilityTraversalBefore() {
6710        return mAccessibilityTraversalBeforeId;
6711    }
6712
6713    /**
6714     * Sets the id of a view after which this one is visited in accessibility traversal.
6715     * A screen-reader must visit the content of the other view before the content of this
6716     * one. For example, if view B is set to be after view A, then a screen-reader
6717     * will traverse the entire content of A before traversing the entire content of B,
6718     * regardles of what traversal strategy it is using.
6719     * <p>
6720     * Views that do not have specified before/after relationships are traversed in order
6721     * determined by the screen-reader.
6722     * </p>
6723     * <p>
6724     * Setting that this view is after a view that is not important for accessibility
6725     * or if this view is not important for accessibility will have no effect as the
6726     * screen-reader is not aware of unimportant views.
6727     * </p>
6728     *
6729     * @param afterId The id of a view this one succedees in accessibility traversal.
6730     *
6731     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6732     *
6733     * @see #setImportantForAccessibility(int)
6734     */
6735    @RemotableViewMethod
6736    public void setAccessibilityTraversalAfter(int afterId) {
6737        if (mAccessibilityTraversalAfterId == afterId) {
6738            return;
6739        }
6740        mAccessibilityTraversalAfterId = afterId;
6741        notifyViewAccessibilityStateChangedIfNeeded(
6742                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6743    }
6744
6745    /**
6746     * Gets the id of a view after which this one is visited in accessibility traversal.
6747     *
6748     * @return The id of a view this one succeedes in accessibility traversal if
6749     *         specified, otherwise {@link #NO_ID}.
6750     *
6751     * @see #setAccessibilityTraversalAfter(int)
6752     */
6753    public int getAccessibilityTraversalAfter() {
6754        return mAccessibilityTraversalAfterId;
6755    }
6756
6757    /**
6758     * Gets the id of a view for which this view serves as a label for
6759     * accessibility purposes.
6760     *
6761     * @return The labeled view id.
6762     */
6763    @ViewDebug.ExportedProperty(category = "accessibility")
6764    public int getLabelFor() {
6765        return mLabelForId;
6766    }
6767
6768    /**
6769     * Sets the id of a view for which this view serves as a label for
6770     * accessibility purposes.
6771     *
6772     * @param id The labeled view id.
6773     */
6774    @RemotableViewMethod
6775    public void setLabelFor(@IdRes int id) {
6776        if (mLabelForId == id) {
6777            return;
6778        }
6779        mLabelForId = id;
6780        if (mLabelForId != View.NO_ID
6781                && mID == View.NO_ID) {
6782            mID = generateViewId();
6783        }
6784        notifyViewAccessibilityStateChangedIfNeeded(
6785                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6786    }
6787
6788    /**
6789     * Invoked whenever this view loses focus, either by losing window focus or by losing
6790     * focus within its window. This method can be used to clear any state tied to the
6791     * focus. For instance, if a button is held pressed with the trackball and the window
6792     * loses focus, this method can be used to cancel the press.
6793     *
6794     * Subclasses of View overriding this method should always call super.onFocusLost().
6795     *
6796     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6797     * @see #onWindowFocusChanged(boolean)
6798     *
6799     * @hide pending API council approval
6800     */
6801    @CallSuper
6802    protected void onFocusLost() {
6803        resetPressedState();
6804    }
6805
6806    private void resetPressedState() {
6807        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6808            return;
6809        }
6810
6811        if (isPressed()) {
6812            setPressed(false);
6813
6814            if (!mHasPerformedLongPress) {
6815                removeLongPressCallback();
6816            }
6817        }
6818    }
6819
6820    /**
6821     * Returns true if this view has focus
6822     *
6823     * @return True if this view has focus, false otherwise.
6824     */
6825    @ViewDebug.ExportedProperty(category = "focus")
6826    public boolean isFocused() {
6827        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6828    }
6829
6830    /**
6831     * Find the view in the hierarchy rooted at this view that currently has
6832     * focus.
6833     *
6834     * @return The view that currently has focus, or null if no focused view can
6835     *         be found.
6836     */
6837    public View findFocus() {
6838        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6839    }
6840
6841    /**
6842     * Indicates whether this view is one of the set of scrollable containers in
6843     * its window.
6844     *
6845     * @return whether this view is one of the set of scrollable containers in
6846     * its window
6847     *
6848     * @attr ref android.R.styleable#View_isScrollContainer
6849     */
6850    public boolean isScrollContainer() {
6851        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6852    }
6853
6854    /**
6855     * Change whether this view is one of the set of scrollable containers in
6856     * its window.  This will be used to determine whether the window can
6857     * resize or must pan when a soft input area is open -- scrollable
6858     * containers allow the window to use resize mode since the container
6859     * will appropriately shrink.
6860     *
6861     * @attr ref android.R.styleable#View_isScrollContainer
6862     */
6863    public void setScrollContainer(boolean isScrollContainer) {
6864        if (isScrollContainer) {
6865            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6866                mAttachInfo.mScrollContainers.add(this);
6867                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6868            }
6869            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6870        } else {
6871            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6872                mAttachInfo.mScrollContainers.remove(this);
6873            }
6874            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6875        }
6876    }
6877
6878    /**
6879     * Returns the quality of the drawing cache.
6880     *
6881     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6882     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6883     *
6884     * @see #setDrawingCacheQuality(int)
6885     * @see #setDrawingCacheEnabled(boolean)
6886     * @see #isDrawingCacheEnabled()
6887     *
6888     * @attr ref android.R.styleable#View_drawingCacheQuality
6889     */
6890    @DrawingCacheQuality
6891    public int getDrawingCacheQuality() {
6892        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6893    }
6894
6895    /**
6896     * Set the drawing cache quality of this view. This value is used only when the
6897     * drawing cache is enabled
6898     *
6899     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6900     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6901     *
6902     * @see #getDrawingCacheQuality()
6903     * @see #setDrawingCacheEnabled(boolean)
6904     * @see #isDrawingCacheEnabled()
6905     *
6906     * @attr ref android.R.styleable#View_drawingCacheQuality
6907     */
6908    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6909        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6910    }
6911
6912    /**
6913     * Returns whether the screen should remain on, corresponding to the current
6914     * value of {@link #KEEP_SCREEN_ON}.
6915     *
6916     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6917     *
6918     * @see #setKeepScreenOn(boolean)
6919     *
6920     * @attr ref android.R.styleable#View_keepScreenOn
6921     */
6922    public boolean getKeepScreenOn() {
6923        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6924    }
6925
6926    /**
6927     * Controls whether the screen should remain on, modifying the
6928     * value of {@link #KEEP_SCREEN_ON}.
6929     *
6930     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6931     *
6932     * @see #getKeepScreenOn()
6933     *
6934     * @attr ref android.R.styleable#View_keepScreenOn
6935     */
6936    public void setKeepScreenOn(boolean keepScreenOn) {
6937        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6938    }
6939
6940    /**
6941     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6942     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6943     *
6944     * @attr ref android.R.styleable#View_nextFocusLeft
6945     */
6946    public int getNextFocusLeftId() {
6947        return mNextFocusLeftId;
6948    }
6949
6950    /**
6951     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6952     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6953     * decide automatically.
6954     *
6955     * @attr ref android.R.styleable#View_nextFocusLeft
6956     */
6957    public void setNextFocusLeftId(int nextFocusLeftId) {
6958        mNextFocusLeftId = nextFocusLeftId;
6959    }
6960
6961    /**
6962     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6963     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6964     *
6965     * @attr ref android.R.styleable#View_nextFocusRight
6966     */
6967    public int getNextFocusRightId() {
6968        return mNextFocusRightId;
6969    }
6970
6971    /**
6972     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6973     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6974     * decide automatically.
6975     *
6976     * @attr ref android.R.styleable#View_nextFocusRight
6977     */
6978    public void setNextFocusRightId(int nextFocusRightId) {
6979        mNextFocusRightId = nextFocusRightId;
6980    }
6981
6982    /**
6983     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6984     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6985     *
6986     * @attr ref android.R.styleable#View_nextFocusUp
6987     */
6988    public int getNextFocusUpId() {
6989        return mNextFocusUpId;
6990    }
6991
6992    /**
6993     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6994     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6995     * decide automatically.
6996     *
6997     * @attr ref android.R.styleable#View_nextFocusUp
6998     */
6999    public void setNextFocusUpId(int nextFocusUpId) {
7000        mNextFocusUpId = nextFocusUpId;
7001    }
7002
7003    /**
7004     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7005     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7006     *
7007     * @attr ref android.R.styleable#View_nextFocusDown
7008     */
7009    public int getNextFocusDownId() {
7010        return mNextFocusDownId;
7011    }
7012
7013    /**
7014     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7015     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7016     * decide automatically.
7017     *
7018     * @attr ref android.R.styleable#View_nextFocusDown
7019     */
7020    public void setNextFocusDownId(int nextFocusDownId) {
7021        mNextFocusDownId = nextFocusDownId;
7022    }
7023
7024    /**
7025     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7026     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7027     *
7028     * @attr ref android.R.styleable#View_nextFocusForward
7029     */
7030    public int getNextFocusForwardId() {
7031        return mNextFocusForwardId;
7032    }
7033
7034    /**
7035     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7036     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7037     * decide automatically.
7038     *
7039     * @attr ref android.R.styleable#View_nextFocusForward
7040     */
7041    public void setNextFocusForwardId(int nextFocusForwardId) {
7042        mNextFocusForwardId = nextFocusForwardId;
7043    }
7044
7045    /**
7046     * Returns the visibility of this view and all of its ancestors
7047     *
7048     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7049     */
7050    public boolean isShown() {
7051        View current = this;
7052        //noinspection ConstantConditions
7053        do {
7054            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7055                return false;
7056            }
7057            ViewParent parent = current.mParent;
7058            if (parent == null) {
7059                return false; // We are not attached to the view root
7060            }
7061            if (!(parent instanceof View)) {
7062                return true;
7063            }
7064            current = (View) parent;
7065        } while (current != null);
7066
7067        return false;
7068    }
7069
7070    /**
7071     * Called by the view hierarchy when the content insets for a window have
7072     * changed, to allow it to adjust its content to fit within those windows.
7073     * The content insets tell you the space that the status bar, input method,
7074     * and other system windows infringe on the application's window.
7075     *
7076     * <p>You do not normally need to deal with this function, since the default
7077     * window decoration given to applications takes care of applying it to the
7078     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7079     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7080     * and your content can be placed under those system elements.  You can then
7081     * use this method within your view hierarchy if you have parts of your UI
7082     * which you would like to ensure are not being covered.
7083     *
7084     * <p>The default implementation of this method simply applies the content
7085     * insets to the view's padding, consuming that content (modifying the
7086     * insets to be 0), and returning true.  This behavior is off by default, but can
7087     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7088     *
7089     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7090     * insets object is propagated down the hierarchy, so any changes made to it will
7091     * be seen by all following views (including potentially ones above in
7092     * the hierarchy since this is a depth-first traversal).  The first view
7093     * that returns true will abort the entire traversal.
7094     *
7095     * <p>The default implementation works well for a situation where it is
7096     * used with a container that covers the entire window, allowing it to
7097     * apply the appropriate insets to its content on all edges.  If you need
7098     * a more complicated layout (such as two different views fitting system
7099     * windows, one on the top of the window, and one on the bottom),
7100     * you can override the method and handle the insets however you would like.
7101     * Note that the insets provided by the framework are always relative to the
7102     * far edges of the window, not accounting for the location of the called view
7103     * within that window.  (In fact when this method is called you do not yet know
7104     * where the layout will place the view, as it is done before layout happens.)
7105     *
7106     * <p>Note: unlike many View methods, there is no dispatch phase to this
7107     * call.  If you are overriding it in a ViewGroup and want to allow the
7108     * call to continue to your children, you must be sure to call the super
7109     * implementation.
7110     *
7111     * <p>Here is a sample layout that makes use of fitting system windows
7112     * to have controls for a video view placed inside of the window decorations
7113     * that it hides and shows.  This can be used with code like the second
7114     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7115     *
7116     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7117     *
7118     * @param insets Current content insets of the window.  Prior to
7119     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7120     * the insets or else you and Android will be unhappy.
7121     *
7122     * @return {@code true} if this view applied the insets and it should not
7123     * continue propagating further down the hierarchy, {@code false} otherwise.
7124     * @see #getFitsSystemWindows()
7125     * @see #setFitsSystemWindows(boolean)
7126     * @see #setSystemUiVisibility(int)
7127     *
7128     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7129     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7130     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7131     * to implement handling their own insets.
7132     */
7133    protected boolean fitSystemWindows(Rect insets) {
7134        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7135            if (insets == null) {
7136                // Null insets by definition have already been consumed.
7137                // This call cannot apply insets since there are none to apply,
7138                // so return false.
7139                return false;
7140            }
7141            // If we're not in the process of dispatching the newer apply insets call,
7142            // that means we're not in the compatibility path. Dispatch into the newer
7143            // apply insets path and take things from there.
7144            try {
7145                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7146                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7147            } finally {
7148                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7149            }
7150        } else {
7151            // We're being called from the newer apply insets path.
7152            // Perform the standard fallback behavior.
7153            return fitSystemWindowsInt(insets);
7154        }
7155    }
7156
7157    private boolean fitSystemWindowsInt(Rect insets) {
7158        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7159            mUserPaddingStart = UNDEFINED_PADDING;
7160            mUserPaddingEnd = UNDEFINED_PADDING;
7161            Rect localInsets = sThreadLocal.get();
7162            if (localInsets == null) {
7163                localInsets = new Rect();
7164                sThreadLocal.set(localInsets);
7165            }
7166            boolean res = computeFitSystemWindows(insets, localInsets);
7167            mUserPaddingLeftInitial = localInsets.left;
7168            mUserPaddingRightInitial = localInsets.right;
7169            internalSetPadding(localInsets.left, localInsets.top,
7170                    localInsets.right, localInsets.bottom);
7171            return res;
7172        }
7173        return false;
7174    }
7175
7176    /**
7177     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7178     *
7179     * <p>This method should be overridden by views that wish to apply a policy different from or
7180     * in addition to the default behavior. Clients that wish to force a view subtree
7181     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7182     *
7183     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7184     * it will be called during dispatch instead of this method. The listener may optionally
7185     * call this method from its own implementation if it wishes to apply the view's default
7186     * insets policy in addition to its own.</p>
7187     *
7188     * <p>Implementations of this method should either return the insets parameter unchanged
7189     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7190     * that this view applied itself. This allows new inset types added in future platform
7191     * versions to pass through existing implementations unchanged without being erroneously
7192     * consumed.</p>
7193     *
7194     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7195     * property is set then the view will consume the system window insets and apply them
7196     * as padding for the view.</p>
7197     *
7198     * @param insets Insets to apply
7199     * @return The supplied insets with any applied insets consumed
7200     */
7201    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7202        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7203            // We weren't called from within a direct call to fitSystemWindows,
7204            // call into it as a fallback in case we're in a class that overrides it
7205            // and has logic to perform.
7206            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7207                return insets.consumeSystemWindowInsets();
7208            }
7209        } else {
7210            // We were called from within a direct call to fitSystemWindows.
7211            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7212                return insets.consumeSystemWindowInsets();
7213            }
7214        }
7215        return insets;
7216    }
7217
7218    /**
7219     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7220     * window insets to this view. The listener's
7221     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7222     * method will be called instead of the view's
7223     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7224     *
7225     * @param listener Listener to set
7226     *
7227     * @see #onApplyWindowInsets(WindowInsets)
7228     */
7229    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7230        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7231    }
7232
7233    /**
7234     * Request to apply the given window insets to this view or another view in its subtree.
7235     *
7236     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7237     * obscured by window decorations or overlays. This can include the status and navigation bars,
7238     * action bars, input methods and more. New inset categories may be added in the future.
7239     * The method returns the insets provided minus any that were applied by this view or its
7240     * children.</p>
7241     *
7242     * <p>Clients wishing to provide custom behavior should override the
7243     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7244     * {@link OnApplyWindowInsetsListener} via the
7245     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7246     * method.</p>
7247     *
7248     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7249     * </p>
7250     *
7251     * @param insets Insets to apply
7252     * @return The provided insets minus the insets that were consumed
7253     */
7254    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7255        try {
7256            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7257            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7258                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7259            } else {
7260                return onApplyWindowInsets(insets);
7261            }
7262        } finally {
7263            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7264        }
7265    }
7266
7267    /**
7268     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7269     * only available if the view is attached.
7270     *
7271     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7272     */
7273    public WindowInsets getRootWindowInsets() {
7274        if (mAttachInfo != null) {
7275            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7276        }
7277        return null;
7278    }
7279
7280    /**
7281     * @hide Compute the insets that should be consumed by this view and the ones
7282     * that should propagate to those under it.
7283     */
7284    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7285        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7286                || mAttachInfo == null
7287                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7288                        && !mAttachInfo.mOverscanRequested)) {
7289            outLocalInsets.set(inoutInsets);
7290            inoutInsets.set(0, 0, 0, 0);
7291            return true;
7292        } else {
7293            // The application wants to take care of fitting system window for
7294            // the content...  however we still need to take care of any overscan here.
7295            final Rect overscan = mAttachInfo.mOverscanInsets;
7296            outLocalInsets.set(overscan);
7297            inoutInsets.left -= overscan.left;
7298            inoutInsets.top -= overscan.top;
7299            inoutInsets.right -= overscan.right;
7300            inoutInsets.bottom -= overscan.bottom;
7301            return false;
7302        }
7303    }
7304
7305    /**
7306     * Compute insets that should be consumed by this view and the ones that should propagate
7307     * to those under it.
7308     *
7309     * @param in Insets currently being processed by this View, likely received as a parameter
7310     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7311     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7312     *                       by this view
7313     * @return Insets that should be passed along to views under this one
7314     */
7315    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7316        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7317                || mAttachInfo == null
7318                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7319            outLocalInsets.set(in.getSystemWindowInsets());
7320            return in.consumeSystemWindowInsets();
7321        } else {
7322            outLocalInsets.set(0, 0, 0, 0);
7323            return in;
7324        }
7325    }
7326
7327    /**
7328     * Sets whether or not this view should account for system screen decorations
7329     * such as the status bar and inset its content; that is, controlling whether
7330     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7331     * executed.  See that method for more details.
7332     *
7333     * <p>Note that if you are providing your own implementation of
7334     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7335     * flag to true -- your implementation will be overriding the default
7336     * implementation that checks this flag.
7337     *
7338     * @param fitSystemWindows If true, then the default implementation of
7339     * {@link #fitSystemWindows(Rect)} will be executed.
7340     *
7341     * @attr ref android.R.styleable#View_fitsSystemWindows
7342     * @see #getFitsSystemWindows()
7343     * @see #fitSystemWindows(Rect)
7344     * @see #setSystemUiVisibility(int)
7345     */
7346    public void setFitsSystemWindows(boolean fitSystemWindows) {
7347        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7348    }
7349
7350    /**
7351     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7352     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7353     * will be executed.
7354     *
7355     * @return {@code true} if the default implementation of
7356     * {@link #fitSystemWindows(Rect)} will be executed.
7357     *
7358     * @attr ref android.R.styleable#View_fitsSystemWindows
7359     * @see #setFitsSystemWindows(boolean)
7360     * @see #fitSystemWindows(Rect)
7361     * @see #setSystemUiVisibility(int)
7362     */
7363    @ViewDebug.ExportedProperty
7364    public boolean getFitsSystemWindows() {
7365        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7366    }
7367
7368    /** @hide */
7369    public boolean fitsSystemWindows() {
7370        return getFitsSystemWindows();
7371    }
7372
7373    /**
7374     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7375     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7376     */
7377    public void requestFitSystemWindows() {
7378        if (mParent != null) {
7379            mParent.requestFitSystemWindows();
7380        }
7381    }
7382
7383    /**
7384     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7385     */
7386    public void requestApplyInsets() {
7387        requestFitSystemWindows();
7388    }
7389
7390    /**
7391     * For use by PhoneWindow to make its own system window fitting optional.
7392     * @hide
7393     */
7394    public void makeOptionalFitsSystemWindows() {
7395        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7396    }
7397
7398    /**
7399     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7400     * treat them as such.
7401     * @hide
7402     */
7403    public void getOutsets(Rect outOutsetRect) {
7404        if (mAttachInfo != null) {
7405            outOutsetRect.set(mAttachInfo.mOutsets);
7406        } else {
7407            outOutsetRect.setEmpty();
7408        }
7409    }
7410
7411    /**
7412     * Returns the visibility status for this view.
7413     *
7414     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7415     * @attr ref android.R.styleable#View_visibility
7416     */
7417    @ViewDebug.ExportedProperty(mapping = {
7418        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7419        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7420        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7421    })
7422    @Visibility
7423    public int getVisibility() {
7424        return mViewFlags & VISIBILITY_MASK;
7425    }
7426
7427    /**
7428     * Set the enabled state of this view.
7429     *
7430     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7431     * @attr ref android.R.styleable#View_visibility
7432     */
7433    @RemotableViewMethod
7434    public void setVisibility(@Visibility int visibility) {
7435        setFlags(visibility, VISIBILITY_MASK);
7436    }
7437
7438    /**
7439     * Returns the enabled status for this view. The interpretation of the
7440     * enabled state varies by subclass.
7441     *
7442     * @return True if this view is enabled, false otherwise.
7443     */
7444    @ViewDebug.ExportedProperty
7445    public boolean isEnabled() {
7446        return (mViewFlags & ENABLED_MASK) == ENABLED;
7447    }
7448
7449    /**
7450     * Set the enabled state of this view. The interpretation of the enabled
7451     * state varies by subclass.
7452     *
7453     * @param enabled True if this view is enabled, false otherwise.
7454     */
7455    @RemotableViewMethod
7456    public void setEnabled(boolean enabled) {
7457        if (enabled == isEnabled()) return;
7458
7459        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7460
7461        /*
7462         * The View most likely has to change its appearance, so refresh
7463         * the drawable state.
7464         */
7465        refreshDrawableState();
7466
7467        // Invalidate too, since the default behavior for views is to be
7468        // be drawn at 50% alpha rather than to change the drawable.
7469        invalidate(true);
7470
7471        if (!enabled) {
7472            cancelPendingInputEvents();
7473        }
7474    }
7475
7476    /**
7477     * Set whether this view can receive the focus.
7478     *
7479     * Setting this to false will also ensure that this view is not focusable
7480     * in touch mode.
7481     *
7482     * @param focusable If true, this view can receive the focus.
7483     *
7484     * @see #setFocusableInTouchMode(boolean)
7485     * @attr ref android.R.styleable#View_focusable
7486     */
7487    public void setFocusable(boolean focusable) {
7488        if (!focusable) {
7489            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
7490        }
7491        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
7492    }
7493
7494    /**
7495     * Set whether this view can receive focus while in touch mode.
7496     *
7497     * Setting this to true will also ensure that this view is focusable.
7498     *
7499     * @param focusableInTouchMode If true, this view can receive the focus while
7500     *   in touch mode.
7501     *
7502     * @see #setFocusable(boolean)
7503     * @attr ref android.R.styleable#View_focusableInTouchMode
7504     */
7505    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
7506        // Focusable in touch mode should always be set before the focusable flag
7507        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
7508        // which, in touch mode, will not successfully request focus on this view
7509        // because the focusable in touch mode flag is not set
7510        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
7511        if (focusableInTouchMode) {
7512            setFlags(FOCUSABLE, FOCUSABLE_MASK);
7513        }
7514    }
7515
7516    /**
7517     * Set whether this view should have sound effects enabled for events such as
7518     * clicking and touching.
7519     *
7520     * <p>You may wish to disable sound effects for a view if you already play sounds,
7521     * for instance, a dial key that plays dtmf tones.
7522     *
7523     * @param soundEffectsEnabled whether sound effects are enabled for this view.
7524     * @see #isSoundEffectsEnabled()
7525     * @see #playSoundEffect(int)
7526     * @attr ref android.R.styleable#View_soundEffectsEnabled
7527     */
7528    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
7529        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
7530    }
7531
7532    /**
7533     * @return whether this view should have sound effects enabled for events such as
7534     *     clicking and touching.
7535     *
7536     * @see #setSoundEffectsEnabled(boolean)
7537     * @see #playSoundEffect(int)
7538     * @attr ref android.R.styleable#View_soundEffectsEnabled
7539     */
7540    @ViewDebug.ExportedProperty
7541    public boolean isSoundEffectsEnabled() {
7542        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
7543    }
7544
7545    /**
7546     * Set whether this view should have haptic feedback for events such as
7547     * long presses.
7548     *
7549     * <p>You may wish to disable haptic feedback if your view already controls
7550     * its own haptic feedback.
7551     *
7552     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
7553     * @see #isHapticFeedbackEnabled()
7554     * @see #performHapticFeedback(int)
7555     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7556     */
7557    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
7558        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
7559    }
7560
7561    /**
7562     * @return whether this view should have haptic feedback enabled for events
7563     * long presses.
7564     *
7565     * @see #setHapticFeedbackEnabled(boolean)
7566     * @see #performHapticFeedback(int)
7567     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7568     */
7569    @ViewDebug.ExportedProperty
7570    public boolean isHapticFeedbackEnabled() {
7571        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
7572    }
7573
7574    /**
7575     * Returns the layout direction for this view.
7576     *
7577     * @return One of {@link #LAYOUT_DIRECTION_LTR},
7578     *   {@link #LAYOUT_DIRECTION_RTL},
7579     *   {@link #LAYOUT_DIRECTION_INHERIT} or
7580     *   {@link #LAYOUT_DIRECTION_LOCALE}.
7581     *
7582     * @attr ref android.R.styleable#View_layoutDirection
7583     *
7584     * @hide
7585     */
7586    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7587        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
7588        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
7589        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
7590        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
7591    })
7592    @LayoutDir
7593    public int getRawLayoutDirection() {
7594        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
7595    }
7596
7597    /**
7598     * Set the layout direction for this view. This will propagate a reset of layout direction
7599     * resolution to the view's children and resolve layout direction for this view.
7600     *
7601     * @param layoutDirection the layout direction to set. Should be one of:
7602     *
7603     * {@link #LAYOUT_DIRECTION_LTR},
7604     * {@link #LAYOUT_DIRECTION_RTL},
7605     * {@link #LAYOUT_DIRECTION_INHERIT},
7606     * {@link #LAYOUT_DIRECTION_LOCALE}.
7607     *
7608     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7609     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7610     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7611     *
7612     * @attr ref android.R.styleable#View_layoutDirection
7613     */
7614    @RemotableViewMethod
7615    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7616        if (getRawLayoutDirection() != layoutDirection) {
7617            // Reset the current layout direction and the resolved one
7618            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7619            resetRtlProperties();
7620            // Set the new layout direction (filtered)
7621            mPrivateFlags2 |=
7622                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7623            // We need to resolve all RTL properties as they all depend on layout direction
7624            resolveRtlPropertiesIfNeeded();
7625            requestLayout();
7626            invalidate(true);
7627        }
7628    }
7629
7630    /**
7631     * Returns the resolved layout direction for this view.
7632     *
7633     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7634     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7635     *
7636     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7637     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7638     *
7639     * @attr ref android.R.styleable#View_layoutDirection
7640     */
7641    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7642        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7643        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7644    })
7645    @ResolvedLayoutDir
7646    public int getLayoutDirection() {
7647        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7648        if (targetSdkVersion < JELLY_BEAN_MR1) {
7649            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7650            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7651        }
7652        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7653                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7654    }
7655
7656    /**
7657     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7658     * layout attribute and/or the inherited value from the parent
7659     *
7660     * @return true if the layout is right-to-left.
7661     *
7662     * @hide
7663     */
7664    @ViewDebug.ExportedProperty(category = "layout")
7665    public boolean isLayoutRtl() {
7666        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7667    }
7668
7669    /**
7670     * Indicates whether the view is currently tracking transient state that the
7671     * app should not need to concern itself with saving and restoring, but that
7672     * the framework should take special note to preserve when possible.
7673     *
7674     * <p>A view with transient state cannot be trivially rebound from an external
7675     * data source, such as an adapter binding item views in a list. This may be
7676     * because the view is performing an animation, tracking user selection
7677     * of content, or similar.</p>
7678     *
7679     * @return true if the view has transient state
7680     */
7681    @ViewDebug.ExportedProperty(category = "layout")
7682    public boolean hasTransientState() {
7683        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7684    }
7685
7686    /**
7687     * Set whether this view is currently tracking transient state that the
7688     * framework should attempt to preserve when possible. This flag is reference counted,
7689     * so every call to setHasTransientState(true) should be paired with a later call
7690     * to setHasTransientState(false).
7691     *
7692     * <p>A view with transient state cannot be trivially rebound from an external
7693     * data source, such as an adapter binding item views in a list. This may be
7694     * because the view is performing an animation, tracking user selection
7695     * of content, or similar.</p>
7696     *
7697     * @param hasTransientState true if this view has transient state
7698     */
7699    public void setHasTransientState(boolean hasTransientState) {
7700        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7701                mTransientStateCount - 1;
7702        if (mTransientStateCount < 0) {
7703            mTransientStateCount = 0;
7704            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7705                    "unmatched pair of setHasTransientState calls");
7706        } else if ((hasTransientState && mTransientStateCount == 1) ||
7707                (!hasTransientState && mTransientStateCount == 0)) {
7708            // update flag if we've just incremented up from 0 or decremented down to 0
7709            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7710                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7711            if (mParent != null) {
7712                try {
7713                    mParent.childHasTransientStateChanged(this, hasTransientState);
7714                } catch (AbstractMethodError e) {
7715                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7716                            " does not fully implement ViewParent", e);
7717                }
7718            }
7719        }
7720    }
7721
7722    /**
7723     * Returns true if this view is currently attached to a window.
7724     */
7725    public boolean isAttachedToWindow() {
7726        return mAttachInfo != null;
7727    }
7728
7729    /**
7730     * Returns true if this view has been through at least one layout since it
7731     * was last attached to or detached from a window.
7732     */
7733    public boolean isLaidOut() {
7734        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7735    }
7736
7737    /**
7738     * If this view doesn't do any drawing on its own, set this flag to
7739     * allow further optimizations. By default, this flag is not set on
7740     * View, but could be set on some View subclasses such as ViewGroup.
7741     *
7742     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7743     * you should clear this flag.
7744     *
7745     * @param willNotDraw whether or not this View draw on its own
7746     */
7747    public void setWillNotDraw(boolean willNotDraw) {
7748        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7749    }
7750
7751    /**
7752     * Returns whether or not this View draws on its own.
7753     *
7754     * @return true if this view has nothing to draw, false otherwise
7755     */
7756    @ViewDebug.ExportedProperty(category = "drawing")
7757    public boolean willNotDraw() {
7758        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7759    }
7760
7761    /**
7762     * When a View's drawing cache is enabled, drawing is redirected to an
7763     * offscreen bitmap. Some views, like an ImageView, must be able to
7764     * bypass this mechanism if they already draw a single bitmap, to avoid
7765     * unnecessary usage of the memory.
7766     *
7767     * @param willNotCacheDrawing true if this view does not cache its
7768     *        drawing, false otherwise
7769     */
7770    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7771        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7772    }
7773
7774    /**
7775     * Returns whether or not this View can cache its drawing or not.
7776     *
7777     * @return true if this view does not cache its drawing, false otherwise
7778     */
7779    @ViewDebug.ExportedProperty(category = "drawing")
7780    public boolean willNotCacheDrawing() {
7781        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7782    }
7783
7784    /**
7785     * Indicates whether this view reacts to click events or not.
7786     *
7787     * @return true if the view is clickable, false otherwise
7788     *
7789     * @see #setClickable(boolean)
7790     * @attr ref android.R.styleable#View_clickable
7791     */
7792    @ViewDebug.ExportedProperty
7793    public boolean isClickable() {
7794        return (mViewFlags & CLICKABLE) == CLICKABLE;
7795    }
7796
7797    /**
7798     * Enables or disables click events for this view. When a view
7799     * is clickable it will change its state to "pressed" on every click.
7800     * Subclasses should set the view clickable to visually react to
7801     * user's clicks.
7802     *
7803     * @param clickable true to make the view clickable, false otherwise
7804     *
7805     * @see #isClickable()
7806     * @attr ref android.R.styleable#View_clickable
7807     */
7808    public void setClickable(boolean clickable) {
7809        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7810    }
7811
7812    /**
7813     * Indicates whether this view reacts to long click events or not.
7814     *
7815     * @return true if the view is long clickable, false otherwise
7816     *
7817     * @see #setLongClickable(boolean)
7818     * @attr ref android.R.styleable#View_longClickable
7819     */
7820    public boolean isLongClickable() {
7821        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7822    }
7823
7824    /**
7825     * Enables or disables long click events for this view. When a view is long
7826     * clickable it reacts to the user holding down the button for a longer
7827     * duration than a tap. This event can either launch the listener or a
7828     * context menu.
7829     *
7830     * @param longClickable true to make the view long clickable, false otherwise
7831     * @see #isLongClickable()
7832     * @attr ref android.R.styleable#View_longClickable
7833     */
7834    public void setLongClickable(boolean longClickable) {
7835        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7836    }
7837
7838    /**
7839     * Indicates whether this view reacts to context clicks or not.
7840     *
7841     * @return true if the view is context clickable, false otherwise
7842     * @see #setContextClickable(boolean)
7843     * @attr ref android.R.styleable#View_contextClickable
7844     */
7845    public boolean isContextClickable() {
7846        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
7847    }
7848
7849    /**
7850     * Enables or disables context clicking for this view. This event can launch the listener.
7851     *
7852     * @param contextClickable true to make the view react to a context click, false otherwise
7853     * @see #isContextClickable()
7854     * @attr ref android.R.styleable#View_contextClickable
7855     */
7856    public void setContextClickable(boolean contextClickable) {
7857        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
7858    }
7859
7860    /**
7861     * Sets the pressed state for this view and provides a touch coordinate for
7862     * animation hinting.
7863     *
7864     * @param pressed Pass true to set the View's internal state to "pressed",
7865     *            or false to reverts the View's internal state from a
7866     *            previously set "pressed" state.
7867     * @param x The x coordinate of the touch that caused the press
7868     * @param y The y coordinate of the touch that caused the press
7869     */
7870    private void setPressed(boolean pressed, float x, float y) {
7871        if (pressed) {
7872            drawableHotspotChanged(x, y);
7873        }
7874
7875        setPressed(pressed);
7876    }
7877
7878    /**
7879     * Sets the pressed state for this view.
7880     *
7881     * @see #isClickable()
7882     * @see #setClickable(boolean)
7883     *
7884     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7885     *        the View's internal state from a previously set "pressed" state.
7886     */
7887    public void setPressed(boolean pressed) {
7888        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7889
7890        if (pressed) {
7891            mPrivateFlags |= PFLAG_PRESSED;
7892        } else {
7893            mPrivateFlags &= ~PFLAG_PRESSED;
7894        }
7895
7896        if (needsRefresh) {
7897            refreshDrawableState();
7898        }
7899        dispatchSetPressed(pressed);
7900    }
7901
7902    /**
7903     * Dispatch setPressed to all of this View's children.
7904     *
7905     * @see #setPressed(boolean)
7906     *
7907     * @param pressed The new pressed state
7908     */
7909    protected void dispatchSetPressed(boolean pressed) {
7910    }
7911
7912    /**
7913     * Indicates whether the view is currently in pressed state. Unless
7914     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7915     * the pressed state.
7916     *
7917     * @see #setPressed(boolean)
7918     * @see #isClickable()
7919     * @see #setClickable(boolean)
7920     *
7921     * @return true if the view is currently pressed, false otherwise
7922     */
7923    @ViewDebug.ExportedProperty
7924    public boolean isPressed() {
7925        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7926    }
7927
7928    /**
7929     * @hide
7930     * Indicates whether this view will participate in data collection through
7931     * {@link ViewStructure}.  If true, it will not provide any data
7932     * for itself or its children.  If false, the normal data collection will be allowed.
7933     *
7934     * @return Returns false if assist data collection is not blocked, else true.
7935     *
7936     * @see #setAssistBlocked(boolean)
7937     * @attr ref android.R.styleable#View_assistBlocked
7938     */
7939    public boolean isAssistBlocked() {
7940        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
7941    }
7942
7943    /**
7944     * @hide
7945     * Controls whether assist data collection from this view and its children is enabled
7946     * (that is, whether {@link #onProvideStructure} and
7947     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
7948     * allowing normal assist collection.  Setting this to false will disable assist collection.
7949     *
7950     * @param enabled Set to true to <em>disable</em> assist data collection, or false
7951     * (the default) to allow it.
7952     *
7953     * @see #isAssistBlocked()
7954     * @see #onProvideStructure
7955     * @see #onProvideVirtualStructure
7956     * @attr ref android.R.styleable#View_assistBlocked
7957     */
7958    public void setAssistBlocked(boolean enabled) {
7959        if (enabled) {
7960            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
7961        } else {
7962            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
7963        }
7964    }
7965
7966    /**
7967     * Indicates whether this view will save its state (that is,
7968     * whether its {@link #onSaveInstanceState} method will be called).
7969     *
7970     * @return Returns true if the view state saving is enabled, else false.
7971     *
7972     * @see #setSaveEnabled(boolean)
7973     * @attr ref android.R.styleable#View_saveEnabled
7974     */
7975    public boolean isSaveEnabled() {
7976        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7977    }
7978
7979    /**
7980     * Controls whether the saving of this view's state is
7981     * enabled (that is, whether its {@link #onSaveInstanceState} method
7982     * will be called).  Note that even if freezing is enabled, the
7983     * view still must have an id assigned to it (via {@link #setId(int)})
7984     * for its state to be saved.  This flag can only disable the
7985     * saving of this view; any child views may still have their state saved.
7986     *
7987     * @param enabled Set to false to <em>disable</em> state saving, or true
7988     * (the default) to allow it.
7989     *
7990     * @see #isSaveEnabled()
7991     * @see #setId(int)
7992     * @see #onSaveInstanceState()
7993     * @attr ref android.R.styleable#View_saveEnabled
7994     */
7995    public void setSaveEnabled(boolean enabled) {
7996        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7997    }
7998
7999    /**
8000     * Gets whether the framework should discard touches when the view's
8001     * window is obscured by another visible window.
8002     * Refer to the {@link View} security documentation for more details.
8003     *
8004     * @return True if touch filtering is enabled.
8005     *
8006     * @see #setFilterTouchesWhenObscured(boolean)
8007     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8008     */
8009    @ViewDebug.ExportedProperty
8010    public boolean getFilterTouchesWhenObscured() {
8011        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8012    }
8013
8014    /**
8015     * Sets whether the framework should discard touches when the view's
8016     * window is obscured by another visible window.
8017     * Refer to the {@link View} security documentation for more details.
8018     *
8019     * @param enabled True if touch filtering should be enabled.
8020     *
8021     * @see #getFilterTouchesWhenObscured
8022     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8023     */
8024    public void setFilterTouchesWhenObscured(boolean enabled) {
8025        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8026                FILTER_TOUCHES_WHEN_OBSCURED);
8027    }
8028
8029    /**
8030     * Indicates whether the entire hierarchy under this view will save its
8031     * state when a state saving traversal occurs from its parent.  The default
8032     * is true; if false, these views will not be saved unless
8033     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8034     *
8035     * @return Returns true if the view state saving from parent is enabled, else false.
8036     *
8037     * @see #setSaveFromParentEnabled(boolean)
8038     */
8039    public boolean isSaveFromParentEnabled() {
8040        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8041    }
8042
8043    /**
8044     * Controls whether the entire hierarchy under this view will save its
8045     * state when a state saving traversal occurs from its parent.  The default
8046     * is true; if false, these views will not be saved unless
8047     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8048     *
8049     * @param enabled Set to false to <em>disable</em> state saving, or true
8050     * (the default) to allow it.
8051     *
8052     * @see #isSaveFromParentEnabled()
8053     * @see #setId(int)
8054     * @see #onSaveInstanceState()
8055     */
8056    public void setSaveFromParentEnabled(boolean enabled) {
8057        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8058    }
8059
8060
8061    /**
8062     * Returns whether this View is able to take focus.
8063     *
8064     * @return True if this view can take focus, or false otherwise.
8065     * @attr ref android.R.styleable#View_focusable
8066     */
8067    @ViewDebug.ExportedProperty(category = "focus")
8068    public final boolean isFocusable() {
8069        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8070    }
8071
8072    /**
8073     * When a view is focusable, it may not want to take focus when in touch mode.
8074     * For example, a button would like focus when the user is navigating via a D-pad
8075     * so that the user can click on it, but once the user starts touching the screen,
8076     * the button shouldn't take focus
8077     * @return Whether the view is focusable in touch mode.
8078     * @attr ref android.R.styleable#View_focusableInTouchMode
8079     */
8080    @ViewDebug.ExportedProperty
8081    public final boolean isFocusableInTouchMode() {
8082        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8083    }
8084
8085    /**
8086     * Find the nearest view in the specified direction that can take focus.
8087     * This does not actually give focus to that view.
8088     *
8089     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8090     *
8091     * @return The nearest focusable in the specified direction, or null if none
8092     *         can be found.
8093     */
8094    public View focusSearch(@FocusRealDirection int direction) {
8095        if (mParent != null) {
8096            return mParent.focusSearch(this, direction);
8097        } else {
8098            return null;
8099        }
8100    }
8101
8102    /**
8103     * This method is the last chance for the focused view and its ancestors to
8104     * respond to an arrow key. This is called when the focused view did not
8105     * consume the key internally, nor could the view system find a new view in
8106     * the requested direction to give focus to.
8107     *
8108     * @param focused The currently focused view.
8109     * @param direction The direction focus wants to move. One of FOCUS_UP,
8110     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8111     * @return True if the this view consumed this unhandled move.
8112     */
8113    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8114        return false;
8115    }
8116
8117    /**
8118     * If a user manually specified the next view id for a particular direction,
8119     * use the root to look up the view.
8120     * @param root The root view of the hierarchy containing this view.
8121     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8122     * or FOCUS_BACKWARD.
8123     * @return The user specified next view, or null if there is none.
8124     */
8125    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8126        switch (direction) {
8127            case FOCUS_LEFT:
8128                if (mNextFocusLeftId == View.NO_ID) return null;
8129                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8130            case FOCUS_RIGHT:
8131                if (mNextFocusRightId == View.NO_ID) return null;
8132                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8133            case FOCUS_UP:
8134                if (mNextFocusUpId == View.NO_ID) return null;
8135                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8136            case FOCUS_DOWN:
8137                if (mNextFocusDownId == View.NO_ID) return null;
8138                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8139            case FOCUS_FORWARD:
8140                if (mNextFocusForwardId == View.NO_ID) return null;
8141                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8142            case FOCUS_BACKWARD: {
8143                if (mID == View.NO_ID) return null;
8144                final int id = mID;
8145                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8146                    @Override
8147                    public boolean apply(View t) {
8148                        return t.mNextFocusForwardId == id;
8149                    }
8150                });
8151            }
8152        }
8153        return null;
8154    }
8155
8156    private View findViewInsideOutShouldExist(View root, int id) {
8157        if (mMatchIdPredicate == null) {
8158            mMatchIdPredicate = new MatchIdPredicate();
8159        }
8160        mMatchIdPredicate.mId = id;
8161        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8162        if (result == null) {
8163            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8164        }
8165        return result;
8166    }
8167
8168    /**
8169     * Find and return all focusable views that are descendants of this view,
8170     * possibly including this view if it is focusable itself.
8171     *
8172     * @param direction The direction of the focus
8173     * @return A list of focusable views
8174     */
8175    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8176        ArrayList<View> result = new ArrayList<View>(24);
8177        addFocusables(result, direction);
8178        return result;
8179    }
8180
8181    /**
8182     * Add any focusable views that are descendants of this view (possibly
8183     * including this view if it is focusable itself) to views.  If we are in touch mode,
8184     * only add views that are also focusable in touch mode.
8185     *
8186     * @param views Focusable views found so far
8187     * @param direction The direction of the focus
8188     */
8189    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8190        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
8191    }
8192
8193    /**
8194     * Adds any focusable views that are descendants of this view (possibly
8195     * including this view if it is focusable itself) to views. This method
8196     * adds all focusable views regardless if we are in touch mode or
8197     * only views focusable in touch mode if we are in touch mode or
8198     * only views that can take accessibility focus if accessibility is enabled
8199     * depending on the focusable mode parameter.
8200     *
8201     * @param views Focusable views found so far or null if all we are interested is
8202     *        the number of focusables.
8203     * @param direction The direction of the focus.
8204     * @param focusableMode The type of focusables to be added.
8205     *
8206     * @see #FOCUSABLES_ALL
8207     * @see #FOCUSABLES_TOUCH_MODE
8208     */
8209    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8210            @FocusableMode int focusableMode) {
8211        if (views == null) {
8212            return;
8213        }
8214        if (!isFocusable()) {
8215            return;
8216        }
8217        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8218                && isInTouchMode() && !isFocusableInTouchMode()) {
8219            return;
8220        }
8221        views.add(this);
8222    }
8223
8224    /**
8225     * Finds the Views that contain given text. The containment is case insensitive.
8226     * The search is performed by either the text that the View renders or the content
8227     * description that describes the view for accessibility purposes and the view does
8228     * not render or both. Clients can specify how the search is to be performed via
8229     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8230     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8231     *
8232     * @param outViews The output list of matching Views.
8233     * @param searched The text to match against.
8234     *
8235     * @see #FIND_VIEWS_WITH_TEXT
8236     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8237     * @see #setContentDescription(CharSequence)
8238     */
8239    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8240            @FindViewFlags int flags) {
8241        if (getAccessibilityNodeProvider() != null) {
8242            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8243                outViews.add(this);
8244            }
8245        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8246                && (searched != null && searched.length() > 0)
8247                && (mContentDescription != null && mContentDescription.length() > 0)) {
8248            String searchedLowerCase = searched.toString().toLowerCase();
8249            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8250            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8251                outViews.add(this);
8252            }
8253        }
8254    }
8255
8256    /**
8257     * Find and return all touchable views that are descendants of this view,
8258     * possibly including this view if it is touchable itself.
8259     *
8260     * @return A list of touchable views
8261     */
8262    public ArrayList<View> getTouchables() {
8263        ArrayList<View> result = new ArrayList<View>();
8264        addTouchables(result);
8265        return result;
8266    }
8267
8268    /**
8269     * Add any touchable views that are descendants of this view (possibly
8270     * including this view if it is touchable itself) to views.
8271     *
8272     * @param views Touchable views found so far
8273     */
8274    public void addTouchables(ArrayList<View> views) {
8275        final int viewFlags = mViewFlags;
8276
8277        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8278                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8279                && (viewFlags & ENABLED_MASK) == ENABLED) {
8280            views.add(this);
8281        }
8282    }
8283
8284    /**
8285     * Returns whether this View is accessibility focused.
8286     *
8287     * @return True if this View is accessibility focused.
8288     */
8289    public boolean isAccessibilityFocused() {
8290        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8291    }
8292
8293    /**
8294     * Call this to try to give accessibility focus to this view.
8295     *
8296     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8297     * returns false or the view is no visible or the view already has accessibility
8298     * focus.
8299     *
8300     * See also {@link #focusSearch(int)}, which is what you call to say that you
8301     * have focus, and you want your parent to look for the next one.
8302     *
8303     * @return Whether this view actually took accessibility focus.
8304     *
8305     * @hide
8306     */
8307    public boolean requestAccessibilityFocus() {
8308        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8309        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8310            return false;
8311        }
8312        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8313            return false;
8314        }
8315        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8316            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8317            ViewRootImpl viewRootImpl = getViewRootImpl();
8318            if (viewRootImpl != null) {
8319                viewRootImpl.setAccessibilityFocus(this, null);
8320            }
8321            invalidate();
8322            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8323            return true;
8324        }
8325        return false;
8326    }
8327
8328    /**
8329     * Call this to try to clear accessibility focus of this view.
8330     *
8331     * See also {@link #focusSearch(int)}, which is what you call to say that you
8332     * have focus, and you want your parent to look for the next one.
8333     *
8334     * @hide
8335     */
8336    public void clearAccessibilityFocus() {
8337        clearAccessibilityFocusNoCallbacks();
8338        // Clear the global reference of accessibility focus if this
8339        // view or any of its descendants had accessibility focus.
8340        ViewRootImpl viewRootImpl = getViewRootImpl();
8341        if (viewRootImpl != null) {
8342            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8343            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8344                viewRootImpl.setAccessibilityFocus(null, null);
8345            }
8346        }
8347    }
8348
8349    private void sendAccessibilityHoverEvent(int eventType) {
8350        // Since we are not delivering to a client accessibility events from not
8351        // important views (unless the clinet request that) we need to fire the
8352        // event from the deepest view exposed to the client. As a consequence if
8353        // the user crosses a not exposed view the client will see enter and exit
8354        // of the exposed predecessor followed by and enter and exit of that same
8355        // predecessor when entering and exiting the not exposed descendant. This
8356        // is fine since the client has a clear idea which view is hovered at the
8357        // price of a couple more events being sent. This is a simple and
8358        // working solution.
8359        View source = this;
8360        while (true) {
8361            if (source.includeForAccessibility()) {
8362                source.sendAccessibilityEvent(eventType);
8363                return;
8364            }
8365            ViewParent parent = source.getParent();
8366            if (parent instanceof View) {
8367                source = (View) parent;
8368            } else {
8369                return;
8370            }
8371        }
8372    }
8373
8374    /**
8375     * Clears accessibility focus without calling any callback methods
8376     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8377     * is used for clearing accessibility focus when giving this focus to
8378     * another view.
8379     */
8380    void clearAccessibilityFocusNoCallbacks() {
8381        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8382            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8383            invalidate();
8384            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8385        }
8386    }
8387
8388    /**
8389     * Call this to try to give focus to a specific view or to one of its
8390     * descendants.
8391     *
8392     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8393     * false), or if it is focusable and it is not focusable in touch mode
8394     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8395     *
8396     * See also {@link #focusSearch(int)}, which is what you call to say that you
8397     * have focus, and you want your parent to look for the next one.
8398     *
8399     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8400     * {@link #FOCUS_DOWN} and <code>null</code>.
8401     *
8402     * @return Whether this view or one of its descendants actually took focus.
8403     */
8404    public final boolean requestFocus() {
8405        return requestFocus(View.FOCUS_DOWN);
8406    }
8407
8408    /**
8409     * Call this to try to give focus to a specific view or to one of its
8410     * descendants and give it a hint about what direction focus is heading.
8411     *
8412     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8413     * false), or if it is focusable and it is not focusable in touch mode
8414     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8415     *
8416     * See also {@link #focusSearch(int)}, which is what you call to say that you
8417     * have focus, and you want your parent to look for the next one.
8418     *
8419     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8420     * <code>null</code> set for the previously focused rectangle.
8421     *
8422     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8423     * @return Whether this view or one of its descendants actually took focus.
8424     */
8425    public final boolean requestFocus(int direction) {
8426        return requestFocus(direction, null);
8427    }
8428
8429    /**
8430     * Call this to try to give focus to a specific view or to one of its descendants
8431     * and give it hints about the direction and a specific rectangle that the focus
8432     * is coming from.  The rectangle can help give larger views a finer grained hint
8433     * about where focus is coming from, and therefore, where to show selection, or
8434     * forward focus change internally.
8435     *
8436     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8437     * false), or if it is focusable and it is not focusable in touch mode
8438     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8439     *
8440     * A View will not take focus if it is not visible.
8441     *
8442     * A View will not take focus if one of its parents has
8443     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
8444     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
8445     *
8446     * See also {@link #focusSearch(int)}, which is what you call to say that you
8447     * have focus, and you want your parent to look for the next one.
8448     *
8449     * You may wish to override this method if your custom {@link View} has an internal
8450     * {@link View} that it wishes to forward the request to.
8451     *
8452     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8453     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8454     *        to give a finer grained hint about where focus is coming from.  May be null
8455     *        if there is no hint.
8456     * @return Whether this view or one of its descendants actually took focus.
8457     */
8458    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8459        return requestFocusNoSearch(direction, previouslyFocusedRect);
8460    }
8461
8462    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8463        // need to be focusable
8464        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
8465                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8466            return false;
8467        }
8468
8469        // need to be focusable in touch mode if in touch mode
8470        if (isInTouchMode() &&
8471            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
8472               return false;
8473        }
8474
8475        // need to not have any parents blocking us
8476        if (hasAncestorThatBlocksDescendantFocus()) {
8477            return false;
8478        }
8479
8480        handleFocusGainInternal(direction, previouslyFocusedRect);
8481        return true;
8482    }
8483
8484    /**
8485     * Call this to try to give focus to a specific view or to one of its descendants. This is a
8486     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
8487     * touch mode to request focus when they are touched.
8488     *
8489     * @return Whether this view or one of its descendants actually took focus.
8490     *
8491     * @see #isInTouchMode()
8492     *
8493     */
8494    public final boolean requestFocusFromTouch() {
8495        // Leave touch mode if we need to
8496        if (isInTouchMode()) {
8497            ViewRootImpl viewRoot = getViewRootImpl();
8498            if (viewRoot != null) {
8499                viewRoot.ensureTouchMode(false);
8500            }
8501        }
8502        return requestFocus(View.FOCUS_DOWN);
8503    }
8504
8505    /**
8506     * @return Whether any ancestor of this view blocks descendant focus.
8507     */
8508    private boolean hasAncestorThatBlocksDescendantFocus() {
8509        final boolean focusableInTouchMode = isFocusableInTouchMode();
8510        ViewParent ancestor = mParent;
8511        while (ancestor instanceof ViewGroup) {
8512            final ViewGroup vgAncestor = (ViewGroup) ancestor;
8513            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
8514                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
8515                return true;
8516            } else {
8517                ancestor = vgAncestor.getParent();
8518            }
8519        }
8520        return false;
8521    }
8522
8523    /**
8524     * Gets the mode for determining whether this View is important for accessibility
8525     * which is if it fires accessibility events and if it is reported to
8526     * accessibility services that query the screen.
8527     *
8528     * @return The mode for determining whether a View is important for accessibility.
8529     *
8530     * @attr ref android.R.styleable#View_importantForAccessibility
8531     *
8532     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8533     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8534     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8535     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8536     */
8537    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
8538            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
8539            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
8540            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
8541            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
8542                    to = "noHideDescendants")
8543        })
8544    public int getImportantForAccessibility() {
8545        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8546                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8547    }
8548
8549    /**
8550     * Sets the live region mode for this view. This indicates to accessibility
8551     * services whether they should automatically notify the user about changes
8552     * to the view's content description or text, or to the content descriptions
8553     * or text of the view's children (where applicable).
8554     * <p>
8555     * For example, in a login screen with a TextView that displays an "incorrect
8556     * password" notification, that view should be marked as a live region with
8557     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8558     * <p>
8559     * To disable change notifications for this view, use
8560     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
8561     * mode for most views.
8562     * <p>
8563     * To indicate that the user should be notified of changes, use
8564     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8565     * <p>
8566     * If the view's changes should interrupt ongoing speech and notify the user
8567     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
8568     *
8569     * @param mode The live region mode for this view, one of:
8570     *        <ul>
8571     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
8572     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
8573     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
8574     *        </ul>
8575     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8576     */
8577    public void setAccessibilityLiveRegion(int mode) {
8578        if (mode != getAccessibilityLiveRegion()) {
8579            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8580            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
8581                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8582            notifyViewAccessibilityStateChangedIfNeeded(
8583                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8584        }
8585    }
8586
8587    /**
8588     * Gets the live region mode for this View.
8589     *
8590     * @return The live region mode for the view.
8591     *
8592     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8593     *
8594     * @see #setAccessibilityLiveRegion(int)
8595     */
8596    public int getAccessibilityLiveRegion() {
8597        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
8598                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
8599    }
8600
8601    /**
8602     * Sets how to determine whether this view is important for accessibility
8603     * which is if it fires accessibility events and if it is reported to
8604     * accessibility services that query the screen.
8605     *
8606     * @param mode How to determine whether this view is important for accessibility.
8607     *
8608     * @attr ref android.R.styleable#View_importantForAccessibility
8609     *
8610     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8611     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8612     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8613     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8614     */
8615    public void setImportantForAccessibility(int mode) {
8616        final int oldMode = getImportantForAccessibility();
8617        if (mode != oldMode) {
8618            // If we're moving between AUTO and another state, we might not need
8619            // to send a subtree changed notification. We'll store the computed
8620            // importance, since we'll need to check it later to make sure.
8621            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
8622                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8623            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
8624            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8625            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
8626                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8627            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
8628                notifySubtreeAccessibilityStateChangedIfNeeded();
8629            } else {
8630                notifyViewAccessibilityStateChangedIfNeeded(
8631                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8632            }
8633        }
8634    }
8635
8636    /**
8637     * Computes whether this view should be exposed for accessibility. In
8638     * general, views that are interactive or provide information are exposed
8639     * while views that serve only as containers are hidden.
8640     * <p>
8641     * If an ancestor of this view has importance
8642     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
8643     * returns <code>false</code>.
8644     * <p>
8645     * Otherwise, the value is computed according to the view's
8646     * {@link #getImportantForAccessibility()} value:
8647     * <ol>
8648     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
8649     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
8650     * </code>
8651     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
8652     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
8653     * view satisfies any of the following:
8654     * <ul>
8655     * <li>Is actionable, e.g. {@link #isClickable()},
8656     * {@link #isLongClickable()}, or {@link #isFocusable()}
8657     * <li>Has an {@link AccessibilityDelegate}
8658     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
8659     * {@link OnKeyListener}, etc.
8660     * <li>Is an accessibility live region, e.g.
8661     * {@link #getAccessibilityLiveRegion()} is not
8662     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
8663     * </ul>
8664     * </ol>
8665     *
8666     * @return Whether the view is exposed for accessibility.
8667     * @see #setImportantForAccessibility(int)
8668     * @see #getImportantForAccessibility()
8669     */
8670    public boolean isImportantForAccessibility() {
8671        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8672                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8673        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8674                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8675            return false;
8676        }
8677
8678        // Check parent mode to ensure we're not hidden.
8679        ViewParent parent = mParent;
8680        while (parent instanceof View) {
8681            if (((View) parent).getImportantForAccessibility()
8682                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8683                return false;
8684            }
8685            parent = parent.getParent();
8686        }
8687
8688        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8689                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8690                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8691    }
8692
8693    /**
8694     * Gets the parent for accessibility purposes. Note that the parent for
8695     * accessibility is not necessary the immediate parent. It is the first
8696     * predecessor that is important for accessibility.
8697     *
8698     * @return The parent for accessibility purposes.
8699     */
8700    public ViewParent getParentForAccessibility() {
8701        if (mParent instanceof View) {
8702            View parentView = (View) mParent;
8703            if (parentView.includeForAccessibility()) {
8704                return mParent;
8705            } else {
8706                return mParent.getParentForAccessibility();
8707            }
8708        }
8709        return null;
8710    }
8711
8712    /**
8713     * Adds the children of a given View for accessibility. Since some Views are
8714     * not important for accessibility the children for accessibility are not
8715     * necessarily direct children of the view, rather they are the first level of
8716     * descendants important for accessibility.
8717     *
8718     * @param children The list of children for accessibility.
8719     */
8720    public void addChildrenForAccessibility(ArrayList<View> children) {
8721
8722    }
8723
8724    /**
8725     * Whether to regard this view for accessibility. A view is regarded for
8726     * accessibility if it is important for accessibility or the querying
8727     * accessibility service has explicitly requested that view not
8728     * important for accessibility are regarded.
8729     *
8730     * @return Whether to regard the view for accessibility.
8731     *
8732     * @hide
8733     */
8734    public boolean includeForAccessibility() {
8735        if (mAttachInfo != null) {
8736            return (mAttachInfo.mAccessibilityFetchFlags
8737                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8738                    || isImportantForAccessibility();
8739        }
8740        return false;
8741    }
8742
8743    /**
8744     * Returns whether the View is considered actionable from
8745     * accessibility perspective. Such view are important for
8746     * accessibility.
8747     *
8748     * @return True if the view is actionable for accessibility.
8749     *
8750     * @hide
8751     */
8752    public boolean isActionableForAccessibility() {
8753        return (isClickable() || isLongClickable() || isFocusable());
8754    }
8755
8756    /**
8757     * Returns whether the View has registered callbacks which makes it
8758     * important for accessibility.
8759     *
8760     * @return True if the view is actionable for accessibility.
8761     */
8762    private boolean hasListenersForAccessibility() {
8763        ListenerInfo info = getListenerInfo();
8764        return mTouchDelegate != null || info.mOnKeyListener != null
8765                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8766                || info.mOnHoverListener != null || info.mOnDragListener != null;
8767    }
8768
8769    /**
8770     * Notifies that the accessibility state of this view changed. The change
8771     * is local to this view and does not represent structural changes such
8772     * as children and parent. For example, the view became focusable. The
8773     * notification is at at most once every
8774     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8775     * to avoid unnecessary load to the system. Also once a view has a pending
8776     * notification this method is a NOP until the notification has been sent.
8777     *
8778     * @hide
8779     */
8780    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8781        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
8782            return;
8783        }
8784        if (mSendViewStateChangedAccessibilityEvent == null) {
8785            mSendViewStateChangedAccessibilityEvent =
8786                    new SendViewStateChangedAccessibilityEvent();
8787        }
8788        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8789    }
8790
8791    /**
8792     * Notifies that the accessibility state of this view changed. The change
8793     * is *not* local to this view and does represent structural changes such
8794     * as children and parent. For example, the view size changed. The
8795     * notification is at at most once every
8796     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8797     * to avoid unnecessary load to the system. Also once a view has a pending
8798     * notification this method is a NOP until the notification has been sent.
8799     *
8800     * @hide
8801     */
8802    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8803        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
8804            return;
8805        }
8806        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8807            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8808            if (mParent != null) {
8809                try {
8810                    mParent.notifySubtreeAccessibilityStateChanged(
8811                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8812                } catch (AbstractMethodError e) {
8813                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8814                            " does not fully implement ViewParent", e);
8815                }
8816            }
8817        }
8818    }
8819
8820    /**
8821     * Change the visibility of the View without triggering any other changes. This is
8822     * important for transitions, where visibility changes should not adjust focus or
8823     * trigger a new layout. This is only used when the visibility has already been changed
8824     * and we need a transient value during an animation. When the animation completes,
8825     * the original visibility value is always restored.
8826     *
8827     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8828     * @hide
8829     */
8830    public void setTransitionVisibility(@Visibility int visibility) {
8831        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
8832    }
8833
8834    /**
8835     * Reset the flag indicating the accessibility state of the subtree rooted
8836     * at this view changed.
8837     */
8838    void resetSubtreeAccessibilityStateChanged() {
8839        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8840    }
8841
8842    /**
8843     * Report an accessibility action to this view's parents for delegated processing.
8844     *
8845     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8846     * call this method to delegate an accessibility action to a supporting parent. If the parent
8847     * returns true from its
8848     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8849     * method this method will return true to signify that the action was consumed.</p>
8850     *
8851     * <p>This method is useful for implementing nested scrolling child views. If
8852     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8853     * a custom view implementation may invoke this method to allow a parent to consume the
8854     * scroll first. If this method returns true the custom view should skip its own scrolling
8855     * behavior.</p>
8856     *
8857     * @param action Accessibility action to delegate
8858     * @param arguments Optional action arguments
8859     * @return true if the action was consumed by a parent
8860     */
8861    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8862        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8863            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8864                return true;
8865            }
8866        }
8867        return false;
8868    }
8869
8870    /**
8871     * Performs the specified accessibility action on the view. For
8872     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8873     * <p>
8874     * If an {@link AccessibilityDelegate} has been specified via calling
8875     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8876     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8877     * is responsible for handling this call.
8878     * </p>
8879     *
8880     * <p>The default implementation will delegate
8881     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8882     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8883     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8884     *
8885     * @param action The action to perform.
8886     * @param arguments Optional action arguments.
8887     * @return Whether the action was performed.
8888     */
8889    public boolean performAccessibilityAction(int action, Bundle arguments) {
8890      if (mAccessibilityDelegate != null) {
8891          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8892      } else {
8893          return performAccessibilityActionInternal(action, arguments);
8894      }
8895    }
8896
8897   /**
8898    * @see #performAccessibilityAction(int, Bundle)
8899    *
8900    * Note: Called from the default {@link AccessibilityDelegate}.
8901    *
8902    * @hide
8903    */
8904    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8905        if (isNestedScrollingEnabled()
8906                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8907                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
8908                || action == R.id.accessibilityActionScrollUp
8909                || action == R.id.accessibilityActionScrollLeft
8910                || action == R.id.accessibilityActionScrollDown
8911                || action == R.id.accessibilityActionScrollRight)) {
8912            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8913                return true;
8914            }
8915        }
8916
8917        switch (action) {
8918            case AccessibilityNodeInfo.ACTION_CLICK: {
8919                if (isClickable()) {
8920                    performClick();
8921                    return true;
8922                }
8923            } break;
8924            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8925                if (isLongClickable()) {
8926                    performLongClick();
8927                    return true;
8928                }
8929            } break;
8930            case AccessibilityNodeInfo.ACTION_FOCUS: {
8931                if (!hasFocus()) {
8932                    // Get out of touch mode since accessibility
8933                    // wants to move focus around.
8934                    getViewRootImpl().ensureTouchMode(false);
8935                    return requestFocus();
8936                }
8937            } break;
8938            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8939                if (hasFocus()) {
8940                    clearFocus();
8941                    return !isFocused();
8942                }
8943            } break;
8944            case AccessibilityNodeInfo.ACTION_SELECT: {
8945                if (!isSelected()) {
8946                    setSelected(true);
8947                    return isSelected();
8948                }
8949            } break;
8950            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8951                if (isSelected()) {
8952                    setSelected(false);
8953                    return !isSelected();
8954                }
8955            } break;
8956            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8957                if (!isAccessibilityFocused()) {
8958                    return requestAccessibilityFocus();
8959                }
8960            } break;
8961            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8962                if (isAccessibilityFocused()) {
8963                    clearAccessibilityFocus();
8964                    return true;
8965                }
8966            } break;
8967            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8968                if (arguments != null) {
8969                    final int granularity = arguments.getInt(
8970                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8971                    final boolean extendSelection = arguments.getBoolean(
8972                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8973                    return traverseAtGranularity(granularity, true, extendSelection);
8974                }
8975            } break;
8976            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8977                if (arguments != null) {
8978                    final int granularity = arguments.getInt(
8979                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8980                    final boolean extendSelection = arguments.getBoolean(
8981                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8982                    return traverseAtGranularity(granularity, false, extendSelection);
8983                }
8984            } break;
8985            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8986                CharSequence text = getIterableTextForAccessibility();
8987                if (text == null) {
8988                    return false;
8989                }
8990                final int start = (arguments != null) ? arguments.getInt(
8991                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8992                final int end = (arguments != null) ? arguments.getInt(
8993                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8994                // Only cursor position can be specified (selection length == 0)
8995                if ((getAccessibilitySelectionStart() != start
8996                        || getAccessibilitySelectionEnd() != end)
8997                        && (start == end)) {
8998                    setAccessibilitySelection(start, end);
8999                    notifyViewAccessibilityStateChangedIfNeeded(
9000                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9001                    return true;
9002                }
9003            } break;
9004            case R.id.accessibilityActionShowOnScreen: {
9005                if (mAttachInfo != null) {
9006                    final Rect r = mAttachInfo.mTmpInvalRect;
9007                    getDrawingRect(r);
9008                    return requestRectangleOnScreen(r, true);
9009                }
9010            } break;
9011            case R.id.accessibilityActionContextClick: {
9012                if (isContextClickable()) {
9013                    performContextClick();
9014                    return true;
9015                }
9016            } break;
9017        }
9018        return false;
9019    }
9020
9021    private boolean traverseAtGranularity(int granularity, boolean forward,
9022            boolean extendSelection) {
9023        CharSequence text = getIterableTextForAccessibility();
9024        if (text == null || text.length() == 0) {
9025            return false;
9026        }
9027        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9028        if (iterator == null) {
9029            return false;
9030        }
9031        int current = getAccessibilitySelectionEnd();
9032        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9033            current = forward ? 0 : text.length();
9034        }
9035        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9036        if (range == null) {
9037            return false;
9038        }
9039        final int segmentStart = range[0];
9040        final int segmentEnd = range[1];
9041        int selectionStart;
9042        int selectionEnd;
9043        if (extendSelection && isAccessibilitySelectionExtendable()) {
9044            selectionStart = getAccessibilitySelectionStart();
9045            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9046                selectionStart = forward ? segmentStart : segmentEnd;
9047            }
9048            selectionEnd = forward ? segmentEnd : segmentStart;
9049        } else {
9050            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9051        }
9052        setAccessibilitySelection(selectionStart, selectionEnd);
9053        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9054                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9055        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9056        return true;
9057    }
9058
9059    /**
9060     * Gets the text reported for accessibility purposes.
9061     *
9062     * @return The accessibility text.
9063     *
9064     * @hide
9065     */
9066    public CharSequence getIterableTextForAccessibility() {
9067        return getContentDescription();
9068    }
9069
9070    /**
9071     * Gets whether accessibility selection can be extended.
9072     *
9073     * @return If selection is extensible.
9074     *
9075     * @hide
9076     */
9077    public boolean isAccessibilitySelectionExtendable() {
9078        return false;
9079    }
9080
9081    /**
9082     * @hide
9083     */
9084    public int getAccessibilitySelectionStart() {
9085        return mAccessibilityCursorPosition;
9086    }
9087
9088    /**
9089     * @hide
9090     */
9091    public int getAccessibilitySelectionEnd() {
9092        return getAccessibilitySelectionStart();
9093    }
9094
9095    /**
9096     * @hide
9097     */
9098    public void setAccessibilitySelection(int start, int end) {
9099        if (start ==  end && end == mAccessibilityCursorPosition) {
9100            return;
9101        }
9102        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9103            mAccessibilityCursorPosition = start;
9104        } else {
9105            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9106        }
9107        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9108    }
9109
9110    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9111            int fromIndex, int toIndex) {
9112        if (mParent == null) {
9113            return;
9114        }
9115        AccessibilityEvent event = AccessibilityEvent.obtain(
9116                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9117        onInitializeAccessibilityEvent(event);
9118        onPopulateAccessibilityEvent(event);
9119        event.setFromIndex(fromIndex);
9120        event.setToIndex(toIndex);
9121        event.setAction(action);
9122        event.setMovementGranularity(granularity);
9123        mParent.requestSendAccessibilityEvent(this, event);
9124    }
9125
9126    /**
9127     * @hide
9128     */
9129    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9130        switch (granularity) {
9131            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9132                CharSequence text = getIterableTextForAccessibility();
9133                if (text != null && text.length() > 0) {
9134                    CharacterTextSegmentIterator iterator =
9135                        CharacterTextSegmentIterator.getInstance(
9136                                mContext.getResources().getConfiguration().locale);
9137                    iterator.initialize(text.toString());
9138                    return iterator;
9139                }
9140            } break;
9141            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9142                CharSequence text = getIterableTextForAccessibility();
9143                if (text != null && text.length() > 0) {
9144                    WordTextSegmentIterator iterator =
9145                        WordTextSegmentIterator.getInstance(
9146                                mContext.getResources().getConfiguration().locale);
9147                    iterator.initialize(text.toString());
9148                    return iterator;
9149                }
9150            } break;
9151            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9152                CharSequence text = getIterableTextForAccessibility();
9153                if (text != null && text.length() > 0) {
9154                    ParagraphTextSegmentIterator iterator =
9155                        ParagraphTextSegmentIterator.getInstance();
9156                    iterator.initialize(text.toString());
9157                    return iterator;
9158                }
9159            } break;
9160        }
9161        return null;
9162    }
9163
9164    /**
9165     * @hide
9166     */
9167    public void dispatchStartTemporaryDetach() {
9168        onStartTemporaryDetach();
9169    }
9170
9171    /**
9172     * This is called when a container is going to temporarily detach a child, with
9173     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9174     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9175     * {@link #onDetachedFromWindow()} when the container is done.
9176     */
9177    public void onStartTemporaryDetach() {
9178        removeUnsetPressCallback();
9179        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9180    }
9181
9182    /**
9183     * @hide
9184     */
9185    public void dispatchFinishTemporaryDetach() {
9186        onFinishTemporaryDetach();
9187    }
9188
9189    /**
9190     * Called after {@link #onStartTemporaryDetach} when the container is done
9191     * changing the view.
9192     */
9193    public void onFinishTemporaryDetach() {
9194    }
9195
9196    /**
9197     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9198     * for this view's window.  Returns null if the view is not currently attached
9199     * to the window.  Normally you will not need to use this directly, but
9200     * just use the standard high-level event callbacks like
9201     * {@link #onKeyDown(int, KeyEvent)}.
9202     */
9203    public KeyEvent.DispatcherState getKeyDispatcherState() {
9204        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9205    }
9206
9207    /**
9208     * Dispatch a key event before it is processed by any input method
9209     * associated with the view hierarchy.  This can be used to intercept
9210     * key events in special situations before the IME consumes them; a
9211     * typical example would be handling the BACK key to update the application's
9212     * UI instead of allowing the IME to see it and close itself.
9213     *
9214     * @param event The key event to be dispatched.
9215     * @return True if the event was handled, false otherwise.
9216     */
9217    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9218        return onKeyPreIme(event.getKeyCode(), event);
9219    }
9220
9221    /**
9222     * Dispatch a key event to the next view on the focus path. This path runs
9223     * from the top of the view tree down to the currently focused view. If this
9224     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9225     * the next node down the focus path. This method also fires any key
9226     * listeners.
9227     *
9228     * @param event The key event to be dispatched.
9229     * @return True if the event was handled, false otherwise.
9230     */
9231    public boolean dispatchKeyEvent(KeyEvent event) {
9232        if (mInputEventConsistencyVerifier != null) {
9233            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9234        }
9235
9236        // Give any attached key listener a first crack at the event.
9237        //noinspection SimplifiableIfStatement
9238        ListenerInfo li = mListenerInfo;
9239        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9240                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9241            return true;
9242        }
9243
9244        if (event.dispatch(this, mAttachInfo != null
9245                ? mAttachInfo.mKeyDispatchState : null, this)) {
9246            return true;
9247        }
9248
9249        if (mInputEventConsistencyVerifier != null) {
9250            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9251        }
9252        return false;
9253    }
9254
9255    /**
9256     * Dispatches a key shortcut event.
9257     *
9258     * @param event The key event to be dispatched.
9259     * @return True if the event was handled by the view, false otherwise.
9260     */
9261    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9262        return onKeyShortcut(event.getKeyCode(), event);
9263    }
9264
9265    /**
9266     * Pass the touch screen motion event down to the target view, or this
9267     * view if it is the target.
9268     *
9269     * @param event The motion event to be dispatched.
9270     * @return True if the event was handled by the view, false otherwise.
9271     */
9272    public boolean dispatchTouchEvent(MotionEvent event) {
9273        // If the event should be handled by accessibility focus first.
9274        if (event.isTargetAccessibilityFocus()) {
9275            // We don't have focus or no virtual descendant has it, do not handle the event.
9276            if (!isAccessibilityFocusedViewOrHost()) {
9277                return false;
9278            }
9279            // We have focus and got the event, then use normal event dispatch.
9280            event.setTargetAccessibilityFocus(false);
9281        }
9282
9283        boolean result = false;
9284
9285        if (mInputEventConsistencyVerifier != null) {
9286            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9287        }
9288
9289        final int actionMasked = event.getActionMasked();
9290        if (actionMasked == MotionEvent.ACTION_DOWN) {
9291            // Defensive cleanup for new gesture
9292            stopNestedScroll();
9293        }
9294
9295        if (onFilterTouchEventForSecurity(event)) {
9296            //noinspection SimplifiableIfStatement
9297            ListenerInfo li = mListenerInfo;
9298            if (li != null && li.mOnTouchListener != null
9299                    && (mViewFlags & ENABLED_MASK) == ENABLED
9300                    && li.mOnTouchListener.onTouch(this, event)) {
9301                result = true;
9302            }
9303
9304            if (!result && onTouchEvent(event)) {
9305                result = true;
9306            }
9307        }
9308
9309        if (!result && mInputEventConsistencyVerifier != null) {
9310            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9311        }
9312
9313        // Clean up after nested scrolls if this is the end of a gesture;
9314        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9315        // of the gesture.
9316        if (actionMasked == MotionEvent.ACTION_UP ||
9317                actionMasked == MotionEvent.ACTION_CANCEL ||
9318                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9319            stopNestedScroll();
9320        }
9321
9322        return result;
9323    }
9324
9325    boolean isAccessibilityFocusedViewOrHost() {
9326        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9327                .getAccessibilityFocusedHost() == this);
9328    }
9329
9330    /**
9331     * Filter the touch event to apply security policies.
9332     *
9333     * @param event The motion event to be filtered.
9334     * @return True if the event should be dispatched, false if the event should be dropped.
9335     *
9336     * @see #getFilterTouchesWhenObscured
9337     */
9338    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9339        //noinspection RedundantIfStatement
9340        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9341                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9342            // Window is obscured, drop this touch.
9343            return false;
9344        }
9345        return true;
9346    }
9347
9348    /**
9349     * Pass a trackball motion event down to the focused view.
9350     *
9351     * @param event The motion event to be dispatched.
9352     * @return True if the event was handled by the view, false otherwise.
9353     */
9354    public boolean dispatchTrackballEvent(MotionEvent event) {
9355        if (mInputEventConsistencyVerifier != null) {
9356            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9357        }
9358
9359        return onTrackballEvent(event);
9360    }
9361
9362    /**
9363     * Dispatch a generic motion event.
9364     * <p>
9365     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9366     * are delivered to the view under the pointer.  All other generic motion events are
9367     * delivered to the focused view.  Hover events are handled specially and are delivered
9368     * to {@link #onHoverEvent(MotionEvent)}.
9369     * </p>
9370     *
9371     * @param event The motion event to be dispatched.
9372     * @return True if the event was handled by the view, false otherwise.
9373     */
9374    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9375        if (mInputEventConsistencyVerifier != null) {
9376            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
9377        }
9378
9379        final int source = event.getSource();
9380        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
9381            final int action = event.getAction();
9382            if (action == MotionEvent.ACTION_HOVER_ENTER
9383                    || action == MotionEvent.ACTION_HOVER_MOVE
9384                    || action == MotionEvent.ACTION_HOVER_EXIT) {
9385                if (dispatchHoverEvent(event)) {
9386                    return true;
9387                }
9388            } else if (dispatchGenericPointerEvent(event)) {
9389                return true;
9390            }
9391        } else if (dispatchGenericFocusedEvent(event)) {
9392            return true;
9393        }
9394
9395        if (dispatchGenericMotionEventInternal(event)) {
9396            return true;
9397        }
9398
9399        if (mInputEventConsistencyVerifier != null) {
9400            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9401        }
9402        return false;
9403    }
9404
9405    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
9406        //noinspection SimplifiableIfStatement
9407        ListenerInfo li = mListenerInfo;
9408        if (li != null && li.mOnGenericMotionListener != null
9409                && (mViewFlags & ENABLED_MASK) == ENABLED
9410                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
9411            return true;
9412        }
9413
9414        if (onGenericMotionEvent(event)) {
9415            return true;
9416        }
9417
9418        final int actionButton = event.getActionButton();
9419        switch (event.getActionMasked()) {
9420            case MotionEvent.ACTION_BUTTON_PRESS:
9421                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
9422                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
9423                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
9424                    if (performContextClick()) {
9425                        mInContextButtonPress = true;
9426                        setPressed(true, event.getX(), event.getY());
9427                        removeTapCallback();
9428                        removeLongPressCallback();
9429                        return true;
9430                    }
9431                }
9432                break;
9433
9434            case MotionEvent.ACTION_BUTTON_RELEASE:
9435                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
9436                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
9437                    mInContextButtonPress = false;
9438                    mIgnoreNextUpEvent = true;
9439                }
9440                break;
9441        }
9442
9443        if (mInputEventConsistencyVerifier != null) {
9444            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9445        }
9446        return false;
9447    }
9448
9449    /**
9450     * Dispatch a hover event.
9451     * <p>
9452     * Do not call this method directly.
9453     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9454     * </p>
9455     *
9456     * @param event The motion event to be dispatched.
9457     * @return True if the event was handled by the view, false otherwise.
9458     */
9459    protected boolean dispatchHoverEvent(MotionEvent event) {
9460        ListenerInfo li = mListenerInfo;
9461        //noinspection SimplifiableIfStatement
9462        if (li != null && li.mOnHoverListener != null
9463                && (mViewFlags & ENABLED_MASK) == ENABLED
9464                && li.mOnHoverListener.onHover(this, event)) {
9465            return true;
9466        }
9467
9468        return onHoverEvent(event);
9469    }
9470
9471    /**
9472     * Returns true if the view has a child to which it has recently sent
9473     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
9474     * it does not have a hovered child, then it must be the innermost hovered view.
9475     * @hide
9476     */
9477    protected boolean hasHoveredChild() {
9478        return false;
9479    }
9480
9481    /**
9482     * Dispatch a generic motion event to the view under the first pointer.
9483     * <p>
9484     * Do not call this method directly.
9485     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9486     * </p>
9487     *
9488     * @param event The motion event to be dispatched.
9489     * @return True if the event was handled by the view, false otherwise.
9490     */
9491    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
9492        return false;
9493    }
9494
9495    /**
9496     * Dispatch a generic motion event to the currently focused view.
9497     * <p>
9498     * Do not call this method directly.
9499     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9500     * </p>
9501     *
9502     * @param event The motion event to be dispatched.
9503     * @return True if the event was handled by the view, false otherwise.
9504     */
9505    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
9506        return false;
9507    }
9508
9509    /**
9510     * Dispatch a pointer event.
9511     * <p>
9512     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
9513     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
9514     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
9515     * and should not be expected to handle other pointing device features.
9516     * </p>
9517     *
9518     * @param event The motion event to be dispatched.
9519     * @return True if the event was handled by the view, false otherwise.
9520     * @hide
9521     */
9522    public final boolean dispatchPointerEvent(MotionEvent event) {
9523        if (event.isTouchEvent()) {
9524            return dispatchTouchEvent(event);
9525        } else {
9526            return dispatchGenericMotionEvent(event);
9527        }
9528    }
9529
9530    /**
9531     * Called when the window containing this view gains or loses window focus.
9532     * ViewGroups should override to route to their children.
9533     *
9534     * @param hasFocus True if the window containing this view now has focus,
9535     *        false otherwise.
9536     */
9537    public void dispatchWindowFocusChanged(boolean hasFocus) {
9538        onWindowFocusChanged(hasFocus);
9539    }
9540
9541    /**
9542     * Called when the window containing this view gains or loses focus.  Note
9543     * that this is separate from view focus: to receive key events, both
9544     * your view and its window must have focus.  If a window is displayed
9545     * on top of yours that takes input focus, then your own window will lose
9546     * focus but the view focus will remain unchanged.
9547     *
9548     * @param hasWindowFocus True if the window containing this view now has
9549     *        focus, false otherwise.
9550     */
9551    public void onWindowFocusChanged(boolean hasWindowFocus) {
9552        InputMethodManager imm = InputMethodManager.peekInstance();
9553        if (!hasWindowFocus) {
9554            if (isPressed()) {
9555                setPressed(false);
9556            }
9557            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9558                imm.focusOut(this);
9559            }
9560            removeLongPressCallback();
9561            removeTapCallback();
9562            onFocusLost();
9563        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9564            imm.focusIn(this);
9565        }
9566        refreshDrawableState();
9567    }
9568
9569    /**
9570     * Returns true if this view is in a window that currently has window focus.
9571     * Note that this is not the same as the view itself having focus.
9572     *
9573     * @return True if this view is in a window that currently has window focus.
9574     */
9575    public boolean hasWindowFocus() {
9576        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
9577    }
9578
9579    /**
9580     * Dispatch a view visibility change down the view hierarchy.
9581     * ViewGroups should override to route to their children.
9582     * @param changedView The view whose visibility changed. Could be 'this' or
9583     * an ancestor view.
9584     * @param visibility The new visibility of changedView: {@link #VISIBLE},
9585     * {@link #INVISIBLE} or {@link #GONE}.
9586     */
9587    protected void dispatchVisibilityChanged(@NonNull View changedView,
9588            @Visibility int visibility) {
9589        onVisibilityChanged(changedView, visibility);
9590    }
9591
9592    /**
9593     * Called when the visibility of the view or an ancestor of the view has
9594     * changed.
9595     *
9596     * @param changedView The view whose visibility changed. May be
9597     *                    {@code this} or an ancestor view.
9598     * @param visibility The new visibility, one of {@link #VISIBLE},
9599     *                   {@link #INVISIBLE} or {@link #GONE}.
9600     */
9601    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
9602        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
9603        if (visible && mAttachInfo != null) {
9604            initialAwakenScrollBars();
9605        }
9606
9607        final Drawable dr = mBackground;
9608        if (dr != null && visible != dr.isVisible()) {
9609            dr.setVisible(visible, false);
9610        }
9611        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
9612        if (fg != null && visible != fg.isVisible()) {
9613            fg.setVisible(visible, false);
9614        }
9615    }
9616
9617    /**
9618     * Dispatch a hint about whether this view is displayed. For instance, when
9619     * a View moves out of the screen, it might receives a display hint indicating
9620     * the view is not displayed. Applications should not <em>rely</em> on this hint
9621     * as there is no guarantee that they will receive one.
9622     *
9623     * @param hint A hint about whether or not this view is displayed:
9624     * {@link #VISIBLE} or {@link #INVISIBLE}.
9625     */
9626    public void dispatchDisplayHint(@Visibility int hint) {
9627        onDisplayHint(hint);
9628    }
9629
9630    /**
9631     * Gives this view a hint about whether is displayed or not. For instance, when
9632     * a View moves out of the screen, it might receives a display hint indicating
9633     * the view is not displayed. Applications should not <em>rely</em> on this hint
9634     * as there is no guarantee that they will receive one.
9635     *
9636     * @param hint A hint about whether or not this view is displayed:
9637     * {@link #VISIBLE} or {@link #INVISIBLE}.
9638     */
9639    protected void onDisplayHint(@Visibility int hint) {
9640    }
9641
9642    /**
9643     * Dispatch a window visibility change down the view hierarchy.
9644     * ViewGroups should override to route to their children.
9645     *
9646     * @param visibility The new visibility of the window.
9647     *
9648     * @see #onWindowVisibilityChanged(int)
9649     */
9650    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
9651        onWindowVisibilityChanged(visibility);
9652    }
9653
9654    /**
9655     * Called when the window containing has change its visibility
9656     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
9657     * that this tells you whether or not your window is being made visible
9658     * to the window manager; this does <em>not</em> tell you whether or not
9659     * your window is obscured by other windows on the screen, even if it
9660     * is itself visible.
9661     *
9662     * @param visibility The new visibility of the window.
9663     */
9664    protected void onWindowVisibilityChanged(@Visibility int visibility) {
9665        if (visibility == VISIBLE) {
9666            initialAwakenScrollBars();
9667        }
9668    }
9669
9670    /**
9671     * Returns the current visibility of the window this view is attached to
9672     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
9673     *
9674     * @return Returns the current visibility of the view's window.
9675     */
9676    @Visibility
9677    public int getWindowVisibility() {
9678        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
9679    }
9680
9681    /**
9682     * Retrieve the overall visible display size in which the window this view is
9683     * attached to has been positioned in.  This takes into account screen
9684     * decorations above the window, for both cases where the window itself
9685     * is being position inside of them or the window is being placed under
9686     * then and covered insets are used for the window to position its content
9687     * inside.  In effect, this tells you the available area where content can
9688     * be placed and remain visible to users.
9689     *
9690     * <p>This function requires an IPC back to the window manager to retrieve
9691     * the requested information, so should not be used in performance critical
9692     * code like drawing.
9693     *
9694     * @param outRect Filled in with the visible display frame.  If the view
9695     * is not attached to a window, this is simply the raw display size.
9696     */
9697    public void getWindowVisibleDisplayFrame(Rect outRect) {
9698        if (mAttachInfo != null) {
9699            try {
9700                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
9701            } catch (RemoteException e) {
9702                return;
9703            }
9704            // XXX This is really broken, and probably all needs to be done
9705            // in the window manager, and we need to know more about whether
9706            // we want the area behind or in front of the IME.
9707            final Rect insets = mAttachInfo.mVisibleInsets;
9708            outRect.left += insets.left;
9709            outRect.top += insets.top;
9710            outRect.right -= insets.right;
9711            outRect.bottom -= insets.bottom;
9712            return;
9713        }
9714        // The view is not attached to a display so we don't have a context.
9715        // Make a best guess about the display size.
9716        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
9717        d.getRectSize(outRect);
9718    }
9719
9720    /**
9721     * Dispatch a notification about a resource configuration change down
9722     * the view hierarchy.
9723     * ViewGroups should override to route to their children.
9724     *
9725     * @param newConfig The new resource configuration.
9726     *
9727     * @see #onConfigurationChanged(android.content.res.Configuration)
9728     */
9729    public void dispatchConfigurationChanged(Configuration newConfig) {
9730        onConfigurationChanged(newConfig);
9731    }
9732
9733    /**
9734     * Called when the current configuration of the resources being used
9735     * by the application have changed.  You can use this to decide when
9736     * to reload resources that can changed based on orientation and other
9737     * configuration characteristics.  You only need to use this if you are
9738     * not relying on the normal {@link android.app.Activity} mechanism of
9739     * recreating the activity instance upon a configuration change.
9740     *
9741     * @param newConfig The new resource configuration.
9742     */
9743    protected void onConfigurationChanged(Configuration newConfig) {
9744    }
9745
9746    /**
9747     * Private function to aggregate all per-view attributes in to the view
9748     * root.
9749     */
9750    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9751        performCollectViewAttributes(attachInfo, visibility);
9752    }
9753
9754    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9755        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
9756            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
9757                attachInfo.mKeepScreenOn = true;
9758            }
9759            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
9760            ListenerInfo li = mListenerInfo;
9761            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
9762                attachInfo.mHasSystemUiListeners = true;
9763            }
9764        }
9765    }
9766
9767    void needGlobalAttributesUpdate(boolean force) {
9768        final AttachInfo ai = mAttachInfo;
9769        if (ai != null && !ai.mRecomputeGlobalAttributes) {
9770            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
9771                    || ai.mHasSystemUiListeners) {
9772                ai.mRecomputeGlobalAttributes = true;
9773            }
9774        }
9775    }
9776
9777    /**
9778     * Returns whether the device is currently in touch mode.  Touch mode is entered
9779     * once the user begins interacting with the device by touch, and affects various
9780     * things like whether focus is always visible to the user.
9781     *
9782     * @return Whether the device is in touch mode.
9783     */
9784    @ViewDebug.ExportedProperty
9785    public boolean isInTouchMode() {
9786        if (mAttachInfo != null) {
9787            return mAttachInfo.mInTouchMode;
9788        } else {
9789            return ViewRootImpl.isInTouchMode();
9790        }
9791    }
9792
9793    /**
9794     * Returns the context the view is running in, through which it can
9795     * access the current theme, resources, etc.
9796     *
9797     * @return The view's Context.
9798     */
9799    @ViewDebug.CapturedViewProperty
9800    public final Context getContext() {
9801        return mContext;
9802    }
9803
9804    /**
9805     * Handle a key event before it is processed by any input method
9806     * associated with the view hierarchy.  This can be used to intercept
9807     * key events in special situations before the IME consumes them; a
9808     * typical example would be handling the BACK key to update the application's
9809     * UI instead of allowing the IME to see it and close itself.
9810     *
9811     * @param keyCode The value in event.getKeyCode().
9812     * @param event Description of the key event.
9813     * @return If you handled the event, return true. If you want to allow the
9814     *         event to be handled by the next receiver, return false.
9815     */
9816    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9817        return false;
9818    }
9819
9820    /**
9821     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9822     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9823     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9824     * is released, if the view is enabled and clickable.
9825     *
9826     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9827     * although some may elect to do so in some situations. Do not rely on this to
9828     * catch software key presses.
9829     *
9830     * @param keyCode A key code that represents the button pressed, from
9831     *                {@link android.view.KeyEvent}.
9832     * @param event   The KeyEvent object that defines the button action.
9833     */
9834    public boolean onKeyDown(int keyCode, KeyEvent event) {
9835        boolean result = false;
9836
9837        if (KeyEvent.isConfirmKey(keyCode)) {
9838            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9839                return true;
9840            }
9841            // Long clickable items don't necessarily have to be clickable
9842            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9843                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9844                    (event.getRepeatCount() == 0)) {
9845                setPressed(true);
9846                checkForLongClick(0);
9847                return true;
9848            }
9849        }
9850        return result;
9851    }
9852
9853    /**
9854     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9855     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9856     * the event).
9857     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9858     * although some may elect to do so in some situations. Do not rely on this to
9859     * catch software key presses.
9860     */
9861    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9862        return false;
9863    }
9864
9865    /**
9866     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9867     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9868     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9869     * {@link KeyEvent#KEYCODE_ENTER} is released.
9870     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9871     * although some may elect to do so in some situations. Do not rely on this to
9872     * catch software key presses.
9873     *
9874     * @param keyCode A key code that represents the button pressed, from
9875     *                {@link android.view.KeyEvent}.
9876     * @param event   The KeyEvent object that defines the button action.
9877     */
9878    public boolean onKeyUp(int keyCode, KeyEvent event) {
9879        if (KeyEvent.isConfirmKey(keyCode)) {
9880            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9881                return true;
9882            }
9883            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9884                setPressed(false);
9885
9886                if (!mHasPerformedLongPress) {
9887                    // This is a tap, so remove the longpress check
9888                    removeLongPressCallback();
9889                    return performClick();
9890                }
9891            }
9892        }
9893        return false;
9894    }
9895
9896    /**
9897     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9898     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9899     * the event).
9900     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9901     * although some may elect to do so in some situations. Do not rely on this to
9902     * catch software key presses.
9903     *
9904     * @param keyCode     A key code that represents the button pressed, from
9905     *                    {@link android.view.KeyEvent}.
9906     * @param repeatCount The number of times the action was made.
9907     * @param event       The KeyEvent object that defines the button action.
9908     */
9909    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9910        return false;
9911    }
9912
9913    /**
9914     * Called on the focused view when a key shortcut event is not handled.
9915     * Override this method to implement local key shortcuts for the View.
9916     * Key shortcuts can also be implemented by setting the
9917     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9918     *
9919     * @param keyCode The value in event.getKeyCode().
9920     * @param event Description of the key event.
9921     * @return If you handled the event, return true. If you want to allow the
9922     *         event to be handled by the next receiver, return false.
9923     */
9924    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9925        return false;
9926    }
9927
9928    /**
9929     * Check whether the called view is a text editor, in which case it
9930     * would make sense to automatically display a soft input window for
9931     * it.  Subclasses should override this if they implement
9932     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9933     * a call on that method would return a non-null InputConnection, and
9934     * they are really a first-class editor that the user would normally
9935     * start typing on when the go into a window containing your view.
9936     *
9937     * <p>The default implementation always returns false.  This does
9938     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9939     * will not be called or the user can not otherwise perform edits on your
9940     * view; it is just a hint to the system that this is not the primary
9941     * purpose of this view.
9942     *
9943     * @return Returns true if this view is a text editor, else false.
9944     */
9945    public boolean onCheckIsTextEditor() {
9946        return false;
9947    }
9948
9949    /**
9950     * Create a new InputConnection for an InputMethod to interact
9951     * with the view.  The default implementation returns null, since it doesn't
9952     * support input methods.  You can override this to implement such support.
9953     * This is only needed for views that take focus and text input.
9954     *
9955     * <p>When implementing this, you probably also want to implement
9956     * {@link #onCheckIsTextEditor()} to indicate you will return a
9957     * non-null InputConnection.</p>
9958     *
9959     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9960     * object correctly and in its entirety, so that the connected IME can rely
9961     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9962     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9963     * must be filled in with the correct cursor position for IMEs to work correctly
9964     * with your application.</p>
9965     *
9966     * @param outAttrs Fill in with attribute information about the connection.
9967     */
9968    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9969        return null;
9970    }
9971
9972    /**
9973     * Called by the {@link android.view.inputmethod.InputMethodManager}
9974     * when a view who is not the current
9975     * input connection target is trying to make a call on the manager.  The
9976     * default implementation returns false; you can override this to return
9977     * true for certain views if you are performing InputConnection proxying
9978     * to them.
9979     * @param view The View that is making the InputMethodManager call.
9980     * @return Return true to allow the call, false to reject.
9981     */
9982    public boolean checkInputConnectionProxy(View view) {
9983        return false;
9984    }
9985
9986    /**
9987     * Show the context menu for this view. It is not safe to hold on to the
9988     * menu after returning from this method.
9989     *
9990     * You should normally not overload this method. Overload
9991     * {@link #onCreateContextMenu(ContextMenu)} or define an
9992     * {@link OnCreateContextMenuListener} to add items to the context menu.
9993     *
9994     * @param menu The context menu to populate
9995     */
9996    public void createContextMenu(ContextMenu menu) {
9997        ContextMenuInfo menuInfo = getContextMenuInfo();
9998
9999        // Sets the current menu info so all items added to menu will have
10000        // my extra info set.
10001        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10002
10003        onCreateContextMenu(menu);
10004        ListenerInfo li = mListenerInfo;
10005        if (li != null && li.mOnCreateContextMenuListener != null) {
10006            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10007        }
10008
10009        // Clear the extra information so subsequent items that aren't mine don't
10010        // have my extra info.
10011        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10012
10013        if (mParent != null) {
10014            mParent.createContextMenu(menu);
10015        }
10016    }
10017
10018    /**
10019     * Views should implement this if they have extra information to associate
10020     * with the context menu. The return result is supplied as a parameter to
10021     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10022     * callback.
10023     *
10024     * @return Extra information about the item for which the context menu
10025     *         should be shown. This information will vary across different
10026     *         subclasses of View.
10027     */
10028    protected ContextMenuInfo getContextMenuInfo() {
10029        return null;
10030    }
10031
10032    /**
10033     * Views should implement this if the view itself is going to add items to
10034     * the context menu.
10035     *
10036     * @param menu the context menu to populate
10037     */
10038    protected void onCreateContextMenu(ContextMenu menu) {
10039    }
10040
10041    /**
10042     * Implement this method to handle trackball motion events.  The
10043     * <em>relative</em> movement of the trackball since the last event
10044     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10045     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10046     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10047     * they will often be fractional values, representing the more fine-grained
10048     * movement information available from a trackball).
10049     *
10050     * @param event The motion event.
10051     * @return True if the event was handled, false otherwise.
10052     */
10053    public boolean onTrackballEvent(MotionEvent event) {
10054        return false;
10055    }
10056
10057    /**
10058     * Implement this method to handle generic motion events.
10059     * <p>
10060     * Generic motion events describe joystick movements, mouse hovers, track pad
10061     * touches, scroll wheel movements and other input events.  The
10062     * {@link MotionEvent#getSource() source} of the motion event specifies
10063     * the class of input that was received.  Implementations of this method
10064     * must examine the bits in the source before processing the event.
10065     * The following code example shows how this is done.
10066     * </p><p>
10067     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10068     * are delivered to the view under the pointer.  All other generic motion events are
10069     * delivered to the focused view.
10070     * </p>
10071     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10072     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10073     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10074     *             // process the joystick movement...
10075     *             return true;
10076     *         }
10077     *     }
10078     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10079     *         switch (event.getAction()) {
10080     *             case MotionEvent.ACTION_HOVER_MOVE:
10081     *                 // process the mouse hover movement...
10082     *                 return true;
10083     *             case MotionEvent.ACTION_SCROLL:
10084     *                 // process the scroll wheel movement...
10085     *                 return true;
10086     *         }
10087     *     }
10088     *     return super.onGenericMotionEvent(event);
10089     * }</pre>
10090     *
10091     * @param event The generic motion event being processed.
10092     * @return True if the event was handled, false otherwise.
10093     */
10094    public boolean onGenericMotionEvent(MotionEvent event) {
10095        return false;
10096    }
10097
10098    /**
10099     * Implement this method to handle hover events.
10100     * <p>
10101     * This method is called whenever a pointer is hovering into, over, or out of the
10102     * bounds of a view and the view is not currently being touched.
10103     * Hover events are represented as pointer events with action
10104     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10105     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10106     * </p>
10107     * <ul>
10108     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10109     * when the pointer enters the bounds of the view.</li>
10110     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10111     * when the pointer has already entered the bounds of the view and has moved.</li>
10112     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10113     * when the pointer has exited the bounds of the view or when the pointer is
10114     * about to go down due to a button click, tap, or similar user action that
10115     * causes the view to be touched.</li>
10116     * </ul>
10117     * <p>
10118     * The view should implement this method to return true to indicate that it is
10119     * handling the hover event, such as by changing its drawable state.
10120     * </p><p>
10121     * The default implementation calls {@link #setHovered} to update the hovered state
10122     * of the view when a hover enter or hover exit event is received, if the view
10123     * is enabled and is clickable.  The default implementation also sends hover
10124     * accessibility events.
10125     * </p>
10126     *
10127     * @param event The motion event that describes the hover.
10128     * @return True if the view handled the hover event.
10129     *
10130     * @see #isHovered
10131     * @see #setHovered
10132     * @see #onHoverChanged
10133     */
10134    public boolean onHoverEvent(MotionEvent event) {
10135        // The root view may receive hover (or touch) events that are outside the bounds of
10136        // the window.  This code ensures that we only send accessibility events for
10137        // hovers that are actually within the bounds of the root view.
10138        final int action = event.getActionMasked();
10139        if (!mSendingHoverAccessibilityEvents) {
10140            if ((action == MotionEvent.ACTION_HOVER_ENTER
10141                    || action == MotionEvent.ACTION_HOVER_MOVE)
10142                    && !hasHoveredChild()
10143                    && pointInView(event.getX(), event.getY())) {
10144                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10145                mSendingHoverAccessibilityEvents = true;
10146            }
10147        } else {
10148            if (action == MotionEvent.ACTION_HOVER_EXIT
10149                    || (action == MotionEvent.ACTION_MOVE
10150                            && !pointInView(event.getX(), event.getY()))) {
10151                mSendingHoverAccessibilityEvents = false;
10152                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10153            }
10154        }
10155
10156        if (isHoverable()) {
10157            switch (action) {
10158                case MotionEvent.ACTION_HOVER_ENTER:
10159                    setHovered(true);
10160                    break;
10161                case MotionEvent.ACTION_HOVER_EXIT:
10162                    setHovered(false);
10163                    break;
10164            }
10165
10166            // Dispatch the event to onGenericMotionEvent before returning true.
10167            // This is to provide compatibility with existing applications that
10168            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10169            // break because of the new default handling for hoverable views
10170            // in onHoverEvent.
10171            // Note that onGenericMotionEvent will be called by default when
10172            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10173            dispatchGenericMotionEventInternal(event);
10174            // The event was already handled by calling setHovered(), so always
10175            // return true.
10176            return true;
10177        }
10178
10179        return false;
10180    }
10181
10182    /**
10183     * Returns true if the view should handle {@link #onHoverEvent}
10184     * by calling {@link #setHovered} to change its hovered state.
10185     *
10186     * @return True if the view is hoverable.
10187     */
10188    private boolean isHoverable() {
10189        final int viewFlags = mViewFlags;
10190        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10191            return false;
10192        }
10193
10194        return (viewFlags & CLICKABLE) == CLICKABLE
10195                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10196                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10197    }
10198
10199    /**
10200     * Returns true if the view is currently hovered.
10201     *
10202     * @return True if the view is currently hovered.
10203     *
10204     * @see #setHovered
10205     * @see #onHoverChanged
10206     */
10207    @ViewDebug.ExportedProperty
10208    public boolean isHovered() {
10209        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10210    }
10211
10212    /**
10213     * Sets whether the view is currently hovered.
10214     * <p>
10215     * Calling this method also changes the drawable state of the view.  This
10216     * enables the view to react to hover by using different drawable resources
10217     * to change its appearance.
10218     * </p><p>
10219     * The {@link #onHoverChanged} method is called when the hovered state changes.
10220     * </p>
10221     *
10222     * @param hovered True if the view is hovered.
10223     *
10224     * @see #isHovered
10225     * @see #onHoverChanged
10226     */
10227    public void setHovered(boolean hovered) {
10228        if (hovered) {
10229            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10230                mPrivateFlags |= PFLAG_HOVERED;
10231                refreshDrawableState();
10232                onHoverChanged(true);
10233            }
10234        } else {
10235            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10236                mPrivateFlags &= ~PFLAG_HOVERED;
10237                refreshDrawableState();
10238                onHoverChanged(false);
10239            }
10240        }
10241    }
10242
10243    /**
10244     * Implement this method to handle hover state changes.
10245     * <p>
10246     * This method is called whenever the hover state changes as a result of a
10247     * call to {@link #setHovered}.
10248     * </p>
10249     *
10250     * @param hovered The current hover state, as returned by {@link #isHovered}.
10251     *
10252     * @see #isHovered
10253     * @see #setHovered
10254     */
10255    public void onHoverChanged(boolean hovered) {
10256    }
10257
10258    /**
10259     * Implement this method to handle touch screen motion events.
10260     * <p>
10261     * If this method is used to detect click actions, it is recommended that
10262     * the actions be performed by implementing and calling
10263     * {@link #performClick()}. This will ensure consistent system behavior,
10264     * including:
10265     * <ul>
10266     * <li>obeying click sound preferences
10267     * <li>dispatching OnClickListener calls
10268     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
10269     * accessibility features are enabled
10270     * </ul>
10271     *
10272     * @param event The motion event.
10273     * @return True if the event was handled, false otherwise.
10274     */
10275    public boolean onTouchEvent(MotionEvent event) {
10276        final float x = event.getX();
10277        final float y = event.getY();
10278        final int viewFlags = mViewFlags;
10279        final int action = event.getAction();
10280
10281        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10282            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
10283                setPressed(false);
10284            }
10285            // A disabled view that is clickable still consumes the touch
10286            // events, it just doesn't respond to them.
10287            return (((viewFlags & CLICKABLE) == CLICKABLE
10288                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10289                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
10290        }
10291
10292        if (mTouchDelegate != null) {
10293            if (mTouchDelegate.onTouchEvent(event)) {
10294                return true;
10295            }
10296        }
10297
10298        if (((viewFlags & CLICKABLE) == CLICKABLE ||
10299                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
10300                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
10301            switch (action) {
10302                case MotionEvent.ACTION_UP:
10303                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
10304                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
10305                        // take focus if we don't have it already and we should in
10306                        // touch mode.
10307                        boolean focusTaken = false;
10308                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
10309                            focusTaken = requestFocus();
10310                        }
10311
10312                        if (prepressed) {
10313                            // The button is being released before we actually
10314                            // showed it as pressed.  Make it show the pressed
10315                            // state now (before scheduling the click) to ensure
10316                            // the user sees it.
10317                            setPressed(true, x, y);
10318                       }
10319
10320                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
10321                            // This is a tap, so remove the longpress check
10322                            removeLongPressCallback();
10323
10324                            // Only perform take click actions if we were in the pressed state
10325                            if (!focusTaken) {
10326                                // Use a Runnable and post this rather than calling
10327                                // performClick directly. This lets other visual state
10328                                // of the view update before click actions start.
10329                                if (mPerformClick == null) {
10330                                    mPerformClick = new PerformClick();
10331                                }
10332                                if (!post(mPerformClick)) {
10333                                    performClick();
10334                                }
10335                            }
10336                        }
10337
10338                        if (mUnsetPressedState == null) {
10339                            mUnsetPressedState = new UnsetPressedState();
10340                        }
10341
10342                        if (prepressed) {
10343                            postDelayed(mUnsetPressedState,
10344                                    ViewConfiguration.getPressedStateDuration());
10345                        } else if (!post(mUnsetPressedState)) {
10346                            // If the post failed, unpress right now
10347                            mUnsetPressedState.run();
10348                        }
10349
10350                        removeTapCallback();
10351                    }
10352                    mIgnoreNextUpEvent = false;
10353                    break;
10354
10355                case MotionEvent.ACTION_DOWN:
10356                    mHasPerformedLongPress = false;
10357
10358                    if (performButtonActionOnTouchDown(event)) {
10359                        break;
10360                    }
10361
10362                    // Walk up the hierarchy to determine if we're inside a scrolling container.
10363                    boolean isInScrollingContainer = isInScrollingContainer();
10364
10365                    // For views inside a scrolling container, delay the pressed feedback for
10366                    // a short period in case this is a scroll.
10367                    if (isInScrollingContainer) {
10368                        mPrivateFlags |= PFLAG_PREPRESSED;
10369                        if (mPendingCheckForTap == null) {
10370                            mPendingCheckForTap = new CheckForTap();
10371                        }
10372                        mPendingCheckForTap.x = event.getX();
10373                        mPendingCheckForTap.y = event.getY();
10374                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
10375                    } else {
10376                        // Not inside a scrolling container, so show the feedback right away
10377                        setPressed(true, x, y);
10378                        checkForLongClick(0);
10379                    }
10380                    break;
10381
10382                case MotionEvent.ACTION_CANCEL:
10383                    setPressed(false);
10384                    removeTapCallback();
10385                    removeLongPressCallback();
10386                    mInContextButtonPress = false;
10387                    mHasPerformedLongPress = false;
10388                    mIgnoreNextUpEvent = false;
10389                    break;
10390
10391                case MotionEvent.ACTION_MOVE:
10392                    drawableHotspotChanged(x, y);
10393
10394                    // Be lenient about moving outside of buttons
10395                    if (!pointInView(x, y, mTouchSlop)) {
10396                        // Outside button
10397                        removeTapCallback();
10398                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
10399                            // Remove any future long press/tap checks
10400                            removeLongPressCallback();
10401
10402                            setPressed(false);
10403                        }
10404                    }
10405                    break;
10406            }
10407
10408            return true;
10409        }
10410
10411        return false;
10412    }
10413
10414    /**
10415     * @hide
10416     */
10417    public boolean isInScrollingContainer() {
10418        ViewParent p = getParent();
10419        while (p != null && p instanceof ViewGroup) {
10420            if (((ViewGroup) p).shouldDelayChildPressedState()) {
10421                return true;
10422            }
10423            p = p.getParent();
10424        }
10425        return false;
10426    }
10427
10428    /**
10429     * Remove the longpress detection timer.
10430     */
10431    private void removeLongPressCallback() {
10432        if (mPendingCheckForLongPress != null) {
10433          removeCallbacks(mPendingCheckForLongPress);
10434        }
10435    }
10436
10437    /**
10438     * Remove the pending click action
10439     */
10440    private void removePerformClickCallback() {
10441        if (mPerformClick != null) {
10442            removeCallbacks(mPerformClick);
10443        }
10444    }
10445
10446    /**
10447     * Remove the prepress detection timer.
10448     */
10449    private void removeUnsetPressCallback() {
10450        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
10451            setPressed(false);
10452            removeCallbacks(mUnsetPressedState);
10453        }
10454    }
10455
10456    /**
10457     * Remove the tap detection timer.
10458     */
10459    private void removeTapCallback() {
10460        if (mPendingCheckForTap != null) {
10461            mPrivateFlags &= ~PFLAG_PREPRESSED;
10462            removeCallbacks(mPendingCheckForTap);
10463        }
10464    }
10465
10466    /**
10467     * Cancels a pending long press.  Your subclass can use this if you
10468     * want the context menu to come up if the user presses and holds
10469     * at the same place, but you don't want it to come up if they press
10470     * and then move around enough to cause scrolling.
10471     */
10472    public void cancelLongPress() {
10473        removeLongPressCallback();
10474
10475        /*
10476         * The prepressed state handled by the tap callback is a display
10477         * construct, but the tap callback will post a long press callback
10478         * less its own timeout. Remove it here.
10479         */
10480        removeTapCallback();
10481    }
10482
10483    /**
10484     * Remove the pending callback for sending a
10485     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
10486     */
10487    private void removeSendViewScrolledAccessibilityEventCallback() {
10488        if (mSendViewScrolledAccessibilityEvent != null) {
10489            removeCallbacks(mSendViewScrolledAccessibilityEvent);
10490            mSendViewScrolledAccessibilityEvent.mIsPending = false;
10491        }
10492    }
10493
10494    /**
10495     * Sets the TouchDelegate for this View.
10496     */
10497    public void setTouchDelegate(TouchDelegate delegate) {
10498        mTouchDelegate = delegate;
10499    }
10500
10501    /**
10502     * Gets the TouchDelegate for this View.
10503     */
10504    public TouchDelegate getTouchDelegate() {
10505        return mTouchDelegate;
10506    }
10507
10508    /**
10509     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
10510     *
10511     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
10512     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
10513     * available. This method should only be called for touch events.
10514     *
10515     * <p class="note">This api is not intended for most applications. Buffered dispatch
10516     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
10517     * streams will not improve your input latency. Side effects include: increased latency,
10518     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
10519     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
10520     * you.</p>
10521     */
10522    public final void requestUnbufferedDispatch(MotionEvent event) {
10523        final int action = event.getAction();
10524        if (mAttachInfo == null
10525                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
10526                || !event.isTouchEvent()) {
10527            return;
10528        }
10529        mAttachInfo.mUnbufferedDispatchRequested = true;
10530    }
10531
10532    /**
10533     * Set flags controlling behavior of this view.
10534     *
10535     * @param flags Constant indicating the value which should be set
10536     * @param mask Constant indicating the bit range that should be changed
10537     */
10538    void setFlags(int flags, int mask) {
10539        final boolean accessibilityEnabled =
10540                AccessibilityManager.getInstance(mContext).isEnabled();
10541        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
10542
10543        int old = mViewFlags;
10544        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
10545
10546        int changed = mViewFlags ^ old;
10547        if (changed == 0) {
10548            return;
10549        }
10550        int privateFlags = mPrivateFlags;
10551
10552        /* Check if the FOCUSABLE bit has changed */
10553        if (((changed & FOCUSABLE_MASK) != 0) &&
10554                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
10555            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
10556                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
10557                /* Give up focus if we are no longer focusable */
10558                clearFocus();
10559            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
10560                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
10561                /*
10562                 * Tell the view system that we are now available to take focus
10563                 * if no one else already has it.
10564                 */
10565                if (mParent != null) mParent.focusableViewAvailable(this);
10566            }
10567        }
10568
10569        final int newVisibility = flags & VISIBILITY_MASK;
10570        if (newVisibility == VISIBLE) {
10571            if ((changed & VISIBILITY_MASK) != 0) {
10572                /*
10573                 * If this view is becoming visible, invalidate it in case it changed while
10574                 * it was not visible. Marking it drawn ensures that the invalidation will
10575                 * go through.
10576                 */
10577                mPrivateFlags |= PFLAG_DRAWN;
10578                invalidate(true);
10579
10580                needGlobalAttributesUpdate(true);
10581
10582                // a view becoming visible is worth notifying the parent
10583                // about in case nothing has focus.  even if this specific view
10584                // isn't focusable, it may contain something that is, so let
10585                // the root view try to give this focus if nothing else does.
10586                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
10587                    mParent.focusableViewAvailable(this);
10588                }
10589            }
10590        }
10591
10592        /* Check if the GONE bit has changed */
10593        if ((changed & GONE) != 0) {
10594            needGlobalAttributesUpdate(false);
10595            requestLayout();
10596
10597            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
10598                if (hasFocus()) clearFocus();
10599                clearAccessibilityFocus();
10600                destroyDrawingCache();
10601                if (mParent instanceof View) {
10602                    // GONE views noop invalidation, so invalidate the parent
10603                    ((View) mParent).invalidate(true);
10604                }
10605                // Mark the view drawn to ensure that it gets invalidated properly the next
10606                // time it is visible and gets invalidated
10607                mPrivateFlags |= PFLAG_DRAWN;
10608            }
10609            if (mAttachInfo != null) {
10610                mAttachInfo.mViewVisibilityChanged = true;
10611            }
10612        }
10613
10614        /* Check if the VISIBLE bit has changed */
10615        if ((changed & INVISIBLE) != 0) {
10616            needGlobalAttributesUpdate(false);
10617            /*
10618             * If this view is becoming invisible, set the DRAWN flag so that
10619             * the next invalidate() will not be skipped.
10620             */
10621            mPrivateFlags |= PFLAG_DRAWN;
10622
10623            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
10624                // root view becoming invisible shouldn't clear focus and accessibility focus
10625                if (getRootView() != this) {
10626                    if (hasFocus()) clearFocus();
10627                    clearAccessibilityFocus();
10628                }
10629            }
10630            if (mAttachInfo != null) {
10631                mAttachInfo.mViewVisibilityChanged = true;
10632            }
10633        }
10634
10635        if ((changed & VISIBILITY_MASK) != 0) {
10636            // If the view is invisible, cleanup its display list to free up resources
10637            if (newVisibility != VISIBLE && mAttachInfo != null) {
10638                cleanupDraw();
10639            }
10640
10641            if (mParent instanceof ViewGroup) {
10642                ((ViewGroup) mParent).onChildVisibilityChanged(this,
10643                        (changed & VISIBILITY_MASK), newVisibility);
10644                ((View) mParent).invalidate(true);
10645            } else if (mParent != null) {
10646                mParent.invalidateChild(this, null);
10647            }
10648
10649            if (mAttachInfo != null) {
10650                dispatchVisibilityChanged(this, newVisibility);
10651                notifySubtreeAccessibilityStateChangedIfNeeded();
10652            }
10653        }
10654
10655        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
10656            destroyDrawingCache();
10657        }
10658
10659        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
10660            destroyDrawingCache();
10661            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10662            invalidateParentCaches();
10663        }
10664
10665        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
10666            destroyDrawingCache();
10667            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10668        }
10669
10670        if ((changed & DRAW_MASK) != 0) {
10671            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
10672                if (mBackground != null
10673                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
10674                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10675                } else {
10676                    mPrivateFlags |= PFLAG_SKIP_DRAW;
10677                }
10678            } else {
10679                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10680            }
10681            requestLayout();
10682            invalidate(true);
10683        }
10684
10685        if ((changed & KEEP_SCREEN_ON) != 0) {
10686            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10687                mParent.recomputeViewAttributes(this);
10688            }
10689        }
10690
10691        if (accessibilityEnabled) {
10692            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
10693                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
10694                    || (changed & CONTEXT_CLICKABLE) != 0) {
10695                if (oldIncludeForAccessibility != includeForAccessibility()) {
10696                    notifySubtreeAccessibilityStateChangedIfNeeded();
10697                } else {
10698                    notifyViewAccessibilityStateChangedIfNeeded(
10699                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10700                }
10701            } else if ((changed & ENABLED_MASK) != 0) {
10702                notifyViewAccessibilityStateChangedIfNeeded(
10703                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10704            }
10705        }
10706    }
10707
10708    /**
10709     * Change the view's z order in the tree, so it's on top of other sibling
10710     * views. This ordering change may affect layout, if the parent container
10711     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
10712     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
10713     * method should be followed by calls to {@link #requestLayout()} and
10714     * {@link View#invalidate()} on the view's parent to force the parent to redraw
10715     * with the new child ordering.
10716     *
10717     * @see ViewGroup#bringChildToFront(View)
10718     */
10719    public void bringToFront() {
10720        if (mParent != null) {
10721            mParent.bringChildToFront(this);
10722        }
10723    }
10724
10725    /**
10726     * This is called in response to an internal scroll in this view (i.e., the
10727     * view scrolled its own contents). This is typically as a result of
10728     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
10729     * called.
10730     *
10731     * @param l Current horizontal scroll origin.
10732     * @param t Current vertical scroll origin.
10733     * @param oldl Previous horizontal scroll origin.
10734     * @param oldt Previous vertical scroll origin.
10735     */
10736    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
10737        notifySubtreeAccessibilityStateChangedIfNeeded();
10738
10739        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10740            postSendViewScrolledAccessibilityEventCallback();
10741        }
10742
10743        mBackgroundSizeChanged = true;
10744        if (mForegroundInfo != null) {
10745            mForegroundInfo.mBoundsChanged = true;
10746        }
10747
10748        final AttachInfo ai = mAttachInfo;
10749        if (ai != null) {
10750            ai.mViewScrollChanged = true;
10751        }
10752
10753        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
10754            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
10755        }
10756    }
10757
10758    /**
10759     * Interface definition for a callback to be invoked when the scroll
10760     * X or Y positions of a view change.
10761     * <p>
10762     * <b>Note:</b> Some views handle scrolling independently from View and may
10763     * have their own separate listeners for scroll-type events. For example,
10764     * {@link android.widget.ListView ListView} allows clients to register an
10765     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
10766     * to listen for changes in list scroll position.
10767     *
10768     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
10769     */
10770    public interface OnScrollChangeListener {
10771        /**
10772         * Called when the scroll position of a view changes.
10773         *
10774         * @param v The view whose scroll position has changed.
10775         * @param scrollX Current horizontal scroll origin.
10776         * @param scrollY Current vertical scroll origin.
10777         * @param oldScrollX Previous horizontal scroll origin.
10778         * @param oldScrollY Previous vertical scroll origin.
10779         */
10780        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
10781    }
10782
10783    /**
10784     * Interface definition for a callback to be invoked when the layout bounds of a view
10785     * changes due to layout processing.
10786     */
10787    public interface OnLayoutChangeListener {
10788        /**
10789         * Called when the layout bounds of a view changes due to layout processing.
10790         *
10791         * @param v The view whose bounds have changed.
10792         * @param left The new value of the view's left property.
10793         * @param top The new value of the view's top property.
10794         * @param right The new value of the view's right property.
10795         * @param bottom The new value of the view's bottom property.
10796         * @param oldLeft The previous value of the view's left property.
10797         * @param oldTop The previous value of the view's top property.
10798         * @param oldRight The previous value of the view's right property.
10799         * @param oldBottom The previous value of the view's bottom property.
10800         */
10801        void onLayoutChange(View v, int left, int top, int right, int bottom,
10802            int oldLeft, int oldTop, int oldRight, int oldBottom);
10803    }
10804
10805    /**
10806     * This is called during layout when the size of this view has changed. If
10807     * you were just added to the view hierarchy, you're called with the old
10808     * values of 0.
10809     *
10810     * @param w Current width of this view.
10811     * @param h Current height of this view.
10812     * @param oldw Old width of this view.
10813     * @param oldh Old height of this view.
10814     */
10815    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10816    }
10817
10818    /**
10819     * Called by draw to draw the child views. This may be overridden
10820     * by derived classes to gain control just before its children are drawn
10821     * (but after its own view has been drawn).
10822     * @param canvas the canvas on which to draw the view
10823     */
10824    protected void dispatchDraw(Canvas canvas) {
10825
10826    }
10827
10828    /**
10829     * Gets the parent of this view. Note that the parent is a
10830     * ViewParent and not necessarily a View.
10831     *
10832     * @return Parent of this view.
10833     */
10834    public final ViewParent getParent() {
10835        return mParent;
10836    }
10837
10838    /**
10839     * Set the horizontal scrolled position of your view. This will cause a call to
10840     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10841     * invalidated.
10842     * @param value the x position to scroll to
10843     */
10844    public void setScrollX(int value) {
10845        scrollTo(value, mScrollY);
10846    }
10847
10848    /**
10849     * Set the vertical scrolled position of your view. This will cause a call to
10850     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10851     * invalidated.
10852     * @param value the y position to scroll to
10853     */
10854    public void setScrollY(int value) {
10855        scrollTo(mScrollX, value);
10856    }
10857
10858    /**
10859     * Return the scrolled left position of this view. This is the left edge of
10860     * the displayed part of your view. You do not need to draw any pixels
10861     * farther left, since those are outside of the frame of your view on
10862     * screen.
10863     *
10864     * @return The left edge of the displayed part of your view, in pixels.
10865     */
10866    public final int getScrollX() {
10867        return mScrollX;
10868    }
10869
10870    /**
10871     * Return the scrolled top position of this view. This is the top edge of
10872     * the displayed part of your view. You do not need to draw any pixels above
10873     * it, since those are outside of the frame of your view on screen.
10874     *
10875     * @return The top edge of the displayed part of your view, in pixels.
10876     */
10877    public final int getScrollY() {
10878        return mScrollY;
10879    }
10880
10881    /**
10882     * Return the width of the your view.
10883     *
10884     * @return The width of your view, in pixels.
10885     */
10886    @ViewDebug.ExportedProperty(category = "layout")
10887    public final int getWidth() {
10888        return mRight - mLeft;
10889    }
10890
10891    /**
10892     * Return the height of your view.
10893     *
10894     * @return The height of your view, in pixels.
10895     */
10896    @ViewDebug.ExportedProperty(category = "layout")
10897    public final int getHeight() {
10898        return mBottom - mTop;
10899    }
10900
10901    /**
10902     * Return the visible drawing bounds of your view. Fills in the output
10903     * rectangle with the values from getScrollX(), getScrollY(),
10904     * getWidth(), and getHeight(). These bounds do not account for any
10905     * transformation properties currently set on the view, such as
10906     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10907     *
10908     * @param outRect The (scrolled) drawing bounds of the view.
10909     */
10910    public void getDrawingRect(Rect outRect) {
10911        outRect.left = mScrollX;
10912        outRect.top = mScrollY;
10913        outRect.right = mScrollX + (mRight - mLeft);
10914        outRect.bottom = mScrollY + (mBottom - mTop);
10915    }
10916
10917    /**
10918     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10919     * raw width component (that is the result is masked by
10920     * {@link #MEASURED_SIZE_MASK}).
10921     *
10922     * @return The raw measured width of this view.
10923     */
10924    public final int getMeasuredWidth() {
10925        return mMeasuredWidth & MEASURED_SIZE_MASK;
10926    }
10927
10928    /**
10929     * Return the full width measurement information for this view as computed
10930     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10931     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10932     * This should be used during measurement and layout calculations only. Use
10933     * {@link #getWidth()} to see how wide a view is after layout.
10934     *
10935     * @return The measured width of this view as a bit mask.
10936     */
10937    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10938            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10939                    name = "MEASURED_STATE_TOO_SMALL"),
10940    })
10941    public final int getMeasuredWidthAndState() {
10942        return mMeasuredWidth;
10943    }
10944
10945    /**
10946     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10947     * raw width component (that is the result is masked by
10948     * {@link #MEASURED_SIZE_MASK}).
10949     *
10950     * @return The raw measured height of this view.
10951     */
10952    public final int getMeasuredHeight() {
10953        return mMeasuredHeight & MEASURED_SIZE_MASK;
10954    }
10955
10956    /**
10957     * Return the full height measurement information for this view as computed
10958     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10959     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10960     * This should be used during measurement and layout calculations only. Use
10961     * {@link #getHeight()} to see how wide a view is after layout.
10962     *
10963     * @return The measured width of this view as a bit mask.
10964     */
10965    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10966            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10967                    name = "MEASURED_STATE_TOO_SMALL"),
10968    })
10969    public final int getMeasuredHeightAndState() {
10970        return mMeasuredHeight;
10971    }
10972
10973    /**
10974     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10975     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10976     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10977     * and the height component is at the shifted bits
10978     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10979     */
10980    public final int getMeasuredState() {
10981        return (mMeasuredWidth&MEASURED_STATE_MASK)
10982                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10983                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10984    }
10985
10986    /**
10987     * The transform matrix of this view, which is calculated based on the current
10988     * rotation, scale, and pivot properties.
10989     *
10990     * @see #getRotation()
10991     * @see #getScaleX()
10992     * @see #getScaleY()
10993     * @see #getPivotX()
10994     * @see #getPivotY()
10995     * @return The current transform matrix for the view
10996     */
10997    public Matrix getMatrix() {
10998        ensureTransformationInfo();
10999        final Matrix matrix = mTransformationInfo.mMatrix;
11000        mRenderNode.getMatrix(matrix);
11001        return matrix;
11002    }
11003
11004    /**
11005     * Returns true if the transform matrix is the identity matrix.
11006     * Recomputes the matrix if necessary.
11007     *
11008     * @return True if the transform matrix is the identity matrix, false otherwise.
11009     */
11010    final boolean hasIdentityMatrix() {
11011        return mRenderNode.hasIdentityMatrix();
11012    }
11013
11014    void ensureTransformationInfo() {
11015        if (mTransformationInfo == null) {
11016            mTransformationInfo = new TransformationInfo();
11017        }
11018    }
11019
11020   /**
11021     * Utility method to retrieve the inverse of the current mMatrix property.
11022     * We cache the matrix to avoid recalculating it when transform properties
11023     * have not changed.
11024     *
11025     * @return The inverse of the current matrix of this view.
11026     * @hide
11027     */
11028    public final Matrix getInverseMatrix() {
11029        ensureTransformationInfo();
11030        if (mTransformationInfo.mInverseMatrix == null) {
11031            mTransformationInfo.mInverseMatrix = new Matrix();
11032        }
11033        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11034        mRenderNode.getInverseMatrix(matrix);
11035        return matrix;
11036    }
11037
11038    /**
11039     * Gets the distance along the Z axis from the camera to this view.
11040     *
11041     * @see #setCameraDistance(float)
11042     *
11043     * @return The distance along the Z axis.
11044     */
11045    public float getCameraDistance() {
11046        final float dpi = mResources.getDisplayMetrics().densityDpi;
11047        return -(mRenderNode.getCameraDistance() * dpi);
11048    }
11049
11050    /**
11051     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11052     * views are drawn) from the camera to this view. The camera's distance
11053     * affects 3D transformations, for instance rotations around the X and Y
11054     * axis. If the rotationX or rotationY properties are changed and this view is
11055     * large (more than half the size of the screen), it is recommended to always
11056     * use a camera distance that's greater than the height (X axis rotation) or
11057     * the width (Y axis rotation) of this view.</p>
11058     *
11059     * <p>The distance of the camera from the view plane can have an affect on the
11060     * perspective distortion of the view when it is rotated around the x or y axis.
11061     * For example, a large distance will result in a large viewing angle, and there
11062     * will not be much perspective distortion of the view as it rotates. A short
11063     * distance may cause much more perspective distortion upon rotation, and can
11064     * also result in some drawing artifacts if the rotated view ends up partially
11065     * behind the camera (which is why the recommendation is to use a distance at
11066     * least as far as the size of the view, if the view is to be rotated.)</p>
11067     *
11068     * <p>The distance is expressed in "depth pixels." The default distance depends
11069     * on the screen density. For instance, on a medium density display, the
11070     * default distance is 1280. On a high density display, the default distance
11071     * is 1920.</p>
11072     *
11073     * <p>If you want to specify a distance that leads to visually consistent
11074     * results across various densities, use the following formula:</p>
11075     * <pre>
11076     * float scale = context.getResources().getDisplayMetrics().density;
11077     * view.setCameraDistance(distance * scale);
11078     * </pre>
11079     *
11080     * <p>The density scale factor of a high density display is 1.5,
11081     * and 1920 = 1280 * 1.5.</p>
11082     *
11083     * @param distance The distance in "depth pixels", if negative the opposite
11084     *        value is used
11085     *
11086     * @see #setRotationX(float)
11087     * @see #setRotationY(float)
11088     */
11089    public void setCameraDistance(float distance) {
11090        final float dpi = mResources.getDisplayMetrics().densityDpi;
11091
11092        invalidateViewProperty(true, false);
11093        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11094        invalidateViewProperty(false, false);
11095
11096        invalidateParentIfNeededAndWasQuickRejected();
11097    }
11098
11099    /**
11100     * The degrees that the view is rotated around the pivot point.
11101     *
11102     * @see #setRotation(float)
11103     * @see #getPivotX()
11104     * @see #getPivotY()
11105     *
11106     * @return The degrees of rotation.
11107     */
11108    @ViewDebug.ExportedProperty(category = "drawing")
11109    public float getRotation() {
11110        return mRenderNode.getRotation();
11111    }
11112
11113    /**
11114     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11115     * result in clockwise rotation.
11116     *
11117     * @param rotation The degrees of rotation.
11118     *
11119     * @see #getRotation()
11120     * @see #getPivotX()
11121     * @see #getPivotY()
11122     * @see #setRotationX(float)
11123     * @see #setRotationY(float)
11124     *
11125     * @attr ref android.R.styleable#View_rotation
11126     */
11127    public void setRotation(float rotation) {
11128        if (rotation != getRotation()) {
11129            // Double-invalidation is necessary to capture view's old and new areas
11130            invalidateViewProperty(true, false);
11131            mRenderNode.setRotation(rotation);
11132            invalidateViewProperty(false, true);
11133
11134            invalidateParentIfNeededAndWasQuickRejected();
11135            notifySubtreeAccessibilityStateChangedIfNeeded();
11136        }
11137    }
11138
11139    /**
11140     * The degrees that the view is rotated around the vertical axis through the pivot point.
11141     *
11142     * @see #getPivotX()
11143     * @see #getPivotY()
11144     * @see #setRotationY(float)
11145     *
11146     * @return The degrees of Y rotation.
11147     */
11148    @ViewDebug.ExportedProperty(category = "drawing")
11149    public float getRotationY() {
11150        return mRenderNode.getRotationY();
11151    }
11152
11153    /**
11154     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11155     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11156     * down the y axis.
11157     *
11158     * When rotating large views, it is recommended to adjust the camera distance
11159     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11160     *
11161     * @param rotationY The degrees of Y rotation.
11162     *
11163     * @see #getRotationY()
11164     * @see #getPivotX()
11165     * @see #getPivotY()
11166     * @see #setRotation(float)
11167     * @see #setRotationX(float)
11168     * @see #setCameraDistance(float)
11169     *
11170     * @attr ref android.R.styleable#View_rotationY
11171     */
11172    public void setRotationY(float rotationY) {
11173        if (rotationY != getRotationY()) {
11174            invalidateViewProperty(true, false);
11175            mRenderNode.setRotationY(rotationY);
11176            invalidateViewProperty(false, true);
11177
11178            invalidateParentIfNeededAndWasQuickRejected();
11179            notifySubtreeAccessibilityStateChangedIfNeeded();
11180        }
11181    }
11182
11183    /**
11184     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11185     *
11186     * @see #getPivotX()
11187     * @see #getPivotY()
11188     * @see #setRotationX(float)
11189     *
11190     * @return The degrees of X rotation.
11191     */
11192    @ViewDebug.ExportedProperty(category = "drawing")
11193    public float getRotationX() {
11194        return mRenderNode.getRotationX();
11195    }
11196
11197    /**
11198     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
11199     * Increasing values result in clockwise rotation from the viewpoint of looking down the
11200     * x axis.
11201     *
11202     * When rotating large views, it is recommended to adjust the camera distance
11203     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11204     *
11205     * @param rotationX The degrees of X rotation.
11206     *
11207     * @see #getRotationX()
11208     * @see #getPivotX()
11209     * @see #getPivotY()
11210     * @see #setRotation(float)
11211     * @see #setRotationY(float)
11212     * @see #setCameraDistance(float)
11213     *
11214     * @attr ref android.R.styleable#View_rotationX
11215     */
11216    public void setRotationX(float rotationX) {
11217        if (rotationX != getRotationX()) {
11218            invalidateViewProperty(true, false);
11219            mRenderNode.setRotationX(rotationX);
11220            invalidateViewProperty(false, true);
11221
11222            invalidateParentIfNeededAndWasQuickRejected();
11223            notifySubtreeAccessibilityStateChangedIfNeeded();
11224        }
11225    }
11226
11227    /**
11228     * The amount that the view is scaled in x around the pivot point, as a proportion of
11229     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
11230     *
11231     * <p>By default, this is 1.0f.
11232     *
11233     * @see #getPivotX()
11234     * @see #getPivotY()
11235     * @return The scaling factor.
11236     */
11237    @ViewDebug.ExportedProperty(category = "drawing")
11238    public float getScaleX() {
11239        return mRenderNode.getScaleX();
11240    }
11241
11242    /**
11243     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
11244     * the view's unscaled width. A value of 1 means that no scaling is applied.
11245     *
11246     * @param scaleX The scaling factor.
11247     * @see #getPivotX()
11248     * @see #getPivotY()
11249     *
11250     * @attr ref android.R.styleable#View_scaleX
11251     */
11252    public void setScaleX(float scaleX) {
11253        if (scaleX != getScaleX()) {
11254            invalidateViewProperty(true, false);
11255            mRenderNode.setScaleX(scaleX);
11256            invalidateViewProperty(false, true);
11257
11258            invalidateParentIfNeededAndWasQuickRejected();
11259            notifySubtreeAccessibilityStateChangedIfNeeded();
11260        }
11261    }
11262
11263    /**
11264     * The amount that the view is scaled in y around the pivot point, as a proportion of
11265     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
11266     *
11267     * <p>By default, this is 1.0f.
11268     *
11269     * @see #getPivotX()
11270     * @see #getPivotY()
11271     * @return The scaling factor.
11272     */
11273    @ViewDebug.ExportedProperty(category = "drawing")
11274    public float getScaleY() {
11275        return mRenderNode.getScaleY();
11276    }
11277
11278    /**
11279     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
11280     * the view's unscaled width. A value of 1 means that no scaling is applied.
11281     *
11282     * @param scaleY The scaling factor.
11283     * @see #getPivotX()
11284     * @see #getPivotY()
11285     *
11286     * @attr ref android.R.styleable#View_scaleY
11287     */
11288    public void setScaleY(float scaleY) {
11289        if (scaleY != getScaleY()) {
11290            invalidateViewProperty(true, false);
11291            mRenderNode.setScaleY(scaleY);
11292            invalidateViewProperty(false, true);
11293
11294            invalidateParentIfNeededAndWasQuickRejected();
11295            notifySubtreeAccessibilityStateChangedIfNeeded();
11296        }
11297    }
11298
11299    /**
11300     * The x location of the point around which the view is {@link #setRotation(float) rotated}
11301     * and {@link #setScaleX(float) scaled}.
11302     *
11303     * @see #getRotation()
11304     * @see #getScaleX()
11305     * @see #getScaleY()
11306     * @see #getPivotY()
11307     * @return The x location of the pivot point.
11308     *
11309     * @attr ref android.R.styleable#View_transformPivotX
11310     */
11311    @ViewDebug.ExportedProperty(category = "drawing")
11312    public float getPivotX() {
11313        return mRenderNode.getPivotX();
11314    }
11315
11316    /**
11317     * Sets the x location of the point around which the view is
11318     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
11319     * By default, the pivot point is centered on the object.
11320     * Setting this property disables this behavior and causes the view to use only the
11321     * explicitly set pivotX and pivotY values.
11322     *
11323     * @param pivotX The x location of the pivot point.
11324     * @see #getRotation()
11325     * @see #getScaleX()
11326     * @see #getScaleY()
11327     * @see #getPivotY()
11328     *
11329     * @attr ref android.R.styleable#View_transformPivotX
11330     */
11331    public void setPivotX(float pivotX) {
11332        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
11333            invalidateViewProperty(true, false);
11334            mRenderNode.setPivotX(pivotX);
11335            invalidateViewProperty(false, true);
11336
11337            invalidateParentIfNeededAndWasQuickRejected();
11338        }
11339    }
11340
11341    /**
11342     * The y location of the point around which the view is {@link #setRotation(float) rotated}
11343     * and {@link #setScaleY(float) scaled}.
11344     *
11345     * @see #getRotation()
11346     * @see #getScaleX()
11347     * @see #getScaleY()
11348     * @see #getPivotY()
11349     * @return The y location of the pivot point.
11350     *
11351     * @attr ref android.R.styleable#View_transformPivotY
11352     */
11353    @ViewDebug.ExportedProperty(category = "drawing")
11354    public float getPivotY() {
11355        return mRenderNode.getPivotY();
11356    }
11357
11358    /**
11359     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
11360     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
11361     * Setting this property disables this behavior and causes the view to use only the
11362     * explicitly set pivotX and pivotY values.
11363     *
11364     * @param pivotY The y location of the pivot point.
11365     * @see #getRotation()
11366     * @see #getScaleX()
11367     * @see #getScaleY()
11368     * @see #getPivotY()
11369     *
11370     * @attr ref android.R.styleable#View_transformPivotY
11371     */
11372    public void setPivotY(float pivotY) {
11373        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
11374            invalidateViewProperty(true, false);
11375            mRenderNode.setPivotY(pivotY);
11376            invalidateViewProperty(false, true);
11377
11378            invalidateParentIfNeededAndWasQuickRejected();
11379        }
11380    }
11381
11382    /**
11383     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
11384     * completely transparent and 1 means the view is completely opaque.
11385     *
11386     * <p>By default this is 1.0f.
11387     * @return The opacity of the view.
11388     */
11389    @ViewDebug.ExportedProperty(category = "drawing")
11390    public float getAlpha() {
11391        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
11392    }
11393
11394    /**
11395     * Returns whether this View has content which overlaps.
11396     *
11397     * <p>This function, intended to be overridden by specific View types, is an optimization when
11398     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
11399     * an offscreen buffer and then composited into place, which can be expensive. If the view has
11400     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
11401     * directly. An example of overlapping rendering is a TextView with a background image, such as
11402     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
11403     * ImageView with only the foreground image. The default implementation returns true; subclasses
11404     * should override if they have cases which can be optimized.</p>
11405     *
11406     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
11407     * necessitates that a View return true if it uses the methods internally without passing the
11408     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
11409     *
11410     * @return true if the content in this view might overlap, false otherwise.
11411     */
11412    @ViewDebug.ExportedProperty(category = "drawing")
11413    public boolean hasOverlappingRendering() {
11414        return true;
11415    }
11416
11417    /**
11418     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
11419     * completely transparent and 1 means the view is completely opaque.
11420     *
11421     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
11422     * can have significant performance implications, especially for large views. It is best to use
11423     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
11424     *
11425     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
11426     * strongly recommended for performance reasons to either override
11427     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
11428     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
11429     * of the animation. On versions {@link android.os.Build.VERSION_CODES#MNC} and below,
11430     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
11431     * of rendering cost, even for simple or small views. Starting with
11432     * {@link android.os.Build.VERSION_CODES#MNC}, {@link #LAYER_TYPE_HARDWARE} is automatically
11433     * applied to the view at the rendering level.</p>
11434     *
11435     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
11436     * responsible for applying the opacity itself.</p>
11437     *
11438     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
11439     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
11440     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
11441     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
11442     *
11443     * <p>Starting with {@link android.os.Build.VERSION_CODES#MNC}, setting a translucent alpha
11444     * value will clip a View to its bounds, unless the View returns <code>false</code> from
11445     * {@link #hasOverlappingRendering}.</p>
11446     *
11447     * @param alpha The opacity of the view.
11448     *
11449     * @see #hasOverlappingRendering()
11450     * @see #setLayerType(int, android.graphics.Paint)
11451     *
11452     * @attr ref android.R.styleable#View_alpha
11453     */
11454    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
11455        ensureTransformationInfo();
11456        if (mTransformationInfo.mAlpha != alpha) {
11457            mTransformationInfo.mAlpha = alpha;
11458            if (onSetAlpha((int) (alpha * 255))) {
11459                mPrivateFlags |= PFLAG_ALPHA_SET;
11460                // subclass is handling alpha - don't optimize rendering cache invalidation
11461                invalidateParentCaches();
11462                invalidate(true);
11463            } else {
11464                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11465                invalidateViewProperty(true, false);
11466                mRenderNode.setAlpha(getFinalAlpha());
11467                notifyViewAccessibilityStateChangedIfNeeded(
11468                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11469            }
11470        }
11471    }
11472
11473    /**
11474     * Faster version of setAlpha() which performs the same steps except there are
11475     * no calls to invalidate(). The caller of this function should perform proper invalidation
11476     * on the parent and this object. The return value indicates whether the subclass handles
11477     * alpha (the return value for onSetAlpha()).
11478     *
11479     * @param alpha The new value for the alpha property
11480     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
11481     *         the new value for the alpha property is different from the old value
11482     */
11483    boolean setAlphaNoInvalidation(float alpha) {
11484        ensureTransformationInfo();
11485        if (mTransformationInfo.mAlpha != alpha) {
11486            mTransformationInfo.mAlpha = alpha;
11487            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
11488            if (subclassHandlesAlpha) {
11489                mPrivateFlags |= PFLAG_ALPHA_SET;
11490                return true;
11491            } else {
11492                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11493                mRenderNode.setAlpha(getFinalAlpha());
11494            }
11495        }
11496        return false;
11497    }
11498
11499    /**
11500     * This property is hidden and intended only for use by the Fade transition, which
11501     * animates it to produce a visual translucency that does not side-effect (or get
11502     * affected by) the real alpha property. This value is composited with the other
11503     * alpha value (and the AlphaAnimation value, when that is present) to produce
11504     * a final visual translucency result, which is what is passed into the DisplayList.
11505     *
11506     * @hide
11507     */
11508    public void setTransitionAlpha(float alpha) {
11509        ensureTransformationInfo();
11510        if (mTransformationInfo.mTransitionAlpha != alpha) {
11511            mTransformationInfo.mTransitionAlpha = alpha;
11512            mPrivateFlags &= ~PFLAG_ALPHA_SET;
11513            invalidateViewProperty(true, false);
11514            mRenderNode.setAlpha(getFinalAlpha());
11515        }
11516    }
11517
11518    /**
11519     * Calculates the visual alpha of this view, which is a combination of the actual
11520     * alpha value and the transitionAlpha value (if set).
11521     */
11522    private float getFinalAlpha() {
11523        if (mTransformationInfo != null) {
11524            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
11525        }
11526        return 1;
11527    }
11528
11529    /**
11530     * This property is hidden and intended only for use by the Fade transition, which
11531     * animates it to produce a visual translucency that does not side-effect (or get
11532     * affected by) the real alpha property. This value is composited with the other
11533     * alpha value (and the AlphaAnimation value, when that is present) to produce
11534     * a final visual translucency result, which is what is passed into the DisplayList.
11535     *
11536     * @hide
11537     */
11538    @ViewDebug.ExportedProperty(category = "drawing")
11539    public float getTransitionAlpha() {
11540        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
11541    }
11542
11543    /**
11544     * Top position of this view relative to its parent.
11545     *
11546     * @return The top of this view, in pixels.
11547     */
11548    @ViewDebug.CapturedViewProperty
11549    public final int getTop() {
11550        return mTop;
11551    }
11552
11553    /**
11554     * Sets the top position of this view relative to its parent. This method is meant to be called
11555     * by the layout system and should not generally be called otherwise, because the property
11556     * may be changed at any time by the layout.
11557     *
11558     * @param top The top of this view, in pixels.
11559     */
11560    public final void setTop(int top) {
11561        if (top != mTop) {
11562            final boolean matrixIsIdentity = hasIdentityMatrix();
11563            if (matrixIsIdentity) {
11564                if (mAttachInfo != null) {
11565                    int minTop;
11566                    int yLoc;
11567                    if (top < mTop) {
11568                        minTop = top;
11569                        yLoc = top - mTop;
11570                    } else {
11571                        minTop = mTop;
11572                        yLoc = 0;
11573                    }
11574                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11575                }
11576            } else {
11577                // Double-invalidation is necessary to capture view's old and new areas
11578                invalidate(true);
11579            }
11580
11581            int width = mRight - mLeft;
11582            int oldHeight = mBottom - mTop;
11583
11584            mTop = top;
11585            mRenderNode.setTop(mTop);
11586
11587            sizeChange(width, mBottom - mTop, width, oldHeight);
11588
11589            if (!matrixIsIdentity) {
11590                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11591                invalidate(true);
11592            }
11593            mBackgroundSizeChanged = true;
11594            if (mForegroundInfo != null) {
11595                mForegroundInfo.mBoundsChanged = true;
11596            }
11597            invalidateParentIfNeeded();
11598            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11599                // View was rejected last time it was drawn by its parent; this may have changed
11600                invalidateParentIfNeeded();
11601            }
11602        }
11603    }
11604
11605    /**
11606     * Bottom position of this view relative to its parent.
11607     *
11608     * @return The bottom of this view, in pixels.
11609     */
11610    @ViewDebug.CapturedViewProperty
11611    public final int getBottom() {
11612        return mBottom;
11613    }
11614
11615    /**
11616     * True if this view has changed since the last time being drawn.
11617     *
11618     * @return The dirty state of this view.
11619     */
11620    public boolean isDirty() {
11621        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11622    }
11623
11624    /**
11625     * Sets the bottom position of this view relative to its parent. This method is meant to be
11626     * called by the layout system and should not generally be called otherwise, because the
11627     * property may be changed at any time by the layout.
11628     *
11629     * @param bottom The bottom of this view, in pixels.
11630     */
11631    public final void setBottom(int bottom) {
11632        if (bottom != mBottom) {
11633            final boolean matrixIsIdentity = hasIdentityMatrix();
11634            if (matrixIsIdentity) {
11635                if (mAttachInfo != null) {
11636                    int maxBottom;
11637                    if (bottom < mBottom) {
11638                        maxBottom = mBottom;
11639                    } else {
11640                        maxBottom = bottom;
11641                    }
11642                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11643                }
11644            } else {
11645                // Double-invalidation is necessary to capture view's old and new areas
11646                invalidate(true);
11647            }
11648
11649            int width = mRight - mLeft;
11650            int oldHeight = mBottom - mTop;
11651
11652            mBottom = bottom;
11653            mRenderNode.setBottom(mBottom);
11654
11655            sizeChange(width, mBottom - mTop, width, oldHeight);
11656
11657            if (!matrixIsIdentity) {
11658                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11659                invalidate(true);
11660            }
11661            mBackgroundSizeChanged = true;
11662            if (mForegroundInfo != null) {
11663                mForegroundInfo.mBoundsChanged = true;
11664            }
11665            invalidateParentIfNeeded();
11666            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11667                // View was rejected last time it was drawn by its parent; this may have changed
11668                invalidateParentIfNeeded();
11669            }
11670        }
11671    }
11672
11673    /**
11674     * Left position of this view relative to its parent.
11675     *
11676     * @return The left edge of this view, in pixels.
11677     */
11678    @ViewDebug.CapturedViewProperty
11679    public final int getLeft() {
11680        return mLeft;
11681    }
11682
11683    /**
11684     * Sets the left position of this view relative to its parent. This method is meant to be called
11685     * by the layout system and should not generally be called otherwise, because the property
11686     * may be changed at any time by the layout.
11687     *
11688     * @param left The left of this view, in pixels.
11689     */
11690    public final void setLeft(int left) {
11691        if (left != mLeft) {
11692            final boolean matrixIsIdentity = hasIdentityMatrix();
11693            if (matrixIsIdentity) {
11694                if (mAttachInfo != null) {
11695                    int minLeft;
11696                    int xLoc;
11697                    if (left < mLeft) {
11698                        minLeft = left;
11699                        xLoc = left - mLeft;
11700                    } else {
11701                        minLeft = mLeft;
11702                        xLoc = 0;
11703                    }
11704                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11705                }
11706            } else {
11707                // Double-invalidation is necessary to capture view's old and new areas
11708                invalidate(true);
11709            }
11710
11711            int oldWidth = mRight - mLeft;
11712            int height = mBottom - mTop;
11713
11714            mLeft = left;
11715            mRenderNode.setLeft(left);
11716
11717            sizeChange(mRight - mLeft, height, oldWidth, height);
11718
11719            if (!matrixIsIdentity) {
11720                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11721                invalidate(true);
11722            }
11723            mBackgroundSizeChanged = true;
11724            if (mForegroundInfo != null) {
11725                mForegroundInfo.mBoundsChanged = true;
11726            }
11727            invalidateParentIfNeeded();
11728            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11729                // View was rejected last time it was drawn by its parent; this may have changed
11730                invalidateParentIfNeeded();
11731            }
11732        }
11733    }
11734
11735    /**
11736     * Right position of this view relative to its parent.
11737     *
11738     * @return The right edge of this view, in pixels.
11739     */
11740    @ViewDebug.CapturedViewProperty
11741    public final int getRight() {
11742        return mRight;
11743    }
11744
11745    /**
11746     * Sets the right position of this view relative to its parent. This method is meant to be called
11747     * by the layout system and should not generally be called otherwise, because the property
11748     * may be changed at any time by the layout.
11749     *
11750     * @param right The right of this view, in pixels.
11751     */
11752    public final void setRight(int right) {
11753        if (right != mRight) {
11754            final boolean matrixIsIdentity = hasIdentityMatrix();
11755            if (matrixIsIdentity) {
11756                if (mAttachInfo != null) {
11757                    int maxRight;
11758                    if (right < mRight) {
11759                        maxRight = mRight;
11760                    } else {
11761                        maxRight = right;
11762                    }
11763                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11764                }
11765            } else {
11766                // Double-invalidation is necessary to capture view's old and new areas
11767                invalidate(true);
11768            }
11769
11770            int oldWidth = mRight - mLeft;
11771            int height = mBottom - mTop;
11772
11773            mRight = right;
11774            mRenderNode.setRight(mRight);
11775
11776            sizeChange(mRight - mLeft, height, oldWidth, height);
11777
11778            if (!matrixIsIdentity) {
11779                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11780                invalidate(true);
11781            }
11782            mBackgroundSizeChanged = true;
11783            if (mForegroundInfo != null) {
11784                mForegroundInfo.mBoundsChanged = true;
11785            }
11786            invalidateParentIfNeeded();
11787            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11788                // View was rejected last time it was drawn by its parent; this may have changed
11789                invalidateParentIfNeeded();
11790            }
11791        }
11792    }
11793
11794    /**
11795     * The visual x position of this view, in pixels. This is equivalent to the
11796     * {@link #setTranslationX(float) translationX} property plus the current
11797     * {@link #getLeft() left} property.
11798     *
11799     * @return The visual x position of this view, in pixels.
11800     */
11801    @ViewDebug.ExportedProperty(category = "drawing")
11802    public float getX() {
11803        return mLeft + getTranslationX();
11804    }
11805
11806    /**
11807     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11808     * {@link #setTranslationX(float) translationX} property to be the difference between
11809     * the x value passed in and the current {@link #getLeft() left} property.
11810     *
11811     * @param x The visual x position of this view, in pixels.
11812     */
11813    public void setX(float x) {
11814        setTranslationX(x - mLeft);
11815    }
11816
11817    /**
11818     * The visual y position of this view, in pixels. This is equivalent to the
11819     * {@link #setTranslationY(float) translationY} property plus the current
11820     * {@link #getTop() top} property.
11821     *
11822     * @return The visual y position of this view, in pixels.
11823     */
11824    @ViewDebug.ExportedProperty(category = "drawing")
11825    public float getY() {
11826        return mTop + getTranslationY();
11827    }
11828
11829    /**
11830     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11831     * {@link #setTranslationY(float) translationY} property to be the difference between
11832     * the y value passed in and the current {@link #getTop() top} property.
11833     *
11834     * @param y The visual y position of this view, in pixels.
11835     */
11836    public void setY(float y) {
11837        setTranslationY(y - mTop);
11838    }
11839
11840    /**
11841     * The visual z position of this view, in pixels. This is equivalent to the
11842     * {@link #setTranslationZ(float) translationZ} property plus the current
11843     * {@link #getElevation() elevation} property.
11844     *
11845     * @return The visual z position of this view, in pixels.
11846     */
11847    @ViewDebug.ExportedProperty(category = "drawing")
11848    public float getZ() {
11849        return getElevation() + getTranslationZ();
11850    }
11851
11852    /**
11853     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11854     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11855     * the x value passed in and the current {@link #getElevation() elevation} property.
11856     *
11857     * @param z The visual z position of this view, in pixels.
11858     */
11859    public void setZ(float z) {
11860        setTranslationZ(z - getElevation());
11861    }
11862
11863    /**
11864     * The base elevation of this view relative to its parent, in pixels.
11865     *
11866     * @return The base depth position of the view, in pixels.
11867     */
11868    @ViewDebug.ExportedProperty(category = "drawing")
11869    public float getElevation() {
11870        return mRenderNode.getElevation();
11871    }
11872
11873    /**
11874     * Sets the base elevation of this view, in pixels.
11875     *
11876     * @attr ref android.R.styleable#View_elevation
11877     */
11878    public void setElevation(float elevation) {
11879        if (elevation != getElevation()) {
11880            invalidateViewProperty(true, false);
11881            mRenderNode.setElevation(elevation);
11882            invalidateViewProperty(false, true);
11883
11884            invalidateParentIfNeededAndWasQuickRejected();
11885        }
11886    }
11887
11888    /**
11889     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11890     * This position is post-layout, in addition to wherever the object's
11891     * layout placed it.
11892     *
11893     * @return The horizontal position of this view relative to its left position, in pixels.
11894     */
11895    @ViewDebug.ExportedProperty(category = "drawing")
11896    public float getTranslationX() {
11897        return mRenderNode.getTranslationX();
11898    }
11899
11900    /**
11901     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11902     * This effectively positions the object post-layout, in addition to wherever the object's
11903     * layout placed it.
11904     *
11905     * @param translationX The horizontal position of this view relative to its left position,
11906     * in pixels.
11907     *
11908     * @attr ref android.R.styleable#View_translationX
11909     */
11910    public void setTranslationX(float translationX) {
11911        if (translationX != getTranslationX()) {
11912            invalidateViewProperty(true, false);
11913            mRenderNode.setTranslationX(translationX);
11914            invalidateViewProperty(false, true);
11915
11916            invalidateParentIfNeededAndWasQuickRejected();
11917            notifySubtreeAccessibilityStateChangedIfNeeded();
11918        }
11919    }
11920
11921    /**
11922     * The vertical location of this view relative to its {@link #getTop() top} position.
11923     * This position is post-layout, in addition to wherever the object's
11924     * layout placed it.
11925     *
11926     * @return The vertical position of this view relative to its top position,
11927     * in pixels.
11928     */
11929    @ViewDebug.ExportedProperty(category = "drawing")
11930    public float getTranslationY() {
11931        return mRenderNode.getTranslationY();
11932    }
11933
11934    /**
11935     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11936     * This effectively positions the object post-layout, in addition to wherever the object's
11937     * layout placed it.
11938     *
11939     * @param translationY The vertical position of this view relative to its top position,
11940     * in pixels.
11941     *
11942     * @attr ref android.R.styleable#View_translationY
11943     */
11944    public void setTranslationY(float translationY) {
11945        if (translationY != getTranslationY()) {
11946            invalidateViewProperty(true, false);
11947            mRenderNode.setTranslationY(translationY);
11948            invalidateViewProperty(false, true);
11949
11950            invalidateParentIfNeededAndWasQuickRejected();
11951            notifySubtreeAccessibilityStateChangedIfNeeded();
11952        }
11953    }
11954
11955    /**
11956     * The depth location of this view relative to its {@link #getElevation() elevation}.
11957     *
11958     * @return The depth of this view relative to its elevation.
11959     */
11960    @ViewDebug.ExportedProperty(category = "drawing")
11961    public float getTranslationZ() {
11962        return mRenderNode.getTranslationZ();
11963    }
11964
11965    /**
11966     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11967     *
11968     * @attr ref android.R.styleable#View_translationZ
11969     */
11970    public void setTranslationZ(float translationZ) {
11971        if (translationZ != getTranslationZ()) {
11972            invalidateViewProperty(true, false);
11973            mRenderNode.setTranslationZ(translationZ);
11974            invalidateViewProperty(false, true);
11975
11976            invalidateParentIfNeededAndWasQuickRejected();
11977        }
11978    }
11979
11980    /** @hide */
11981    public void setAnimationMatrix(Matrix matrix) {
11982        invalidateViewProperty(true, false);
11983        mRenderNode.setAnimationMatrix(matrix);
11984        invalidateViewProperty(false, true);
11985
11986        invalidateParentIfNeededAndWasQuickRejected();
11987    }
11988
11989    /**
11990     * Returns the current StateListAnimator if exists.
11991     *
11992     * @return StateListAnimator or null if it does not exists
11993     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11994     */
11995    public StateListAnimator getStateListAnimator() {
11996        return mStateListAnimator;
11997    }
11998
11999    /**
12000     * Attaches the provided StateListAnimator to this View.
12001     * <p>
12002     * Any previously attached StateListAnimator will be detached.
12003     *
12004     * @param stateListAnimator The StateListAnimator to update the view
12005     * @see {@link android.animation.StateListAnimator}
12006     */
12007    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12008        if (mStateListAnimator == stateListAnimator) {
12009            return;
12010        }
12011        if (mStateListAnimator != null) {
12012            mStateListAnimator.setTarget(null);
12013        }
12014        mStateListAnimator = stateListAnimator;
12015        if (stateListAnimator != null) {
12016            stateListAnimator.setTarget(this);
12017            if (isAttachedToWindow()) {
12018                stateListAnimator.setState(getDrawableState());
12019            }
12020        }
12021    }
12022
12023    /**
12024     * Returns whether the Outline should be used to clip the contents of the View.
12025     * <p>
12026     * Note that this flag will only be respected if the View's Outline returns true from
12027     * {@link Outline#canClip()}.
12028     *
12029     * @see #setOutlineProvider(ViewOutlineProvider)
12030     * @see #setClipToOutline(boolean)
12031     */
12032    public final boolean getClipToOutline() {
12033        return mRenderNode.getClipToOutline();
12034    }
12035
12036    /**
12037     * Sets whether the View's Outline should be used to clip the contents of the View.
12038     * <p>
12039     * Only a single non-rectangular clip can be applied on a View at any time.
12040     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12041     * circular reveal} animation take priority over Outline clipping, and
12042     * child Outline clipping takes priority over Outline clipping done by a
12043     * parent.
12044     * <p>
12045     * Note that this flag will only be respected if the View's Outline returns true from
12046     * {@link Outline#canClip()}.
12047     *
12048     * @see #setOutlineProvider(ViewOutlineProvider)
12049     * @see #getClipToOutline()
12050     */
12051    public void setClipToOutline(boolean clipToOutline) {
12052        damageInParent();
12053        if (getClipToOutline() != clipToOutline) {
12054            mRenderNode.setClipToOutline(clipToOutline);
12055        }
12056    }
12057
12058    // correspond to the enum values of View_outlineProvider
12059    private static final int PROVIDER_BACKGROUND = 0;
12060    private static final int PROVIDER_NONE = 1;
12061    private static final int PROVIDER_BOUNDS = 2;
12062    private static final int PROVIDER_PADDED_BOUNDS = 3;
12063    private void setOutlineProviderFromAttribute(int providerInt) {
12064        switch (providerInt) {
12065            case PROVIDER_BACKGROUND:
12066                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12067                break;
12068            case PROVIDER_NONE:
12069                setOutlineProvider(null);
12070                break;
12071            case PROVIDER_BOUNDS:
12072                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12073                break;
12074            case PROVIDER_PADDED_BOUNDS:
12075                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12076                break;
12077        }
12078    }
12079
12080    /**
12081     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12082     * the shape of the shadow it casts, and enables outline clipping.
12083     * <p>
12084     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12085     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12086     * outline provider with this method allows this behavior to be overridden.
12087     * <p>
12088     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12089     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12090     * <p>
12091     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12092     *
12093     * @see #setClipToOutline(boolean)
12094     * @see #getClipToOutline()
12095     * @see #getOutlineProvider()
12096     */
12097    public void setOutlineProvider(ViewOutlineProvider provider) {
12098        mOutlineProvider = provider;
12099        invalidateOutline();
12100    }
12101
12102    /**
12103     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12104     * that defines the shape of the shadow it casts, and enables outline clipping.
12105     *
12106     * @see #setOutlineProvider(ViewOutlineProvider)
12107     */
12108    public ViewOutlineProvider getOutlineProvider() {
12109        return mOutlineProvider;
12110    }
12111
12112    /**
12113     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12114     *
12115     * @see #setOutlineProvider(ViewOutlineProvider)
12116     */
12117    public void invalidateOutline() {
12118        rebuildOutline();
12119
12120        notifySubtreeAccessibilityStateChangedIfNeeded();
12121        invalidateViewProperty(false, false);
12122    }
12123
12124    /**
12125     * Internal version of {@link #invalidateOutline()} which invalidates the
12126     * outline without invalidating the view itself. This is intended to be called from
12127     * within methods in the View class itself which are the result of the view being
12128     * invalidated already. For example, when we are drawing the background of a View,
12129     * we invalidate the outline in case it changed in the meantime, but we do not
12130     * need to invalidate the view because we're already drawing the background as part
12131     * of drawing the view in response to an earlier invalidation of the view.
12132     */
12133    private void rebuildOutline() {
12134        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12135        if (mAttachInfo == null) return;
12136
12137        if (mOutlineProvider == null) {
12138            // no provider, remove outline
12139            mRenderNode.setOutline(null);
12140        } else {
12141            final Outline outline = mAttachInfo.mTmpOutline;
12142            outline.setEmpty();
12143            outline.setAlpha(1.0f);
12144
12145            mOutlineProvider.getOutline(this, outline);
12146            mRenderNode.setOutline(outline);
12147        }
12148    }
12149
12150    /**
12151     * HierarchyViewer only
12152     *
12153     * @hide
12154     */
12155    @ViewDebug.ExportedProperty(category = "drawing")
12156    public boolean hasShadow() {
12157        return mRenderNode.hasShadow();
12158    }
12159
12160
12161    /** @hide */
12162    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
12163        mRenderNode.setRevealClip(shouldClip, x, y, radius);
12164        invalidateViewProperty(false, false);
12165    }
12166
12167    /**
12168     * Hit rectangle in parent's coordinates
12169     *
12170     * @param outRect The hit rectangle of the view.
12171     */
12172    public void getHitRect(Rect outRect) {
12173        if (hasIdentityMatrix() || mAttachInfo == null) {
12174            outRect.set(mLeft, mTop, mRight, mBottom);
12175        } else {
12176            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
12177            tmpRect.set(0, 0, getWidth(), getHeight());
12178            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
12179            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
12180                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
12181        }
12182    }
12183
12184    /**
12185     * Determines whether the given point, in local coordinates is inside the view.
12186     */
12187    /*package*/ final boolean pointInView(float localX, float localY) {
12188        return localX >= 0 && localX < (mRight - mLeft)
12189                && localY >= 0 && localY < (mBottom - mTop);
12190    }
12191
12192    /**
12193     * Utility method to determine whether the given point, in local coordinates,
12194     * is inside the view, where the area of the view is expanded by the slop factor.
12195     * This method is called while processing touch-move events to determine if the event
12196     * is still within the view.
12197     *
12198     * @hide
12199     */
12200    public boolean pointInView(float localX, float localY, float slop) {
12201        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
12202                localY < ((mBottom - mTop) + slop);
12203    }
12204
12205    /**
12206     * When a view has focus and the user navigates away from it, the next view is searched for
12207     * starting from the rectangle filled in by this method.
12208     *
12209     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
12210     * of the view.  However, if your view maintains some idea of internal selection,
12211     * such as a cursor, or a selected row or column, you should override this method and
12212     * fill in a more specific rectangle.
12213     *
12214     * @param r The rectangle to fill in, in this view's coordinates.
12215     */
12216    public void getFocusedRect(Rect r) {
12217        getDrawingRect(r);
12218    }
12219
12220    /**
12221     * If some part of this view is not clipped by any of its parents, then
12222     * return that area in r in global (root) coordinates. To convert r to local
12223     * coordinates (without taking possible View rotations into account), offset
12224     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
12225     * If the view is completely clipped or translated out, return false.
12226     *
12227     * @param r If true is returned, r holds the global coordinates of the
12228     *        visible portion of this view.
12229     * @param globalOffset If true is returned, globalOffset holds the dx,dy
12230     *        between this view and its root. globalOffet may be null.
12231     * @return true if r is non-empty (i.e. part of the view is visible at the
12232     *         root level.
12233     */
12234    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
12235        int width = mRight - mLeft;
12236        int height = mBottom - mTop;
12237        if (width > 0 && height > 0) {
12238            r.set(0, 0, width, height);
12239            if (globalOffset != null) {
12240                globalOffset.set(-mScrollX, -mScrollY);
12241            }
12242            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
12243        }
12244        return false;
12245    }
12246
12247    public final boolean getGlobalVisibleRect(Rect r) {
12248        return getGlobalVisibleRect(r, null);
12249    }
12250
12251    public final boolean getLocalVisibleRect(Rect r) {
12252        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
12253        if (getGlobalVisibleRect(r, offset)) {
12254            r.offset(-offset.x, -offset.y); // make r local
12255            return true;
12256        }
12257        return false;
12258    }
12259
12260    /**
12261     * Offset this view's vertical location by the specified number of pixels.
12262     *
12263     * @param offset the number of pixels to offset the view by
12264     */
12265    public void offsetTopAndBottom(int offset) {
12266        if (offset != 0) {
12267            final boolean matrixIsIdentity = hasIdentityMatrix();
12268            if (matrixIsIdentity) {
12269                if (isHardwareAccelerated()) {
12270                    invalidateViewProperty(false, false);
12271                } else {
12272                    final ViewParent p = mParent;
12273                    if (p != null && mAttachInfo != null) {
12274                        final Rect r = mAttachInfo.mTmpInvalRect;
12275                        int minTop;
12276                        int maxBottom;
12277                        int yLoc;
12278                        if (offset < 0) {
12279                            minTop = mTop + offset;
12280                            maxBottom = mBottom;
12281                            yLoc = offset;
12282                        } else {
12283                            minTop = mTop;
12284                            maxBottom = mBottom + offset;
12285                            yLoc = 0;
12286                        }
12287                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
12288                        p.invalidateChild(this, r);
12289                    }
12290                }
12291            } else {
12292                invalidateViewProperty(false, false);
12293            }
12294
12295            mTop += offset;
12296            mBottom += offset;
12297            mRenderNode.offsetTopAndBottom(offset);
12298            if (isHardwareAccelerated()) {
12299                invalidateViewProperty(false, false);
12300            } else {
12301                if (!matrixIsIdentity) {
12302                    invalidateViewProperty(false, true);
12303                }
12304                invalidateParentIfNeeded();
12305            }
12306            notifySubtreeAccessibilityStateChangedIfNeeded();
12307        }
12308    }
12309
12310    /**
12311     * Offset this view's horizontal location by the specified amount of pixels.
12312     *
12313     * @param offset the number of pixels to offset the view by
12314     */
12315    public void offsetLeftAndRight(int offset) {
12316        if (offset != 0) {
12317            final boolean matrixIsIdentity = hasIdentityMatrix();
12318            if (matrixIsIdentity) {
12319                if (isHardwareAccelerated()) {
12320                    invalidateViewProperty(false, false);
12321                } else {
12322                    final ViewParent p = mParent;
12323                    if (p != null && mAttachInfo != null) {
12324                        final Rect r = mAttachInfo.mTmpInvalRect;
12325                        int minLeft;
12326                        int maxRight;
12327                        if (offset < 0) {
12328                            minLeft = mLeft + offset;
12329                            maxRight = mRight;
12330                        } else {
12331                            minLeft = mLeft;
12332                            maxRight = mRight + offset;
12333                        }
12334                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
12335                        p.invalidateChild(this, r);
12336                    }
12337                }
12338            } else {
12339                invalidateViewProperty(false, false);
12340            }
12341
12342            mLeft += offset;
12343            mRight += offset;
12344            mRenderNode.offsetLeftAndRight(offset);
12345            if (isHardwareAccelerated()) {
12346                invalidateViewProperty(false, false);
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, "View too large to fit into drawing cache, needs "
15377                        + projectedBitmapSize + " bytes, only "
15378                        + drawingCacheSize + " available");
15379            }
15380            destroyDrawingCache();
15381            mCachingFailed = true;
15382            return;
15383        }
15384
15385        boolean clear = true;
15386        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
15387
15388        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
15389            Bitmap.Config quality;
15390            if (!opaque) {
15391                // Never pick ARGB_4444 because it looks awful
15392                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
15393                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
15394                    case DRAWING_CACHE_QUALITY_AUTO:
15395                    case DRAWING_CACHE_QUALITY_LOW:
15396                    case DRAWING_CACHE_QUALITY_HIGH:
15397                    default:
15398                        quality = Bitmap.Config.ARGB_8888;
15399                        break;
15400                }
15401            } else {
15402                // Optimization for translucent windows
15403                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
15404                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
15405            }
15406
15407            // Try to cleanup memory
15408            if (bitmap != null) bitmap.recycle();
15409
15410            try {
15411                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15412                        width, height, quality);
15413                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
15414                if (autoScale) {
15415                    mDrawingCache = bitmap;
15416                } else {
15417                    mUnscaledDrawingCache = bitmap;
15418                }
15419                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
15420            } catch (OutOfMemoryError e) {
15421                // If there is not enough memory to create the bitmap cache, just
15422                // ignore the issue as bitmap caches are not required to draw the
15423                // view hierarchy
15424                if (autoScale) {
15425                    mDrawingCache = null;
15426                } else {
15427                    mUnscaledDrawingCache = null;
15428                }
15429                mCachingFailed = true;
15430                return;
15431            }
15432
15433            clear = drawingCacheBackgroundColor != 0;
15434        }
15435
15436        Canvas canvas;
15437        if (attachInfo != null) {
15438            canvas = attachInfo.mCanvas;
15439            if (canvas == null) {
15440                canvas = new Canvas();
15441            }
15442            canvas.setBitmap(bitmap);
15443            // Temporarily clobber the cached Canvas in case one of our children
15444            // is also using a drawing cache. Without this, the children would
15445            // steal the canvas by attaching their own bitmap to it and bad, bad
15446            // thing would happen (invisible views, corrupted drawings, etc.)
15447            attachInfo.mCanvas = null;
15448        } else {
15449            // This case should hopefully never or seldom happen
15450            canvas = new Canvas(bitmap);
15451        }
15452
15453        if (clear) {
15454            bitmap.eraseColor(drawingCacheBackgroundColor);
15455        }
15456
15457        computeScroll();
15458        final int restoreCount = canvas.save();
15459
15460        if (autoScale && scalingRequired) {
15461            final float scale = attachInfo.mApplicationScale;
15462            canvas.scale(scale, scale);
15463        }
15464
15465        canvas.translate(-mScrollX, -mScrollY);
15466
15467        mPrivateFlags |= PFLAG_DRAWN;
15468        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
15469                mLayerType != LAYER_TYPE_NONE) {
15470            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
15471        }
15472
15473        // Fast path for layouts with no backgrounds
15474        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15475            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15476            dispatchDraw(canvas);
15477            if (mOverlay != null && !mOverlay.isEmpty()) {
15478                mOverlay.getOverlayView().draw(canvas);
15479            }
15480        } else {
15481            draw(canvas);
15482        }
15483
15484        canvas.restoreToCount(restoreCount);
15485        canvas.setBitmap(null);
15486
15487        if (attachInfo != null) {
15488            // Restore the cached Canvas for our siblings
15489            attachInfo.mCanvas = canvas;
15490        }
15491    }
15492
15493    /**
15494     * Create a snapshot of the view into a bitmap.  We should probably make
15495     * some form of this public, but should think about the API.
15496     */
15497    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
15498        int width = mRight - mLeft;
15499        int height = mBottom - mTop;
15500
15501        final AttachInfo attachInfo = mAttachInfo;
15502        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
15503        width = (int) ((width * scale) + 0.5f);
15504        height = (int) ((height * scale) + 0.5f);
15505
15506        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15507                width > 0 ? width : 1, height > 0 ? height : 1, quality);
15508        if (bitmap == null) {
15509            throw new OutOfMemoryError();
15510        }
15511
15512        Resources resources = getResources();
15513        if (resources != null) {
15514            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
15515        }
15516
15517        Canvas canvas;
15518        if (attachInfo != null) {
15519            canvas = attachInfo.mCanvas;
15520            if (canvas == null) {
15521                canvas = new Canvas();
15522            }
15523            canvas.setBitmap(bitmap);
15524            // Temporarily clobber the cached Canvas in case one of our children
15525            // is also using a drawing cache. Without this, the children would
15526            // steal the canvas by attaching their own bitmap to it and bad, bad
15527            // things would happen (invisible views, corrupted drawings, etc.)
15528            attachInfo.mCanvas = null;
15529        } else {
15530            // This case should hopefully never or seldom happen
15531            canvas = new Canvas(bitmap);
15532        }
15533
15534        if ((backgroundColor & 0xff000000) != 0) {
15535            bitmap.eraseColor(backgroundColor);
15536        }
15537
15538        computeScroll();
15539        final int restoreCount = canvas.save();
15540        canvas.scale(scale, scale);
15541        canvas.translate(-mScrollX, -mScrollY);
15542
15543        // Temporarily remove the dirty mask
15544        int flags = mPrivateFlags;
15545        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15546
15547        // Fast path for layouts with no backgrounds
15548        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15549            dispatchDraw(canvas);
15550            if (mOverlay != null && !mOverlay.isEmpty()) {
15551                mOverlay.getOverlayView().draw(canvas);
15552            }
15553        } else {
15554            draw(canvas);
15555        }
15556
15557        mPrivateFlags = flags;
15558
15559        canvas.restoreToCount(restoreCount);
15560        canvas.setBitmap(null);
15561
15562        if (attachInfo != null) {
15563            // Restore the cached Canvas for our siblings
15564            attachInfo.mCanvas = canvas;
15565        }
15566
15567        return bitmap;
15568    }
15569
15570    /**
15571     * Indicates whether this View is currently in edit mode. A View is usually
15572     * in edit mode when displayed within a developer tool. For instance, if
15573     * this View is being drawn by a visual user interface builder, this method
15574     * should return true.
15575     *
15576     * Subclasses should check the return value of this method to provide
15577     * different behaviors if their normal behavior might interfere with the
15578     * host environment. For instance: the class spawns a thread in its
15579     * constructor, the drawing code relies on device-specific features, etc.
15580     *
15581     * This method is usually checked in the drawing code of custom widgets.
15582     *
15583     * @return True if this View is in edit mode, false otherwise.
15584     */
15585    public boolean isInEditMode() {
15586        return false;
15587    }
15588
15589    /**
15590     * If the View draws content inside its padding and enables fading edges,
15591     * it needs to support padding offsets. Padding offsets are added to the
15592     * fading edges to extend the length of the fade so that it covers pixels
15593     * drawn inside the padding.
15594     *
15595     * Subclasses of this class should override this method if they need
15596     * to draw content inside the padding.
15597     *
15598     * @return True if padding offset must be applied, false otherwise.
15599     *
15600     * @see #getLeftPaddingOffset()
15601     * @see #getRightPaddingOffset()
15602     * @see #getTopPaddingOffset()
15603     * @see #getBottomPaddingOffset()
15604     *
15605     * @since CURRENT
15606     */
15607    protected boolean isPaddingOffsetRequired() {
15608        return false;
15609    }
15610
15611    /**
15612     * Amount by which to extend the left fading region. Called only when
15613     * {@link #isPaddingOffsetRequired()} returns true.
15614     *
15615     * @return The left padding offset in pixels.
15616     *
15617     * @see #isPaddingOffsetRequired()
15618     *
15619     * @since CURRENT
15620     */
15621    protected int getLeftPaddingOffset() {
15622        return 0;
15623    }
15624
15625    /**
15626     * Amount by which to extend the right fading region. Called only when
15627     * {@link #isPaddingOffsetRequired()} returns true.
15628     *
15629     * @return The right padding offset in pixels.
15630     *
15631     * @see #isPaddingOffsetRequired()
15632     *
15633     * @since CURRENT
15634     */
15635    protected int getRightPaddingOffset() {
15636        return 0;
15637    }
15638
15639    /**
15640     * Amount by which to extend the top fading region. Called only when
15641     * {@link #isPaddingOffsetRequired()} returns true.
15642     *
15643     * @return The top padding offset in pixels.
15644     *
15645     * @see #isPaddingOffsetRequired()
15646     *
15647     * @since CURRENT
15648     */
15649    protected int getTopPaddingOffset() {
15650        return 0;
15651    }
15652
15653    /**
15654     * Amount by which to extend the bottom fading region. Called only when
15655     * {@link #isPaddingOffsetRequired()} returns true.
15656     *
15657     * @return The bottom padding offset in pixels.
15658     *
15659     * @see #isPaddingOffsetRequired()
15660     *
15661     * @since CURRENT
15662     */
15663    protected int getBottomPaddingOffset() {
15664        return 0;
15665    }
15666
15667    /**
15668     * @hide
15669     * @param offsetRequired
15670     */
15671    protected int getFadeTop(boolean offsetRequired) {
15672        int top = mPaddingTop;
15673        if (offsetRequired) top += getTopPaddingOffset();
15674        return top;
15675    }
15676
15677    /**
15678     * @hide
15679     * @param offsetRequired
15680     */
15681    protected int getFadeHeight(boolean offsetRequired) {
15682        int padding = mPaddingTop;
15683        if (offsetRequired) padding += getTopPaddingOffset();
15684        return mBottom - mTop - mPaddingBottom - padding;
15685    }
15686
15687    /**
15688     * <p>Indicates whether this view is attached to a hardware accelerated
15689     * window or not.</p>
15690     *
15691     * <p>Even if this method returns true, it does not mean that every call
15692     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15693     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15694     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15695     * window is hardware accelerated,
15696     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15697     * return false, and this method will return true.</p>
15698     *
15699     * @return True if the view is attached to a window and the window is
15700     *         hardware accelerated; false in any other case.
15701     */
15702    @ViewDebug.ExportedProperty(category = "drawing")
15703    public boolean isHardwareAccelerated() {
15704        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15705    }
15706
15707    /**
15708     * Sets a rectangular area on this view to which the view will be clipped
15709     * when it is drawn. Setting the value to null will remove the clip bounds
15710     * and the view will draw normally, using its full bounds.
15711     *
15712     * @param clipBounds The rectangular area, in the local coordinates of
15713     * this view, to which future drawing operations will be clipped.
15714     */
15715    public void setClipBounds(Rect clipBounds) {
15716        if (clipBounds == mClipBounds
15717                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15718            return;
15719        }
15720        if (clipBounds != null) {
15721            if (mClipBounds == null) {
15722                mClipBounds = new Rect(clipBounds);
15723            } else {
15724                mClipBounds.set(clipBounds);
15725            }
15726        } else {
15727            mClipBounds = null;
15728        }
15729        mRenderNode.setClipBounds(mClipBounds);
15730        invalidateViewProperty(false, false);
15731    }
15732
15733    /**
15734     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15735     *
15736     * @return A copy of the current clip bounds if clip bounds are set,
15737     * otherwise null.
15738     */
15739    public Rect getClipBounds() {
15740        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15741    }
15742
15743
15744    /**
15745     * Populates an output rectangle with the clip bounds of the view,
15746     * returning {@code true} if successful or {@code false} if the view's
15747     * clip bounds are {@code null}.
15748     *
15749     * @param outRect rectangle in which to place the clip bounds of the view
15750     * @return {@code true} if successful or {@code false} if the view's
15751     *         clip bounds are {@code null}
15752     */
15753    public boolean getClipBounds(Rect outRect) {
15754        if (mClipBounds != null) {
15755            outRect.set(mClipBounds);
15756            return true;
15757        }
15758        return false;
15759    }
15760
15761    /**
15762     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15763     * case of an active Animation being run on the view.
15764     */
15765    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15766            Animation a, boolean scalingRequired) {
15767        Transformation invalidationTransform;
15768        final int flags = parent.mGroupFlags;
15769        final boolean initialized = a.isInitialized();
15770        if (!initialized) {
15771            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15772            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15773            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15774            onAnimationStart();
15775        }
15776
15777        final Transformation t = parent.getChildTransformation();
15778        boolean more = a.getTransformation(drawingTime, t, 1f);
15779        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15780            if (parent.mInvalidationTransformation == null) {
15781                parent.mInvalidationTransformation = new Transformation();
15782            }
15783            invalidationTransform = parent.mInvalidationTransformation;
15784            a.getTransformation(drawingTime, invalidationTransform, 1f);
15785        } else {
15786            invalidationTransform = t;
15787        }
15788
15789        if (more) {
15790            if (!a.willChangeBounds()) {
15791                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15792                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15793                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15794                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15795                    // The child need to draw an animation, potentially offscreen, so
15796                    // make sure we do not cancel invalidate requests
15797                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15798                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15799                }
15800            } else {
15801                if (parent.mInvalidateRegion == null) {
15802                    parent.mInvalidateRegion = new RectF();
15803                }
15804                final RectF region = parent.mInvalidateRegion;
15805                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15806                        invalidationTransform);
15807
15808                // The child need to draw an animation, potentially offscreen, so
15809                // make sure we do not cancel invalidate requests
15810                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15811
15812                final int left = mLeft + (int) region.left;
15813                final int top = mTop + (int) region.top;
15814                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15815                        top + (int) (region.height() + .5f));
15816            }
15817        }
15818        return more;
15819    }
15820
15821    /**
15822     * This method is called by getDisplayList() when a display list is recorded for a View.
15823     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15824     */
15825    void setDisplayListProperties(RenderNode renderNode) {
15826        if (renderNode != null) {
15827            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15828            renderNode.setClipToBounds(mParent instanceof ViewGroup
15829                    && ((ViewGroup) mParent).getClipChildren());
15830
15831            float alpha = 1;
15832            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15833                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15834                ViewGroup parentVG = (ViewGroup) mParent;
15835                final Transformation t = parentVG.getChildTransformation();
15836                if (parentVG.getChildStaticTransformation(this, t)) {
15837                    final int transformType = t.getTransformationType();
15838                    if (transformType != Transformation.TYPE_IDENTITY) {
15839                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15840                            alpha = t.getAlpha();
15841                        }
15842                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15843                            renderNode.setStaticMatrix(t.getMatrix());
15844                        }
15845                    }
15846                }
15847            }
15848            if (mTransformationInfo != null) {
15849                alpha *= getFinalAlpha();
15850                if (alpha < 1) {
15851                    final int multipliedAlpha = (int) (255 * alpha);
15852                    if (onSetAlpha(multipliedAlpha)) {
15853                        alpha = 1;
15854                    }
15855                }
15856                renderNode.setAlpha(alpha);
15857            } else if (alpha < 1) {
15858                renderNode.setAlpha(alpha);
15859            }
15860        }
15861    }
15862
15863    /**
15864     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15865     *
15866     * This is where the View specializes rendering behavior based on layer type,
15867     * and hardware acceleration.
15868     */
15869    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15870        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15871        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15872         *
15873         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15874         * HW accelerated, it can't handle drawing RenderNodes.
15875         */
15876        boolean drawingWithRenderNode = mAttachInfo != null
15877                && mAttachInfo.mHardwareAccelerated
15878                && hardwareAcceleratedCanvas;
15879
15880        boolean more = false;
15881        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15882        final int parentFlags = parent.mGroupFlags;
15883
15884        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15885            parent.getChildTransformation().clear();
15886            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15887        }
15888
15889        Transformation transformToApply = null;
15890        boolean concatMatrix = false;
15891        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15892        final Animation a = getAnimation();
15893        if (a != null) {
15894            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15895            concatMatrix = a.willChangeTransformationMatrix();
15896            if (concatMatrix) {
15897                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15898            }
15899            transformToApply = parent.getChildTransformation();
15900        } else {
15901            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15902                // No longer animating: clear out old animation matrix
15903                mRenderNode.setAnimationMatrix(null);
15904                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15905            }
15906            if (!drawingWithRenderNode
15907                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15908                final Transformation t = parent.getChildTransformation();
15909                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15910                if (hasTransform) {
15911                    final int transformType = t.getTransformationType();
15912                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15913                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15914                }
15915            }
15916        }
15917
15918        concatMatrix |= !childHasIdentityMatrix;
15919
15920        // Sets the flag as early as possible to allow draw() implementations
15921        // to call invalidate() successfully when doing animations
15922        mPrivateFlags |= PFLAG_DRAWN;
15923
15924        if (!concatMatrix &&
15925                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15926                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15927                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15928                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15929            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15930            return more;
15931        }
15932        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15933
15934        if (hardwareAcceleratedCanvas) {
15935            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15936            // retain the flag's value temporarily in the mRecreateDisplayList flag
15937            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15938            mPrivateFlags &= ~PFLAG_INVALIDATED;
15939        }
15940
15941        RenderNode renderNode = null;
15942        Bitmap cache = null;
15943        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
15944        if (layerType == LAYER_TYPE_SOFTWARE
15945                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15946            // If not drawing with RenderNode, treat HW layers as SW
15947            layerType = LAYER_TYPE_SOFTWARE;
15948            buildDrawingCache(true);
15949            cache = getDrawingCache(true);
15950        }
15951
15952        if (drawingWithRenderNode) {
15953            // Delay getting the display list until animation-driven alpha values are
15954            // set up and possibly passed on to the view
15955            renderNode = updateDisplayListIfDirty();
15956            if (!renderNode.isValid()) {
15957                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15958                // to getDisplayList(), the display list will be marked invalid and we should not
15959                // try to use it again.
15960                renderNode = null;
15961                drawingWithRenderNode = false;
15962            }
15963        }
15964
15965        int sx = 0;
15966        int sy = 0;
15967        if (!drawingWithRenderNode) {
15968            computeScroll();
15969            sx = mScrollX;
15970            sy = mScrollY;
15971        }
15972
15973        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
15974        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
15975
15976        int restoreTo = -1;
15977        if (!drawingWithRenderNode || transformToApply != null) {
15978            restoreTo = canvas.save();
15979        }
15980        if (offsetForScroll) {
15981            canvas.translate(mLeft - sx, mTop - sy);
15982        } else {
15983            if (!drawingWithRenderNode) {
15984                canvas.translate(mLeft, mTop);
15985            }
15986            if (scalingRequired) {
15987                if (drawingWithRenderNode) {
15988                    // TODO: Might not need this if we put everything inside the DL
15989                    restoreTo = canvas.save();
15990                }
15991                // mAttachInfo cannot be null, otherwise scalingRequired == false
15992                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15993                canvas.scale(scale, scale);
15994            }
15995        }
15996
15997        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15998        if (transformToApply != null
15999                || alpha < 1
16000                || !hasIdentityMatrix()
16001                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16002            if (transformToApply != null || !childHasIdentityMatrix) {
16003                int transX = 0;
16004                int transY = 0;
16005
16006                if (offsetForScroll) {
16007                    transX = -sx;
16008                    transY = -sy;
16009                }
16010
16011                if (transformToApply != null) {
16012                    if (concatMatrix) {
16013                        if (drawingWithRenderNode) {
16014                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16015                        } else {
16016                            // Undo the scroll translation, apply the transformation matrix,
16017                            // then redo the scroll translate to get the correct result.
16018                            canvas.translate(-transX, -transY);
16019                            canvas.concat(transformToApply.getMatrix());
16020                            canvas.translate(transX, transY);
16021                        }
16022                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16023                    }
16024
16025                    float transformAlpha = transformToApply.getAlpha();
16026                    if (transformAlpha < 1) {
16027                        alpha *= transformAlpha;
16028                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16029                    }
16030                }
16031
16032                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16033                    canvas.translate(-transX, -transY);
16034                    canvas.concat(getMatrix());
16035                    canvas.translate(transX, transY);
16036                }
16037            }
16038
16039            // Deal with alpha if it is or used to be <1
16040            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16041                if (alpha < 1) {
16042                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16043                } else {
16044                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16045                }
16046                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16047                if (!drawingWithDrawingCache) {
16048                    final int multipliedAlpha = (int) (255 * alpha);
16049                    if (!onSetAlpha(multipliedAlpha)) {
16050                        if (drawingWithRenderNode) {
16051                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16052                        } else if (layerType == LAYER_TYPE_NONE) {
16053                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16054                                    multipliedAlpha);
16055                        }
16056                    } else {
16057                        // Alpha is handled by the child directly, clobber the layer's alpha
16058                        mPrivateFlags |= PFLAG_ALPHA_SET;
16059                    }
16060                }
16061            }
16062        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16063            onSetAlpha(255);
16064            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16065        }
16066
16067        if (!drawingWithRenderNode) {
16068            // apply clips directly, since RenderNode won't do it for this draw
16069            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16070                if (offsetForScroll) {
16071                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16072                } else {
16073                    if (!scalingRequired || cache == null) {
16074                        canvas.clipRect(0, 0, getWidth(), getHeight());
16075                    } else {
16076                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16077                    }
16078                }
16079            }
16080
16081            if (mClipBounds != null) {
16082                // clip bounds ignore scroll
16083                canvas.clipRect(mClipBounds);
16084            }
16085        }
16086
16087        if (!drawingWithDrawingCache) {
16088            if (drawingWithRenderNode) {
16089                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16090                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16091            } else {
16092                // Fast path for layouts with no backgrounds
16093                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16094                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16095                    dispatchDraw(canvas);
16096                } else {
16097                    draw(canvas);
16098                }
16099            }
16100        } else if (cache != null) {
16101            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16102            if (layerType == LAYER_TYPE_NONE) {
16103                // no layer paint, use temporary paint to draw bitmap
16104                Paint cachePaint = parent.mCachePaint;
16105                if (cachePaint == null) {
16106                    cachePaint = new Paint();
16107                    cachePaint.setDither(false);
16108                    parent.mCachePaint = cachePaint;
16109                }
16110                cachePaint.setAlpha((int) (alpha * 255));
16111                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16112            } else {
16113                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16114                int layerPaintAlpha = mLayerPaint.getAlpha();
16115                mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
16116                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
16117                mLayerPaint.setAlpha(layerPaintAlpha);
16118            }
16119        }
16120
16121        if (restoreTo >= 0) {
16122            canvas.restoreToCount(restoreTo);
16123        }
16124
16125        if (a != null && !more) {
16126            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
16127                onSetAlpha(255);
16128            }
16129            parent.finishAnimatingView(this, a);
16130        }
16131
16132        if (more && hardwareAcceleratedCanvas) {
16133            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16134                // alpha animations should cause the child to recreate its display list
16135                invalidate(true);
16136            }
16137        }
16138
16139        mRecreateDisplayList = false;
16140
16141        return more;
16142    }
16143
16144    /**
16145     * Manually render this view (and all of its children) to the given Canvas.
16146     * The view must have already done a full layout before this function is
16147     * called.  When implementing a view, implement
16148     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
16149     * If you do need to override this method, call the superclass version.
16150     *
16151     * @param canvas The Canvas to which the View is rendered.
16152     */
16153    @CallSuper
16154    public void draw(Canvas canvas) {
16155        final int privateFlags = mPrivateFlags;
16156        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
16157                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
16158        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
16159
16160        /*
16161         * Draw traversal performs several drawing steps which must be executed
16162         * in the appropriate order:
16163         *
16164         *      1. Draw the background
16165         *      2. If necessary, save the canvas' layers to prepare for fading
16166         *      3. Draw view's content
16167         *      4. Draw children
16168         *      5. If necessary, draw the fading edges and restore layers
16169         *      6. Draw decorations (scrollbars for instance)
16170         */
16171
16172        // Step 1, draw the background, if needed
16173        int saveCount;
16174
16175        if (!dirtyOpaque) {
16176            drawBackground(canvas);
16177        }
16178
16179        // skip step 2 & 5 if possible (common case)
16180        final int viewFlags = mViewFlags;
16181        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
16182        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
16183        if (!verticalEdges && !horizontalEdges) {
16184            // Step 3, draw the content
16185            if (!dirtyOpaque) onDraw(canvas);
16186
16187            // Step 4, draw the children
16188            dispatchDraw(canvas);
16189
16190            // Overlay is part of the content and draws beneath Foreground
16191            if (mOverlay != null && !mOverlay.isEmpty()) {
16192                mOverlay.getOverlayView().dispatchDraw(canvas);
16193            }
16194
16195            // Step 6, draw decorations (foreground, scrollbars)
16196            onDrawForeground(canvas);
16197
16198            // we're done...
16199            return;
16200        }
16201
16202        /*
16203         * Here we do the full fledged routine...
16204         * (this is an uncommon case where speed matters less,
16205         * this is why we repeat some of the tests that have been
16206         * done above)
16207         */
16208
16209        boolean drawTop = false;
16210        boolean drawBottom = false;
16211        boolean drawLeft = false;
16212        boolean drawRight = false;
16213
16214        float topFadeStrength = 0.0f;
16215        float bottomFadeStrength = 0.0f;
16216        float leftFadeStrength = 0.0f;
16217        float rightFadeStrength = 0.0f;
16218
16219        // Step 2, save the canvas' layers
16220        int paddingLeft = mPaddingLeft;
16221
16222        final boolean offsetRequired = isPaddingOffsetRequired();
16223        if (offsetRequired) {
16224            paddingLeft += getLeftPaddingOffset();
16225        }
16226
16227        int left = mScrollX + paddingLeft;
16228        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
16229        int top = mScrollY + getFadeTop(offsetRequired);
16230        int bottom = top + getFadeHeight(offsetRequired);
16231
16232        if (offsetRequired) {
16233            right += getRightPaddingOffset();
16234            bottom += getBottomPaddingOffset();
16235        }
16236
16237        final ScrollabilityCache scrollabilityCache = mScrollCache;
16238        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
16239        int length = (int) fadeHeight;
16240
16241        // clip the fade length if top and bottom fades overlap
16242        // overlapping fades produce odd-looking artifacts
16243        if (verticalEdges && (top + length > bottom - length)) {
16244            length = (bottom - top) / 2;
16245        }
16246
16247        // also clip horizontal fades if necessary
16248        if (horizontalEdges && (left + length > right - length)) {
16249            length = (right - left) / 2;
16250        }
16251
16252        if (verticalEdges) {
16253            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
16254            drawTop = topFadeStrength * fadeHeight > 1.0f;
16255            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
16256            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
16257        }
16258
16259        if (horizontalEdges) {
16260            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
16261            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
16262            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
16263            drawRight = rightFadeStrength * fadeHeight > 1.0f;
16264        }
16265
16266        saveCount = canvas.getSaveCount();
16267
16268        int solidColor = getSolidColor();
16269        if (solidColor == 0) {
16270            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
16271
16272            if (drawTop) {
16273                canvas.saveLayer(left, top, right, top + length, null, flags);
16274            }
16275
16276            if (drawBottom) {
16277                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
16278            }
16279
16280            if (drawLeft) {
16281                canvas.saveLayer(left, top, left + length, bottom, null, flags);
16282            }
16283
16284            if (drawRight) {
16285                canvas.saveLayer(right - length, top, right, bottom, null, flags);
16286            }
16287        } else {
16288            scrollabilityCache.setFadeColor(solidColor);
16289        }
16290
16291        // Step 3, draw the content
16292        if (!dirtyOpaque) onDraw(canvas);
16293
16294        // Step 4, draw the children
16295        dispatchDraw(canvas);
16296
16297        // Step 5, draw the fade effect and restore layers
16298        final Paint p = scrollabilityCache.paint;
16299        final Matrix matrix = scrollabilityCache.matrix;
16300        final Shader fade = scrollabilityCache.shader;
16301
16302        if (drawTop) {
16303            matrix.setScale(1, fadeHeight * topFadeStrength);
16304            matrix.postTranslate(left, top);
16305            fade.setLocalMatrix(matrix);
16306            p.setShader(fade);
16307            canvas.drawRect(left, top, right, top + length, p);
16308        }
16309
16310        if (drawBottom) {
16311            matrix.setScale(1, fadeHeight * bottomFadeStrength);
16312            matrix.postRotate(180);
16313            matrix.postTranslate(left, bottom);
16314            fade.setLocalMatrix(matrix);
16315            p.setShader(fade);
16316            canvas.drawRect(left, bottom - length, right, bottom, p);
16317        }
16318
16319        if (drawLeft) {
16320            matrix.setScale(1, fadeHeight * leftFadeStrength);
16321            matrix.postRotate(-90);
16322            matrix.postTranslate(left, top);
16323            fade.setLocalMatrix(matrix);
16324            p.setShader(fade);
16325            canvas.drawRect(left, top, left + length, bottom, p);
16326        }
16327
16328        if (drawRight) {
16329            matrix.setScale(1, fadeHeight * rightFadeStrength);
16330            matrix.postRotate(90);
16331            matrix.postTranslate(right, top);
16332            fade.setLocalMatrix(matrix);
16333            p.setShader(fade);
16334            canvas.drawRect(right - length, top, right, bottom, p);
16335        }
16336
16337        canvas.restoreToCount(saveCount);
16338
16339        // Overlay is part of the content and draws beneath Foreground
16340        if (mOverlay != null && !mOverlay.isEmpty()) {
16341            mOverlay.getOverlayView().dispatchDraw(canvas);
16342        }
16343
16344        // Step 6, draw decorations (foreground, scrollbars)
16345        onDrawForeground(canvas);
16346    }
16347
16348    /**
16349     * Draws the background onto the specified canvas.
16350     *
16351     * @param canvas Canvas on which to draw the background
16352     */
16353    private void drawBackground(Canvas canvas) {
16354        final Drawable background = mBackground;
16355        if (background == null) {
16356            return;
16357        }
16358
16359        setBackgroundBounds();
16360
16361        // Attempt to use a display list if requested.
16362        if (canvas.isHardwareAccelerated() && mAttachInfo != null
16363                && mAttachInfo.mHardwareRenderer != null) {
16364            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
16365
16366            final RenderNode renderNode = mBackgroundRenderNode;
16367            if (renderNode != null && renderNode.isValid()) {
16368                setBackgroundRenderNodeProperties(renderNode);
16369                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16370                return;
16371            }
16372        }
16373
16374        final int scrollX = mScrollX;
16375        final int scrollY = mScrollY;
16376        if ((scrollX | scrollY) == 0) {
16377            background.draw(canvas);
16378        } else {
16379            canvas.translate(scrollX, scrollY);
16380            background.draw(canvas);
16381            canvas.translate(-scrollX, -scrollY);
16382        }
16383    }
16384
16385    /**
16386     * Sets the correct background bounds and rebuilds the outline, if needed.
16387     * <p/>
16388     * This is called by LayoutLib.
16389     */
16390    void setBackgroundBounds() {
16391        if (mBackgroundSizeChanged && mBackground != null) {
16392            mBackground.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
16393            mBackgroundSizeChanged = false;
16394            rebuildOutline();
16395        }
16396    }
16397
16398    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
16399        renderNode.setTranslationX(mScrollX);
16400        renderNode.setTranslationY(mScrollY);
16401    }
16402
16403    /**
16404     * Creates a new display list or updates the existing display list for the
16405     * specified Drawable.
16406     *
16407     * @param drawable Drawable for which to create a display list
16408     * @param renderNode Existing RenderNode, or {@code null}
16409     * @return A valid display list for the specified drawable
16410     */
16411    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
16412        if (renderNode == null) {
16413            renderNode = RenderNode.create(drawable.getClass().getName(), this);
16414        }
16415
16416        final Rect bounds = drawable.getBounds();
16417        final int width = bounds.width();
16418        final int height = bounds.height();
16419        final DisplayListCanvas canvas = renderNode.start(width, height);
16420
16421        // Reverse left/top translation done by drawable canvas, which will
16422        // instead be applied by rendernode's LTRB bounds below. This way, the
16423        // drawable's bounds match with its rendernode bounds and its content
16424        // will lie within those bounds in the rendernode tree.
16425        canvas.translate(-bounds.left, -bounds.top);
16426
16427        try {
16428            drawable.draw(canvas);
16429        } finally {
16430            renderNode.end(canvas);
16431        }
16432
16433        // Set up drawable properties that are view-independent.
16434        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
16435        renderNode.setProjectBackwards(drawable.isProjected());
16436        renderNode.setProjectionReceiver(true);
16437        renderNode.setClipToBounds(false);
16438        return renderNode;
16439    }
16440
16441    /**
16442     * Returns the overlay for this view, creating it if it does not yet exist.
16443     * Adding drawables to the overlay will cause them to be displayed whenever
16444     * the view itself is redrawn. Objects in the overlay should be actively
16445     * managed: remove them when they should not be displayed anymore. The
16446     * overlay will always have the same size as its host view.
16447     *
16448     * <p>Note: Overlays do not currently work correctly with {@link
16449     * SurfaceView} or {@link TextureView}; contents in overlays for these
16450     * types of views may not display correctly.</p>
16451     *
16452     * @return The ViewOverlay object for this view.
16453     * @see ViewOverlay
16454     */
16455    public ViewOverlay getOverlay() {
16456        if (mOverlay == null) {
16457            mOverlay = new ViewOverlay(mContext, this);
16458        }
16459        return mOverlay;
16460    }
16461
16462    /**
16463     * Override this if your view is known to always be drawn on top of a solid color background,
16464     * and needs to draw fading edges. Returning a non-zero color enables the view system to
16465     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
16466     * should be set to 0xFF.
16467     *
16468     * @see #setVerticalFadingEdgeEnabled(boolean)
16469     * @see #setHorizontalFadingEdgeEnabled(boolean)
16470     *
16471     * @return The known solid color background for this view, or 0 if the color may vary
16472     */
16473    @ViewDebug.ExportedProperty(category = "drawing")
16474    @ColorInt
16475    public int getSolidColor() {
16476        return 0;
16477    }
16478
16479    /**
16480     * Build a human readable string representation of the specified view flags.
16481     *
16482     * @param flags the view flags to convert to a string
16483     * @return a String representing the supplied flags
16484     */
16485    private static String printFlags(int flags) {
16486        String output = "";
16487        int numFlags = 0;
16488        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
16489            output += "TAKES_FOCUS";
16490            numFlags++;
16491        }
16492
16493        switch (flags & VISIBILITY_MASK) {
16494        case INVISIBLE:
16495            if (numFlags > 0) {
16496                output += " ";
16497            }
16498            output += "INVISIBLE";
16499            // USELESS HERE numFlags++;
16500            break;
16501        case GONE:
16502            if (numFlags > 0) {
16503                output += " ";
16504            }
16505            output += "GONE";
16506            // USELESS HERE numFlags++;
16507            break;
16508        default:
16509            break;
16510        }
16511        return output;
16512    }
16513
16514    /**
16515     * Build a human readable string representation of the specified private
16516     * view flags.
16517     *
16518     * @param privateFlags the private view flags to convert to a string
16519     * @return a String representing the supplied flags
16520     */
16521    private static String printPrivateFlags(int privateFlags) {
16522        String output = "";
16523        int numFlags = 0;
16524
16525        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
16526            output += "WANTS_FOCUS";
16527            numFlags++;
16528        }
16529
16530        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
16531            if (numFlags > 0) {
16532                output += " ";
16533            }
16534            output += "FOCUSED";
16535            numFlags++;
16536        }
16537
16538        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
16539            if (numFlags > 0) {
16540                output += " ";
16541            }
16542            output += "SELECTED";
16543            numFlags++;
16544        }
16545
16546        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
16547            if (numFlags > 0) {
16548                output += " ";
16549            }
16550            output += "IS_ROOT_NAMESPACE";
16551            numFlags++;
16552        }
16553
16554        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
16555            if (numFlags > 0) {
16556                output += " ";
16557            }
16558            output += "HAS_BOUNDS";
16559            numFlags++;
16560        }
16561
16562        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
16563            if (numFlags > 0) {
16564                output += " ";
16565            }
16566            output += "DRAWN";
16567            // USELESS HERE numFlags++;
16568        }
16569        return output;
16570    }
16571
16572    /**
16573     * <p>Indicates whether or not this view's layout will be requested during
16574     * the next hierarchy layout pass.</p>
16575     *
16576     * @return true if the layout will be forced during next layout pass
16577     */
16578    public boolean isLayoutRequested() {
16579        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
16580    }
16581
16582    /**
16583     * Return true if o is a ViewGroup that is laying out using optical bounds.
16584     * @hide
16585     */
16586    public static boolean isLayoutModeOptical(Object o) {
16587        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
16588    }
16589
16590    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
16591        Insets parentInsets = mParent instanceof View ?
16592                ((View) mParent).getOpticalInsets() : Insets.NONE;
16593        Insets childInsets = getOpticalInsets();
16594        return setFrame(
16595                left   + parentInsets.left - childInsets.left,
16596                top    + parentInsets.top  - childInsets.top,
16597                right  + parentInsets.left + childInsets.right,
16598                bottom + parentInsets.top  + childInsets.bottom);
16599    }
16600
16601    /**
16602     * Assign a size and position to a view and all of its
16603     * descendants
16604     *
16605     * <p>This is the second phase of the layout mechanism.
16606     * (The first is measuring). In this phase, each parent calls
16607     * layout on all of its children to position them.
16608     * This is typically done using the child measurements
16609     * that were stored in the measure pass().</p>
16610     *
16611     * <p>Derived classes should not override this method.
16612     * Derived classes with children should override
16613     * onLayout. In that method, they should
16614     * call layout on each of their children.</p>
16615     *
16616     * @param l Left position, relative to parent
16617     * @param t Top position, relative to parent
16618     * @param r Right position, relative to parent
16619     * @param b Bottom position, relative to parent
16620     */
16621    @SuppressWarnings({"unchecked"})
16622    public void layout(int l, int t, int r, int b) {
16623        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
16624            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
16625            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16626        }
16627
16628        int oldL = mLeft;
16629        int oldT = mTop;
16630        int oldB = mBottom;
16631        int oldR = mRight;
16632
16633        boolean changed = isLayoutModeOptical(mParent) ?
16634                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
16635
16636        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
16637            onLayout(changed, l, t, r, b);
16638            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
16639
16640            ListenerInfo li = mListenerInfo;
16641            if (li != null && li.mOnLayoutChangeListeners != null) {
16642                ArrayList<OnLayoutChangeListener> listenersCopy =
16643                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16644                int numListeners = listenersCopy.size();
16645                for (int i = 0; i < numListeners; ++i) {
16646                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16647                }
16648            }
16649        }
16650
16651        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16652        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16653    }
16654
16655    /**
16656     * Called from layout when this view should
16657     * assign a size and position to each of its children.
16658     *
16659     * Derived classes with children should override
16660     * this method and call layout on each of
16661     * their children.
16662     * @param changed This is a new size or position for this view
16663     * @param left Left position, relative to parent
16664     * @param top Top position, relative to parent
16665     * @param right Right position, relative to parent
16666     * @param bottom Bottom position, relative to parent
16667     */
16668    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16669    }
16670
16671    /**
16672     * Assign a size and position to this view.
16673     *
16674     * This is called from layout.
16675     *
16676     * @param left Left position, relative to parent
16677     * @param top Top position, relative to parent
16678     * @param right Right position, relative to parent
16679     * @param bottom Bottom position, relative to parent
16680     * @return true if the new size and position are different than the
16681     *         previous ones
16682     * {@hide}
16683     */
16684    protected boolean setFrame(int left, int top, int right, int bottom) {
16685        boolean changed = false;
16686
16687        if (DBG) {
16688            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16689                    + right + "," + bottom + ")");
16690        }
16691
16692        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16693            changed = true;
16694
16695            // Remember our drawn bit
16696            int drawn = mPrivateFlags & PFLAG_DRAWN;
16697
16698            int oldWidth = mRight - mLeft;
16699            int oldHeight = mBottom - mTop;
16700            int newWidth = right - left;
16701            int newHeight = bottom - top;
16702            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16703
16704            // Invalidate our old position
16705            invalidate(sizeChanged);
16706
16707            mLeft = left;
16708            mTop = top;
16709            mRight = right;
16710            mBottom = bottom;
16711            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16712
16713            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16714
16715
16716            if (sizeChanged) {
16717                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16718            }
16719
16720            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16721                // If we are visible, force the DRAWN bit to on so that
16722                // this invalidate will go through (at least to our parent).
16723                // This is because someone may have invalidated this view
16724                // before this call to setFrame came in, thereby clearing
16725                // the DRAWN bit.
16726                mPrivateFlags |= PFLAG_DRAWN;
16727                invalidate(sizeChanged);
16728                // parent display list may need to be recreated based on a change in the bounds
16729                // of any child
16730                invalidateParentCaches();
16731            }
16732
16733            // Reset drawn bit to original value (invalidate turns it off)
16734            mPrivateFlags |= drawn;
16735
16736            mBackgroundSizeChanged = true;
16737            if (mForegroundInfo != null) {
16738                mForegroundInfo.mBoundsChanged = true;
16739            }
16740
16741            notifySubtreeAccessibilityStateChangedIfNeeded();
16742        }
16743        return changed;
16744    }
16745
16746    /**
16747     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16748     * @hide
16749     */
16750    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16751        setFrame(left, top, right, bottom);
16752    }
16753
16754    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16755        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16756        if (mOverlay != null) {
16757            mOverlay.getOverlayView().setRight(newWidth);
16758            mOverlay.getOverlayView().setBottom(newHeight);
16759        }
16760        rebuildOutline();
16761    }
16762
16763    /**
16764     * Finalize inflating a view from XML.  This is called as the last phase
16765     * of inflation, after all child views have been added.
16766     *
16767     * <p>Even if the subclass overrides onFinishInflate, they should always be
16768     * sure to call the super method, so that we get called.
16769     */
16770    @CallSuper
16771    protected void onFinishInflate() {
16772    }
16773
16774    /**
16775     * Returns the resources associated with this view.
16776     *
16777     * @return Resources object.
16778     */
16779    public Resources getResources() {
16780        return mResources;
16781    }
16782
16783    /**
16784     * Invalidates the specified Drawable.
16785     *
16786     * @param drawable the drawable to invalidate
16787     */
16788    @Override
16789    public void invalidateDrawable(@NonNull Drawable drawable) {
16790        if (verifyDrawable(drawable)) {
16791            final Rect dirty = drawable.getDirtyBounds();
16792            final int scrollX = mScrollX;
16793            final int scrollY = mScrollY;
16794
16795            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16796                    dirty.right + scrollX, dirty.bottom + scrollY);
16797            rebuildOutline();
16798        }
16799    }
16800
16801    /**
16802     * Schedules an action on a drawable to occur at a specified time.
16803     *
16804     * @param who the recipient of the action
16805     * @param what the action to run on the drawable
16806     * @param when the time at which the action must occur. Uses the
16807     *        {@link SystemClock#uptimeMillis} timebase.
16808     */
16809    @Override
16810    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16811        if (verifyDrawable(who) && what != null) {
16812            final long delay = when - SystemClock.uptimeMillis();
16813            if (mAttachInfo != null) {
16814                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16815                        Choreographer.CALLBACK_ANIMATION, what, who,
16816                        Choreographer.subtractFrameDelay(delay));
16817            } else {
16818                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16819            }
16820        }
16821    }
16822
16823    /**
16824     * Cancels a scheduled action on a drawable.
16825     *
16826     * @param who the recipient of the action
16827     * @param what the action to cancel
16828     */
16829    @Override
16830    public void unscheduleDrawable(Drawable who, Runnable what) {
16831        if (verifyDrawable(who) && what != null) {
16832            if (mAttachInfo != null) {
16833                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16834                        Choreographer.CALLBACK_ANIMATION, what, who);
16835            }
16836            ViewRootImpl.getRunQueue().removeCallbacks(what);
16837        }
16838    }
16839
16840    /**
16841     * Unschedule any events associated with the given Drawable.  This can be
16842     * used when selecting a new Drawable into a view, so that the previous
16843     * one is completely unscheduled.
16844     *
16845     * @param who The Drawable to unschedule.
16846     *
16847     * @see #drawableStateChanged
16848     */
16849    public void unscheduleDrawable(Drawable who) {
16850        if (mAttachInfo != null && who != null) {
16851            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16852                    Choreographer.CALLBACK_ANIMATION, null, who);
16853        }
16854    }
16855
16856    /**
16857     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16858     * that the View directionality can and will be resolved before its Drawables.
16859     *
16860     * Will call {@link View#onResolveDrawables} when resolution is done.
16861     *
16862     * @hide
16863     */
16864    protected void resolveDrawables() {
16865        // Drawables resolution may need to happen before resolving the layout direction (which is
16866        // done only during the measure() call).
16867        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16868        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16869        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16870        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16871        // direction to be resolved as its resolved value will be the same as its raw value.
16872        if (!isLayoutDirectionResolved() &&
16873                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16874            return;
16875        }
16876
16877        final int layoutDirection = isLayoutDirectionResolved() ?
16878                getLayoutDirection() : getRawLayoutDirection();
16879
16880        if (mBackground != null) {
16881            mBackground.setLayoutDirection(layoutDirection);
16882        }
16883        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16884            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16885        }
16886        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16887        onResolveDrawables(layoutDirection);
16888    }
16889
16890    boolean areDrawablesResolved() {
16891        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16892    }
16893
16894    /**
16895     * Called when layout direction has been resolved.
16896     *
16897     * The default implementation does nothing.
16898     *
16899     * @param layoutDirection The resolved layout direction.
16900     *
16901     * @see #LAYOUT_DIRECTION_LTR
16902     * @see #LAYOUT_DIRECTION_RTL
16903     *
16904     * @hide
16905     */
16906    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16907    }
16908
16909    /**
16910     * @hide
16911     */
16912    protected void resetResolvedDrawables() {
16913        resetResolvedDrawablesInternal();
16914    }
16915
16916    void resetResolvedDrawablesInternal() {
16917        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16918    }
16919
16920    /**
16921     * If your view subclass is displaying its own Drawable objects, it should
16922     * override this function and return true for any Drawable it is
16923     * displaying.  This allows animations for those drawables to be
16924     * scheduled.
16925     *
16926     * <p>Be sure to call through to the super class when overriding this
16927     * function.
16928     *
16929     * @param who The Drawable to verify.  Return true if it is one you are
16930     *            displaying, else return the result of calling through to the
16931     *            super class.
16932     *
16933     * @return boolean If true than the Drawable is being displayed in the
16934     *         view; else false and it is not allowed to animate.
16935     *
16936     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16937     * @see #drawableStateChanged()
16938     */
16939    @CallSuper
16940    protected boolean verifyDrawable(Drawable who) {
16941        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16942                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16943    }
16944
16945    /**
16946     * This function is called whenever the state of the view changes in such
16947     * a way that it impacts the state of drawables being shown.
16948     * <p>
16949     * If the View has a StateListAnimator, it will also be called to run necessary state
16950     * change animations.
16951     * <p>
16952     * Be sure to call through to the superclass when overriding this function.
16953     *
16954     * @see Drawable#setState(int[])
16955     */
16956    @CallSuper
16957    protected void drawableStateChanged() {
16958        final int[] state = getDrawableState();
16959
16960        final Drawable bg = mBackground;
16961        if (bg != null && bg.isStateful()) {
16962            bg.setState(state);
16963        }
16964
16965        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16966        if (fg != null && fg.isStateful()) {
16967            fg.setState(state);
16968        }
16969
16970        if (mScrollCache != null) {
16971            final Drawable scrollBar = mScrollCache.scrollBar;
16972            if (scrollBar != null && scrollBar.isStateful()) {
16973                scrollBar.setState(state);
16974            }
16975        }
16976
16977        if (mStateListAnimator != null) {
16978            mStateListAnimator.setState(state);
16979        }
16980    }
16981
16982    /**
16983     * This function is called whenever the view hotspot changes and needs to
16984     * be propagated to drawables or child views managed by the view.
16985     * <p>
16986     * Dispatching to child views is handled by
16987     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16988     * <p>
16989     * Be sure to call through to the superclass when overriding this function.
16990     *
16991     * @param x hotspot x coordinate
16992     * @param y hotspot y coordinate
16993     */
16994    @CallSuper
16995    public void drawableHotspotChanged(float x, float y) {
16996        if (mBackground != null) {
16997            mBackground.setHotspot(x, y);
16998        }
16999        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17000            mForegroundInfo.mDrawable.setHotspot(x, y);
17001        }
17002
17003        dispatchDrawableHotspotChanged(x, y);
17004    }
17005
17006    /**
17007     * Dispatches drawableHotspotChanged to all of this View's children.
17008     *
17009     * @param x hotspot x coordinate
17010     * @param y hotspot y coordinate
17011     * @see #drawableHotspotChanged(float, float)
17012     */
17013    public void dispatchDrawableHotspotChanged(float x, float y) {
17014    }
17015
17016    /**
17017     * Call this to force a view to update its drawable state. This will cause
17018     * drawableStateChanged to be called on this view. Views that are interested
17019     * in the new state should call getDrawableState.
17020     *
17021     * @see #drawableStateChanged
17022     * @see #getDrawableState
17023     */
17024    public void refreshDrawableState() {
17025        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17026        drawableStateChanged();
17027
17028        ViewParent parent = mParent;
17029        if (parent != null) {
17030            parent.childDrawableStateChanged(this);
17031        }
17032    }
17033
17034    /**
17035     * Return an array of resource IDs of the drawable states representing the
17036     * current state of the view.
17037     *
17038     * @return The current drawable state
17039     *
17040     * @see Drawable#setState(int[])
17041     * @see #drawableStateChanged()
17042     * @see #onCreateDrawableState(int)
17043     */
17044    public final int[] getDrawableState() {
17045        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17046            return mDrawableState;
17047        } else {
17048            mDrawableState = onCreateDrawableState(0);
17049            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17050            return mDrawableState;
17051        }
17052    }
17053
17054    /**
17055     * Generate the new {@link android.graphics.drawable.Drawable} state for
17056     * this view. This is called by the view
17057     * system when the cached Drawable state is determined to be invalid.  To
17058     * retrieve the current state, you should use {@link #getDrawableState}.
17059     *
17060     * @param extraSpace if non-zero, this is the number of extra entries you
17061     * would like in the returned array in which you can place your own
17062     * states.
17063     *
17064     * @return Returns an array holding the current {@link Drawable} state of
17065     * the view.
17066     *
17067     * @see #mergeDrawableStates(int[], int[])
17068     */
17069    protected int[] onCreateDrawableState(int extraSpace) {
17070        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17071                mParent instanceof View) {
17072            return ((View) mParent).onCreateDrawableState(extraSpace);
17073        }
17074
17075        int[] drawableState;
17076
17077        int privateFlags = mPrivateFlags;
17078
17079        int viewStateIndex = 0;
17080        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17081        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17082        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17083        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17084        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17085        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17086        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17087                HardwareRenderer.isAvailable()) {
17088            // This is set if HW acceleration is requested, even if the current
17089            // process doesn't allow it.  This is just to allow app preview
17090            // windows to better match their app.
17091            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17092        }
17093        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17094
17095        final int privateFlags2 = mPrivateFlags2;
17096        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17097            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17098        }
17099        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17100            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17101        }
17102
17103        drawableState = StateSet.get(viewStateIndex);
17104
17105        //noinspection ConstantIfStatement
17106        if (false) {
17107            Log.i("View", "drawableStateIndex=" + viewStateIndex);
17108            Log.i("View", toString()
17109                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
17110                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
17111                    + " fo=" + hasFocus()
17112                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
17113                    + " wf=" + hasWindowFocus()
17114                    + ": " + Arrays.toString(drawableState));
17115        }
17116
17117        if (extraSpace == 0) {
17118            return drawableState;
17119        }
17120
17121        final int[] fullState;
17122        if (drawableState != null) {
17123            fullState = new int[drawableState.length + extraSpace];
17124            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
17125        } else {
17126            fullState = new int[extraSpace];
17127        }
17128
17129        return fullState;
17130    }
17131
17132    /**
17133     * Merge your own state values in <var>additionalState</var> into the base
17134     * state values <var>baseState</var> that were returned by
17135     * {@link #onCreateDrawableState(int)}.
17136     *
17137     * @param baseState The base state values returned by
17138     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
17139     * own additional state values.
17140     *
17141     * @param additionalState The additional state values you would like
17142     * added to <var>baseState</var>; this array is not modified.
17143     *
17144     * @return As a convenience, the <var>baseState</var> array you originally
17145     * passed into the function is returned.
17146     *
17147     * @see #onCreateDrawableState(int)
17148     */
17149    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
17150        final int N = baseState.length;
17151        int i = N - 1;
17152        while (i >= 0 && baseState[i] == 0) {
17153            i--;
17154        }
17155        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
17156        return baseState;
17157    }
17158
17159    /**
17160     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
17161     * on all Drawable objects associated with this view.
17162     * <p>
17163     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
17164     * attached to this view.
17165     */
17166    @CallSuper
17167    public void jumpDrawablesToCurrentState() {
17168        if (mBackground != null) {
17169            mBackground.jumpToCurrentState();
17170        }
17171        if (mStateListAnimator != null) {
17172            mStateListAnimator.jumpToCurrentState();
17173        }
17174        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17175            mForegroundInfo.mDrawable.jumpToCurrentState();
17176        }
17177    }
17178
17179    /**
17180     * Sets the background color for this view.
17181     * @param color the color of the background
17182     */
17183    @RemotableViewMethod
17184    public void setBackgroundColor(@ColorInt int color) {
17185        if (mBackground instanceof ColorDrawable) {
17186            ((ColorDrawable) mBackground.mutate()).setColor(color);
17187            computeOpaqueFlags();
17188            mBackgroundResource = 0;
17189        } else {
17190            setBackground(new ColorDrawable(color));
17191        }
17192    }
17193
17194    /**
17195     * Set the background to a given resource. The resource should refer to
17196     * a Drawable object or 0 to remove the background.
17197     * @param resid The identifier of the resource.
17198     *
17199     * @attr ref android.R.styleable#View_background
17200     */
17201    @RemotableViewMethod
17202    public void setBackgroundResource(@DrawableRes int resid) {
17203        if (resid != 0 && resid == mBackgroundResource) {
17204            return;
17205        }
17206
17207        Drawable d = null;
17208        if (resid != 0) {
17209            d = mContext.getDrawable(resid);
17210        }
17211        setBackground(d);
17212
17213        mBackgroundResource = resid;
17214    }
17215
17216    /**
17217     * Set the background to a given Drawable, or remove the background. If the
17218     * background has padding, this View's padding is set to the background's
17219     * padding. However, when a background is removed, this View's padding isn't
17220     * touched. If setting the padding is desired, please use
17221     * {@link #setPadding(int, int, int, int)}.
17222     *
17223     * @param background The Drawable to use as the background, or null to remove the
17224     *        background
17225     */
17226    public void setBackground(Drawable background) {
17227        //noinspection deprecation
17228        setBackgroundDrawable(background);
17229    }
17230
17231    /**
17232     * @deprecated use {@link #setBackground(Drawable)} instead
17233     */
17234    @Deprecated
17235    public void setBackgroundDrawable(Drawable background) {
17236        computeOpaqueFlags();
17237
17238        if (background == mBackground) {
17239            return;
17240        }
17241
17242        boolean requestLayout = false;
17243
17244        mBackgroundResource = 0;
17245
17246        /*
17247         * Regardless of whether we're setting a new background or not, we want
17248         * to clear the previous drawable.
17249         */
17250        if (mBackground != null) {
17251            mBackground.setCallback(null);
17252            unscheduleDrawable(mBackground);
17253        }
17254
17255        if (background != null) {
17256            Rect padding = sThreadLocal.get();
17257            if (padding == null) {
17258                padding = new Rect();
17259                sThreadLocal.set(padding);
17260            }
17261            resetResolvedDrawablesInternal();
17262            background.setLayoutDirection(getLayoutDirection());
17263            if (background.getPadding(padding)) {
17264                resetResolvedPaddingInternal();
17265                switch (background.getLayoutDirection()) {
17266                    case LAYOUT_DIRECTION_RTL:
17267                        mUserPaddingLeftInitial = padding.right;
17268                        mUserPaddingRightInitial = padding.left;
17269                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
17270                        break;
17271                    case LAYOUT_DIRECTION_LTR:
17272                    default:
17273                        mUserPaddingLeftInitial = padding.left;
17274                        mUserPaddingRightInitial = padding.right;
17275                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
17276                }
17277                mLeftPaddingDefined = false;
17278                mRightPaddingDefined = false;
17279            }
17280
17281            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
17282            // if it has a different minimum size, we should layout again
17283            if (mBackground == null
17284                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
17285                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
17286                requestLayout = true;
17287            }
17288
17289            background.setCallback(this);
17290            if (background.isStateful()) {
17291                background.setState(getDrawableState());
17292            }
17293            background.setVisible(getVisibility() == VISIBLE, false);
17294            mBackground = background;
17295
17296            applyBackgroundTint();
17297
17298            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
17299                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
17300                requestLayout = true;
17301            }
17302        } else {
17303            /* Remove the background */
17304            mBackground = null;
17305            if ((mViewFlags & WILL_NOT_DRAW) != 0
17306                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
17307                mPrivateFlags |= PFLAG_SKIP_DRAW;
17308            }
17309
17310            /*
17311             * When the background is set, we try to apply its padding to this
17312             * View. When the background is removed, we don't touch this View's
17313             * padding. This is noted in the Javadocs. Hence, we don't need to
17314             * requestLayout(), the invalidate() below is sufficient.
17315             */
17316
17317            // The old background's minimum size could have affected this
17318            // View's layout, so let's requestLayout
17319            requestLayout = true;
17320        }
17321
17322        computeOpaqueFlags();
17323
17324        if (requestLayout) {
17325            requestLayout();
17326        }
17327
17328        mBackgroundSizeChanged = true;
17329        invalidate(true);
17330    }
17331
17332    /**
17333     * Gets the background drawable
17334     *
17335     * @return The drawable used as the background for this view, if any.
17336     *
17337     * @see #setBackground(Drawable)
17338     *
17339     * @attr ref android.R.styleable#View_background
17340     */
17341    public Drawable getBackground() {
17342        return mBackground;
17343    }
17344
17345    /**
17346     * Applies a tint to the background drawable. Does not modify the current tint
17347     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17348     * <p>
17349     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
17350     * mutate the drawable and apply the specified tint and tint mode using
17351     * {@link Drawable#setTintList(ColorStateList)}.
17352     *
17353     * @param tint the tint to apply, may be {@code null} to clear tint
17354     *
17355     * @attr ref android.R.styleable#View_backgroundTint
17356     * @see #getBackgroundTintList()
17357     * @see Drawable#setTintList(ColorStateList)
17358     */
17359    public void setBackgroundTintList(@Nullable ColorStateList tint) {
17360        if (mBackgroundTint == null) {
17361            mBackgroundTint = new TintInfo();
17362        }
17363        mBackgroundTint.mTintList = tint;
17364        mBackgroundTint.mHasTintList = true;
17365
17366        applyBackgroundTint();
17367    }
17368
17369    /**
17370     * Return the tint applied to the background drawable, if specified.
17371     *
17372     * @return the tint applied to the background drawable
17373     * @attr ref android.R.styleable#View_backgroundTint
17374     * @see #setBackgroundTintList(ColorStateList)
17375     */
17376    @Nullable
17377    public ColorStateList getBackgroundTintList() {
17378        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
17379    }
17380
17381    /**
17382     * Specifies the blending mode used to apply the tint specified by
17383     * {@link #setBackgroundTintList(ColorStateList)}} to the background
17384     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17385     *
17386     * @param tintMode the blending mode used to apply the tint, may be
17387     *                 {@code null} to clear tint
17388     * @attr ref android.R.styleable#View_backgroundTintMode
17389     * @see #getBackgroundTintMode()
17390     * @see Drawable#setTintMode(PorterDuff.Mode)
17391     */
17392    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17393        if (mBackgroundTint == null) {
17394            mBackgroundTint = new TintInfo();
17395        }
17396        mBackgroundTint.mTintMode = tintMode;
17397        mBackgroundTint.mHasTintMode = true;
17398
17399        applyBackgroundTint();
17400    }
17401
17402    /**
17403     * Return the blending mode used to apply the tint to the background
17404     * drawable, if specified.
17405     *
17406     * @return the blending mode used to apply the tint to the background
17407     *         drawable
17408     * @attr ref android.R.styleable#View_backgroundTintMode
17409     * @see #setBackgroundTintMode(PorterDuff.Mode)
17410     */
17411    @Nullable
17412    public PorterDuff.Mode getBackgroundTintMode() {
17413        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
17414    }
17415
17416    private void applyBackgroundTint() {
17417        if (mBackground != null && mBackgroundTint != null) {
17418            final TintInfo tintInfo = mBackgroundTint;
17419            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17420                mBackground = mBackground.mutate();
17421
17422                if (tintInfo.mHasTintList) {
17423                    mBackground.setTintList(tintInfo.mTintList);
17424                }
17425
17426                if (tintInfo.mHasTintMode) {
17427                    mBackground.setTintMode(tintInfo.mTintMode);
17428                }
17429
17430                // The drawable (or one of its children) may not have been
17431                // stateful before applying the tint, so let's try again.
17432                if (mBackground.isStateful()) {
17433                    mBackground.setState(getDrawableState());
17434                }
17435            }
17436        }
17437    }
17438
17439    /**
17440     * Returns the drawable used as the foreground of this View. The
17441     * foreground drawable, if non-null, is always drawn on top of the view's content.
17442     *
17443     * @return a Drawable or null if no foreground was set
17444     *
17445     * @see #onDrawForeground(Canvas)
17446     */
17447    public Drawable getForeground() {
17448        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17449    }
17450
17451    /**
17452     * Supply a Drawable that is to be rendered on top of all of the content in the view.
17453     *
17454     * @param foreground the Drawable to be drawn on top of the children
17455     *
17456     * @attr ref android.R.styleable#View_foreground
17457     */
17458    public void setForeground(Drawable foreground) {
17459        if (mForegroundInfo == null) {
17460            if (foreground == null) {
17461                // Nothing to do.
17462                return;
17463            }
17464            mForegroundInfo = new ForegroundInfo();
17465        }
17466
17467        if (foreground == mForegroundInfo.mDrawable) {
17468            // Nothing to do
17469            return;
17470        }
17471
17472        if (mForegroundInfo.mDrawable != null) {
17473            mForegroundInfo.mDrawable.setCallback(null);
17474            unscheduleDrawable(mForegroundInfo.mDrawable);
17475        }
17476
17477        mForegroundInfo.mDrawable = foreground;
17478        mForegroundInfo.mBoundsChanged = true;
17479        if (foreground != null) {
17480            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
17481                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
17482            }
17483            foreground.setCallback(this);
17484            foreground.setLayoutDirection(getLayoutDirection());
17485            if (foreground.isStateful()) {
17486                foreground.setState(getDrawableState());
17487            }
17488            applyForegroundTint();
17489        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
17490            mPrivateFlags |= PFLAG_SKIP_DRAW;
17491        }
17492        requestLayout();
17493        invalidate();
17494    }
17495
17496    /**
17497     * Magic bit used to support features of framework-internal window decor implementation details.
17498     * This used to live exclusively in FrameLayout.
17499     *
17500     * @return true if the foreground should draw inside the padding region or false
17501     *         if it should draw inset by the view's padding
17502     * @hide internal use only; only used by FrameLayout and internal screen layouts.
17503     */
17504    public boolean isForegroundInsidePadding() {
17505        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
17506    }
17507
17508    /**
17509     * Describes how the foreground is positioned.
17510     *
17511     * @return foreground gravity.
17512     *
17513     * @see #setForegroundGravity(int)
17514     *
17515     * @attr ref android.R.styleable#View_foregroundGravity
17516     */
17517    public int getForegroundGravity() {
17518        return mForegroundInfo != null ? mForegroundInfo.mGravity
17519                : Gravity.START | Gravity.TOP;
17520    }
17521
17522    /**
17523     * Describes how the foreground is positioned. Defaults to START and TOP.
17524     *
17525     * @param gravity see {@link android.view.Gravity}
17526     *
17527     * @see #getForegroundGravity()
17528     *
17529     * @attr ref android.R.styleable#View_foregroundGravity
17530     */
17531    public void setForegroundGravity(int gravity) {
17532        if (mForegroundInfo == null) {
17533            mForegroundInfo = new ForegroundInfo();
17534        }
17535
17536        if (mForegroundInfo.mGravity != gravity) {
17537            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
17538                gravity |= Gravity.START;
17539            }
17540
17541            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
17542                gravity |= Gravity.TOP;
17543            }
17544
17545            mForegroundInfo.mGravity = gravity;
17546            requestLayout();
17547        }
17548    }
17549
17550    /**
17551     * Applies a tint to the foreground drawable. Does not modify the current tint
17552     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17553     * <p>
17554     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
17555     * mutate the drawable and apply the specified tint and tint mode using
17556     * {@link Drawable#setTintList(ColorStateList)}.
17557     *
17558     * @param tint the tint to apply, may be {@code null} to clear tint
17559     *
17560     * @attr ref android.R.styleable#View_foregroundTint
17561     * @see #getForegroundTintList()
17562     * @see Drawable#setTintList(ColorStateList)
17563     */
17564    public void setForegroundTintList(@Nullable ColorStateList tint) {
17565        if (mForegroundInfo == null) {
17566            mForegroundInfo = new ForegroundInfo();
17567        }
17568        if (mForegroundInfo.mTintInfo == null) {
17569            mForegroundInfo.mTintInfo = new TintInfo();
17570        }
17571        mForegroundInfo.mTintInfo.mTintList = tint;
17572        mForegroundInfo.mTintInfo.mHasTintList = true;
17573
17574        applyForegroundTint();
17575    }
17576
17577    /**
17578     * Return the tint applied to the foreground drawable, if specified.
17579     *
17580     * @return the tint applied to the foreground drawable
17581     * @attr ref android.R.styleable#View_foregroundTint
17582     * @see #setForegroundTintList(ColorStateList)
17583     */
17584    @Nullable
17585    public ColorStateList getForegroundTintList() {
17586        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17587                ? mForegroundInfo.mTintInfo.mTintList : null;
17588    }
17589
17590    /**
17591     * Specifies the blending mode used to apply the tint specified by
17592     * {@link #setForegroundTintList(ColorStateList)}} to the background
17593     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17594     *
17595     * @param tintMode the blending mode used to apply the tint, may be
17596     *                 {@code null} to clear tint
17597     * @attr ref android.R.styleable#View_foregroundTintMode
17598     * @see #getForegroundTintMode()
17599     * @see Drawable#setTintMode(PorterDuff.Mode)
17600     */
17601    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17602        if (mForegroundInfo == null) {
17603            mForegroundInfo = new ForegroundInfo();
17604        }
17605        if (mForegroundInfo.mTintInfo == null) {
17606            mForegroundInfo.mTintInfo = new TintInfo();
17607        }
17608        mForegroundInfo.mTintInfo.mTintMode = tintMode;
17609        mForegroundInfo.mTintInfo.mHasTintMode = true;
17610
17611        applyForegroundTint();
17612    }
17613
17614    /**
17615     * Return the blending mode used to apply the tint to the foreground
17616     * drawable, if specified.
17617     *
17618     * @return the blending mode used to apply the tint to the foreground
17619     *         drawable
17620     * @attr ref android.R.styleable#View_foregroundTintMode
17621     * @see #setForegroundTintMode(PorterDuff.Mode)
17622     */
17623    @Nullable
17624    public PorterDuff.Mode getForegroundTintMode() {
17625        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17626                ? mForegroundInfo.mTintInfo.mTintMode : null;
17627    }
17628
17629    private void applyForegroundTint() {
17630        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17631                && mForegroundInfo.mTintInfo != null) {
17632            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17633            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17634                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17635
17636                if (tintInfo.mHasTintList) {
17637                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17638                }
17639
17640                if (tintInfo.mHasTintMode) {
17641                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17642                }
17643
17644                // The drawable (or one of its children) may not have been
17645                // stateful before applying the tint, so let's try again.
17646                if (mForegroundInfo.mDrawable.isStateful()) {
17647                    mForegroundInfo.mDrawable.setState(getDrawableState());
17648                }
17649            }
17650        }
17651    }
17652
17653    /**
17654     * Draw any foreground content for this view.
17655     *
17656     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17657     * drawable or other view-specific decorations. The foreground is drawn on top of the
17658     * primary view content.</p>
17659     *
17660     * @param canvas canvas to draw into
17661     */
17662    public void onDrawForeground(Canvas canvas) {
17663        onDrawScrollIndicators(canvas);
17664        onDrawScrollBars(canvas);
17665
17666        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17667        if (foreground != null) {
17668            if (mForegroundInfo.mBoundsChanged) {
17669                mForegroundInfo.mBoundsChanged = false;
17670                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17671                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17672
17673                if (mForegroundInfo.mInsidePadding) {
17674                    selfBounds.set(0, 0, getWidth(), getHeight());
17675                } else {
17676                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17677                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17678                }
17679
17680                final int ld = getLayoutDirection();
17681                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17682                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17683                foreground.setBounds(overlayBounds);
17684            }
17685
17686            foreground.draw(canvas);
17687        }
17688    }
17689
17690    /**
17691     * Sets the padding. The view may add on the space required to display
17692     * the scrollbars, depending on the style and visibility of the scrollbars.
17693     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17694     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17695     * from the values set in this call.
17696     *
17697     * @attr ref android.R.styleable#View_padding
17698     * @attr ref android.R.styleable#View_paddingBottom
17699     * @attr ref android.R.styleable#View_paddingLeft
17700     * @attr ref android.R.styleable#View_paddingRight
17701     * @attr ref android.R.styleable#View_paddingTop
17702     * @param left the left padding in pixels
17703     * @param top the top padding in pixels
17704     * @param right the right padding in pixels
17705     * @param bottom the bottom padding in pixels
17706     */
17707    public void setPadding(int left, int top, int right, int bottom) {
17708        resetResolvedPaddingInternal();
17709
17710        mUserPaddingStart = UNDEFINED_PADDING;
17711        mUserPaddingEnd = UNDEFINED_PADDING;
17712
17713        mUserPaddingLeftInitial = left;
17714        mUserPaddingRightInitial = right;
17715
17716        mLeftPaddingDefined = true;
17717        mRightPaddingDefined = true;
17718
17719        internalSetPadding(left, top, right, bottom);
17720    }
17721
17722    /**
17723     * @hide
17724     */
17725    protected void internalSetPadding(int left, int top, int right, int bottom) {
17726        mUserPaddingLeft = left;
17727        mUserPaddingRight = right;
17728        mUserPaddingBottom = bottom;
17729
17730        final int viewFlags = mViewFlags;
17731        boolean changed = false;
17732
17733        // Common case is there are no scroll bars.
17734        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17735            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17736                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17737                        ? 0 : getVerticalScrollbarWidth();
17738                switch (mVerticalScrollbarPosition) {
17739                    case SCROLLBAR_POSITION_DEFAULT:
17740                        if (isLayoutRtl()) {
17741                            left += offset;
17742                        } else {
17743                            right += offset;
17744                        }
17745                        break;
17746                    case SCROLLBAR_POSITION_RIGHT:
17747                        right += offset;
17748                        break;
17749                    case SCROLLBAR_POSITION_LEFT:
17750                        left += offset;
17751                        break;
17752                }
17753            }
17754            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17755                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17756                        ? 0 : getHorizontalScrollbarHeight();
17757            }
17758        }
17759
17760        if (mPaddingLeft != left) {
17761            changed = true;
17762            mPaddingLeft = left;
17763        }
17764        if (mPaddingTop != top) {
17765            changed = true;
17766            mPaddingTop = top;
17767        }
17768        if (mPaddingRight != right) {
17769            changed = true;
17770            mPaddingRight = right;
17771        }
17772        if (mPaddingBottom != bottom) {
17773            changed = true;
17774            mPaddingBottom = bottom;
17775        }
17776
17777        if (changed) {
17778            requestLayout();
17779            invalidateOutline();
17780        }
17781    }
17782
17783    /**
17784     * Sets the relative padding. The view may add on the space required to display
17785     * the scrollbars, depending on the style and visibility of the scrollbars.
17786     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17787     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17788     * from the values set in this call.
17789     *
17790     * @attr ref android.R.styleable#View_padding
17791     * @attr ref android.R.styleable#View_paddingBottom
17792     * @attr ref android.R.styleable#View_paddingStart
17793     * @attr ref android.R.styleable#View_paddingEnd
17794     * @attr ref android.R.styleable#View_paddingTop
17795     * @param start the start padding in pixels
17796     * @param top the top padding in pixels
17797     * @param end the end padding in pixels
17798     * @param bottom the bottom padding in pixels
17799     */
17800    public void setPaddingRelative(int start, int top, int end, int bottom) {
17801        resetResolvedPaddingInternal();
17802
17803        mUserPaddingStart = start;
17804        mUserPaddingEnd = end;
17805        mLeftPaddingDefined = true;
17806        mRightPaddingDefined = true;
17807
17808        switch(getLayoutDirection()) {
17809            case LAYOUT_DIRECTION_RTL:
17810                mUserPaddingLeftInitial = end;
17811                mUserPaddingRightInitial = start;
17812                internalSetPadding(end, top, start, bottom);
17813                break;
17814            case LAYOUT_DIRECTION_LTR:
17815            default:
17816                mUserPaddingLeftInitial = start;
17817                mUserPaddingRightInitial = end;
17818                internalSetPadding(start, top, end, bottom);
17819        }
17820    }
17821
17822    /**
17823     * Returns the top padding of this view.
17824     *
17825     * @return the top padding in pixels
17826     */
17827    public int getPaddingTop() {
17828        return mPaddingTop;
17829    }
17830
17831    /**
17832     * Returns the bottom padding of this view. If there are inset and enabled
17833     * scrollbars, this value may include the space required to display the
17834     * scrollbars as well.
17835     *
17836     * @return the bottom padding in pixels
17837     */
17838    public int getPaddingBottom() {
17839        return mPaddingBottom;
17840    }
17841
17842    /**
17843     * Returns the left padding of this view. If there are inset and enabled
17844     * scrollbars, this value may include the space required to display the
17845     * scrollbars as well.
17846     *
17847     * @return the left padding in pixels
17848     */
17849    public int getPaddingLeft() {
17850        if (!isPaddingResolved()) {
17851            resolvePadding();
17852        }
17853        return mPaddingLeft;
17854    }
17855
17856    /**
17857     * Returns the start padding of this view depending on its resolved layout direction.
17858     * If there are inset and enabled scrollbars, this value may include the space
17859     * required to display the scrollbars as well.
17860     *
17861     * @return the start padding in pixels
17862     */
17863    public int getPaddingStart() {
17864        if (!isPaddingResolved()) {
17865            resolvePadding();
17866        }
17867        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17868                mPaddingRight : mPaddingLeft;
17869    }
17870
17871    /**
17872     * Returns the right padding of this view. If there are inset and enabled
17873     * scrollbars, this value may include the space required to display the
17874     * scrollbars as well.
17875     *
17876     * @return the right padding in pixels
17877     */
17878    public int getPaddingRight() {
17879        if (!isPaddingResolved()) {
17880            resolvePadding();
17881        }
17882        return mPaddingRight;
17883    }
17884
17885    /**
17886     * Returns the end padding of this view depending on its resolved layout direction.
17887     * If there are inset and enabled scrollbars, this value may include the space
17888     * required to display the scrollbars as well.
17889     *
17890     * @return the end padding in pixels
17891     */
17892    public int getPaddingEnd() {
17893        if (!isPaddingResolved()) {
17894            resolvePadding();
17895        }
17896        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17897                mPaddingLeft : mPaddingRight;
17898    }
17899
17900    /**
17901     * Return if the padding has been set through relative values
17902     * {@link #setPaddingRelative(int, int, int, int)} or through
17903     * @attr ref android.R.styleable#View_paddingStart or
17904     * @attr ref android.R.styleable#View_paddingEnd
17905     *
17906     * @return true if the padding is relative or false if it is not.
17907     */
17908    public boolean isPaddingRelative() {
17909        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17910    }
17911
17912    Insets computeOpticalInsets() {
17913        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17914    }
17915
17916    /**
17917     * @hide
17918     */
17919    public void resetPaddingToInitialValues() {
17920        if (isRtlCompatibilityMode()) {
17921            mPaddingLeft = mUserPaddingLeftInitial;
17922            mPaddingRight = mUserPaddingRightInitial;
17923            return;
17924        }
17925        if (isLayoutRtl()) {
17926            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17927            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17928        } else {
17929            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17930            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17931        }
17932    }
17933
17934    /**
17935     * @hide
17936     */
17937    public Insets getOpticalInsets() {
17938        if (mLayoutInsets == null) {
17939            mLayoutInsets = computeOpticalInsets();
17940        }
17941        return mLayoutInsets;
17942    }
17943
17944    /**
17945     * Set this view's optical insets.
17946     *
17947     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17948     * property. Views that compute their own optical insets should call it as part of measurement.
17949     * This method does not request layout. If you are setting optical insets outside of
17950     * measure/layout itself you will want to call requestLayout() yourself.
17951     * </p>
17952     * @hide
17953     */
17954    public void setOpticalInsets(Insets insets) {
17955        mLayoutInsets = insets;
17956    }
17957
17958    /**
17959     * Changes the selection state of this view. A view can be selected or not.
17960     * Note that selection is not the same as focus. Views are typically
17961     * selected in the context of an AdapterView like ListView or GridView;
17962     * the selected view is the view that is highlighted.
17963     *
17964     * @param selected true if the view must be selected, false otherwise
17965     */
17966    public void setSelected(boolean selected) {
17967        //noinspection DoubleNegation
17968        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17969            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17970            if (!selected) resetPressedState();
17971            invalidate(true);
17972            refreshDrawableState();
17973            dispatchSetSelected(selected);
17974            if (selected) {
17975                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17976            } else {
17977                notifyViewAccessibilityStateChangedIfNeeded(
17978                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17979            }
17980        }
17981    }
17982
17983    /**
17984     * Dispatch setSelected to all of this View's children.
17985     *
17986     * @see #setSelected(boolean)
17987     *
17988     * @param selected The new selected state
17989     */
17990    protected void dispatchSetSelected(boolean selected) {
17991    }
17992
17993    /**
17994     * Indicates the selection state of this view.
17995     *
17996     * @return true if the view is selected, false otherwise
17997     */
17998    @ViewDebug.ExportedProperty
17999    public boolean isSelected() {
18000        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18001    }
18002
18003    /**
18004     * Changes the activated state of this view. A view can be activated or not.
18005     * Note that activation is not the same as selection.  Selection is
18006     * a transient property, representing the view (hierarchy) the user is
18007     * currently interacting with.  Activation is a longer-term state that the
18008     * user can move views in and out of.  For example, in a list view with
18009     * single or multiple selection enabled, the views in the current selection
18010     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18011     * here.)  The activated state is propagated down to children of the view it
18012     * is set on.
18013     *
18014     * @param activated true if the view must be activated, false otherwise
18015     */
18016    public void setActivated(boolean activated) {
18017        //noinspection DoubleNegation
18018        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18019            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18020            invalidate(true);
18021            refreshDrawableState();
18022            dispatchSetActivated(activated);
18023        }
18024    }
18025
18026    /**
18027     * Dispatch setActivated to all of this View's children.
18028     *
18029     * @see #setActivated(boolean)
18030     *
18031     * @param activated The new activated state
18032     */
18033    protected void dispatchSetActivated(boolean activated) {
18034    }
18035
18036    /**
18037     * Indicates the activation state of this view.
18038     *
18039     * @return true if the view is activated, false otherwise
18040     */
18041    @ViewDebug.ExportedProperty
18042    public boolean isActivated() {
18043        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18044    }
18045
18046    /**
18047     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18048     * observer can be used to get notifications when global events, like
18049     * layout, happen.
18050     *
18051     * The returned ViewTreeObserver observer is not guaranteed to remain
18052     * valid for the lifetime of this View. If the caller of this method keeps
18053     * a long-lived reference to ViewTreeObserver, it should always check for
18054     * the return value of {@link ViewTreeObserver#isAlive()}.
18055     *
18056     * @return The ViewTreeObserver for this view's hierarchy.
18057     */
18058    public ViewTreeObserver getViewTreeObserver() {
18059        if (mAttachInfo != null) {
18060            return mAttachInfo.mTreeObserver;
18061        }
18062        if (mFloatingTreeObserver == null) {
18063            mFloatingTreeObserver = new ViewTreeObserver();
18064        }
18065        return mFloatingTreeObserver;
18066    }
18067
18068    /**
18069     * <p>Finds the topmost view in the current view hierarchy.</p>
18070     *
18071     * @return the topmost view containing this view
18072     */
18073    public View getRootView() {
18074        if (mAttachInfo != null) {
18075            final View v = mAttachInfo.mRootView;
18076            if (v != null) {
18077                return v;
18078            }
18079        }
18080
18081        View parent = this;
18082
18083        while (parent.mParent != null && parent.mParent instanceof View) {
18084            parent = (View) parent.mParent;
18085        }
18086
18087        return parent;
18088    }
18089
18090    /**
18091     * Transforms a motion event from view-local coordinates to on-screen
18092     * coordinates.
18093     *
18094     * @param ev the view-local motion event
18095     * @return false if the transformation could not be applied
18096     * @hide
18097     */
18098    public boolean toGlobalMotionEvent(MotionEvent ev) {
18099        final AttachInfo info = mAttachInfo;
18100        if (info == null) {
18101            return false;
18102        }
18103
18104        final Matrix m = info.mTmpMatrix;
18105        m.set(Matrix.IDENTITY_MATRIX);
18106        transformMatrixToGlobal(m);
18107        ev.transform(m);
18108        return true;
18109    }
18110
18111    /**
18112     * Transforms a motion event from on-screen coordinates to view-local
18113     * coordinates.
18114     *
18115     * @param ev the on-screen motion event
18116     * @return false if the transformation could not be applied
18117     * @hide
18118     */
18119    public boolean toLocalMotionEvent(MotionEvent ev) {
18120        final AttachInfo info = mAttachInfo;
18121        if (info == null) {
18122            return false;
18123        }
18124
18125        final Matrix m = info.mTmpMatrix;
18126        m.set(Matrix.IDENTITY_MATRIX);
18127        transformMatrixToLocal(m);
18128        ev.transform(m);
18129        return true;
18130    }
18131
18132    /**
18133     * Modifies the input matrix such that it maps view-local coordinates to
18134     * on-screen coordinates.
18135     *
18136     * @param m input matrix to modify
18137     * @hide
18138     */
18139    public void transformMatrixToGlobal(Matrix m) {
18140        final ViewParent parent = mParent;
18141        if (parent instanceof View) {
18142            final View vp = (View) parent;
18143            vp.transformMatrixToGlobal(m);
18144            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
18145        } else if (parent instanceof ViewRootImpl) {
18146            final ViewRootImpl vr = (ViewRootImpl) parent;
18147            vr.transformMatrixToGlobal(m);
18148            m.preTranslate(0, -vr.mCurScrollY);
18149        }
18150
18151        m.preTranslate(mLeft, mTop);
18152
18153        if (!hasIdentityMatrix()) {
18154            m.preConcat(getMatrix());
18155        }
18156    }
18157
18158    /**
18159     * Modifies the input matrix such that it maps on-screen coordinates to
18160     * view-local coordinates.
18161     *
18162     * @param m input matrix to modify
18163     * @hide
18164     */
18165    public void transformMatrixToLocal(Matrix m) {
18166        final ViewParent parent = mParent;
18167        if (parent instanceof View) {
18168            final View vp = (View) parent;
18169            vp.transformMatrixToLocal(m);
18170            m.postTranslate(vp.mScrollX, vp.mScrollY);
18171        } else if (parent instanceof ViewRootImpl) {
18172            final ViewRootImpl vr = (ViewRootImpl) parent;
18173            vr.transformMatrixToLocal(m);
18174            m.postTranslate(0, vr.mCurScrollY);
18175        }
18176
18177        m.postTranslate(-mLeft, -mTop);
18178
18179        if (!hasIdentityMatrix()) {
18180            m.postConcat(getInverseMatrix());
18181        }
18182    }
18183
18184    /**
18185     * @hide
18186     */
18187    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
18188            @ViewDebug.IntToString(from = 0, to = "x"),
18189            @ViewDebug.IntToString(from = 1, to = "y")
18190    })
18191    public int[] getLocationOnScreen() {
18192        int[] location = new int[2];
18193        getLocationOnScreen(location);
18194        return location;
18195    }
18196
18197    /**
18198     * <p>Computes the coordinates of this view on the screen. The argument
18199     * must be an array of two integers. After the method returns, the array
18200     * contains the x and y location in that order.</p>
18201     *
18202     * @param location an array of two integers in which to hold the coordinates
18203     */
18204    public void getLocationOnScreen(@Size(2) int[] location) {
18205        getLocationInWindow(location);
18206
18207        final AttachInfo info = mAttachInfo;
18208        if (info != null) {
18209            location[0] += info.mWindowLeft;
18210            location[1] += info.mWindowTop;
18211        }
18212    }
18213
18214    /**
18215     * <p>Computes the coordinates of this view in its window. The argument
18216     * must be an array of two integers. After the method returns, the array
18217     * contains the x and y location in that order.</p>
18218     *
18219     * @param location an array of two integers in which to hold the coordinates
18220     */
18221    public void getLocationInWindow(@Size(2) int[] location) {
18222        if (location == null || location.length < 2) {
18223            throw new IllegalArgumentException("location must be an array of two integers");
18224        }
18225
18226        if (mAttachInfo == null) {
18227            // When the view is not attached to a window, this method does not make sense
18228            location[0] = location[1] = 0;
18229            return;
18230        }
18231
18232        float[] position = mAttachInfo.mTmpTransformLocation;
18233        position[0] = position[1] = 0.0f;
18234
18235        if (!hasIdentityMatrix()) {
18236            getMatrix().mapPoints(position);
18237        }
18238
18239        position[0] += mLeft;
18240        position[1] += mTop;
18241
18242        ViewParent viewParent = mParent;
18243        while (viewParent instanceof View) {
18244            final View view = (View) viewParent;
18245
18246            position[0] -= view.mScrollX;
18247            position[1] -= view.mScrollY;
18248
18249            if (!view.hasIdentityMatrix()) {
18250                view.getMatrix().mapPoints(position);
18251            }
18252
18253            position[0] += view.mLeft;
18254            position[1] += view.mTop;
18255
18256            viewParent = view.mParent;
18257         }
18258
18259        if (viewParent instanceof ViewRootImpl) {
18260            // *cough*
18261            final ViewRootImpl vr = (ViewRootImpl) viewParent;
18262            position[1] -= vr.mCurScrollY;
18263        }
18264
18265        location[0] = (int) (position[0] + 0.5f);
18266        location[1] = (int) (position[1] + 0.5f);
18267    }
18268
18269    /**
18270     * {@hide}
18271     * @param id the id of the view to be found
18272     * @return the view of the specified id, null if cannot be found
18273     */
18274    protected View findViewTraversal(@IdRes int id) {
18275        if (id == mID) {
18276            return this;
18277        }
18278        return null;
18279    }
18280
18281    /**
18282     * {@hide}
18283     * @param tag the tag of the view to be found
18284     * @return the view of specified tag, null if cannot be found
18285     */
18286    protected View findViewWithTagTraversal(Object tag) {
18287        if (tag != null && tag.equals(mTag)) {
18288            return this;
18289        }
18290        return null;
18291    }
18292
18293    /**
18294     * {@hide}
18295     * @param predicate The predicate to evaluate.
18296     * @param childToSkip If not null, ignores this child during the recursive traversal.
18297     * @return The first view that matches the predicate or null.
18298     */
18299    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
18300        if (predicate.apply(this)) {
18301            return this;
18302        }
18303        return null;
18304    }
18305
18306    /**
18307     * Look for a child view with the given id.  If this view has the given
18308     * id, return this view.
18309     *
18310     * @param id The id to search for.
18311     * @return The view that has the given id in the hierarchy or null
18312     */
18313    @Nullable
18314    public final View findViewById(@IdRes int id) {
18315        if (id < 0) {
18316            return null;
18317        }
18318        return findViewTraversal(id);
18319    }
18320
18321    /**
18322     * Finds a view by its unuque and stable accessibility id.
18323     *
18324     * @param accessibilityId The searched accessibility id.
18325     * @return The found view.
18326     */
18327    final View findViewByAccessibilityId(int accessibilityId) {
18328        if (accessibilityId < 0) {
18329            return null;
18330        }
18331        View view = findViewByAccessibilityIdTraversal(accessibilityId);
18332        if (view != null) {
18333            return view.includeForAccessibility() ? view : null;
18334        }
18335        return null;
18336    }
18337
18338    /**
18339     * Performs the traversal to find a view by its unuque and stable accessibility id.
18340     *
18341     * <strong>Note:</strong>This method does not stop at the root namespace
18342     * boundary since the user can touch the screen at an arbitrary location
18343     * potentially crossing the root namespace bounday which will send an
18344     * accessibility event to accessibility services and they should be able
18345     * to obtain the event source. Also accessibility ids are guaranteed to be
18346     * unique in the window.
18347     *
18348     * @param accessibilityId The accessibility id.
18349     * @return The found view.
18350     *
18351     * @hide
18352     */
18353    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
18354        if (getAccessibilityViewId() == accessibilityId) {
18355            return this;
18356        }
18357        return null;
18358    }
18359
18360    /**
18361     * Look for a child view with the given tag.  If this view has the given
18362     * tag, return this view.
18363     *
18364     * @param tag The tag to search for, using "tag.equals(getTag())".
18365     * @return The View that has the given tag in the hierarchy or null
18366     */
18367    public final View findViewWithTag(Object tag) {
18368        if (tag == null) {
18369            return null;
18370        }
18371        return findViewWithTagTraversal(tag);
18372    }
18373
18374    /**
18375     * {@hide}
18376     * Look for a child view that matches the specified predicate.
18377     * If this view matches the predicate, return this view.
18378     *
18379     * @param predicate The predicate to evaluate.
18380     * @return The first view that matches the predicate or null.
18381     */
18382    public final View findViewByPredicate(Predicate<View> predicate) {
18383        return findViewByPredicateTraversal(predicate, null);
18384    }
18385
18386    /**
18387     * {@hide}
18388     * Look for a child view that matches the specified predicate,
18389     * starting with the specified view and its descendents and then
18390     * recusively searching the ancestors and siblings of that view
18391     * until this view is reached.
18392     *
18393     * This method is useful in cases where the predicate does not match
18394     * a single unique view (perhaps multiple views use the same id)
18395     * and we are trying to find the view that is "closest" in scope to the
18396     * starting view.
18397     *
18398     * @param start The view to start from.
18399     * @param predicate The predicate to evaluate.
18400     * @return The first view that matches the predicate or null.
18401     */
18402    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
18403        View childToSkip = null;
18404        for (;;) {
18405            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
18406            if (view != null || start == this) {
18407                return view;
18408            }
18409
18410            ViewParent parent = start.getParent();
18411            if (parent == null || !(parent instanceof View)) {
18412                return null;
18413            }
18414
18415            childToSkip = start;
18416            start = (View) parent;
18417        }
18418    }
18419
18420    /**
18421     * Sets the identifier for this view. The identifier does not have to be
18422     * unique in this view's hierarchy. The identifier should be a positive
18423     * number.
18424     *
18425     * @see #NO_ID
18426     * @see #getId()
18427     * @see #findViewById(int)
18428     *
18429     * @param id a number used to identify the view
18430     *
18431     * @attr ref android.R.styleable#View_id
18432     */
18433    public void setId(@IdRes int id) {
18434        mID = id;
18435        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
18436            mID = generateViewId();
18437        }
18438    }
18439
18440    /**
18441     * {@hide}
18442     *
18443     * @param isRoot true if the view belongs to the root namespace, false
18444     *        otherwise
18445     */
18446    public void setIsRootNamespace(boolean isRoot) {
18447        if (isRoot) {
18448            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
18449        } else {
18450            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
18451        }
18452    }
18453
18454    /**
18455     * {@hide}
18456     *
18457     * @return true if the view belongs to the root namespace, false otherwise
18458     */
18459    public boolean isRootNamespace() {
18460        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
18461    }
18462
18463    /**
18464     * Returns this view's identifier.
18465     *
18466     * @return a positive integer used to identify the view or {@link #NO_ID}
18467     *         if the view has no ID
18468     *
18469     * @see #setId(int)
18470     * @see #findViewById(int)
18471     * @attr ref android.R.styleable#View_id
18472     */
18473    @IdRes
18474    @ViewDebug.CapturedViewProperty
18475    public int getId() {
18476        return mID;
18477    }
18478
18479    /**
18480     * Returns this view's tag.
18481     *
18482     * @return the Object stored in this view as a tag, or {@code null} if not
18483     *         set
18484     *
18485     * @see #setTag(Object)
18486     * @see #getTag(int)
18487     */
18488    @ViewDebug.ExportedProperty
18489    public Object getTag() {
18490        return mTag;
18491    }
18492
18493    /**
18494     * Sets the tag associated with this view. A tag can be used to mark
18495     * a view in its hierarchy and does not have to be unique within the
18496     * hierarchy. Tags can also be used to store data within a view without
18497     * resorting to another data structure.
18498     *
18499     * @param tag an Object to tag the view with
18500     *
18501     * @see #getTag()
18502     * @see #setTag(int, Object)
18503     */
18504    public void setTag(final Object tag) {
18505        mTag = tag;
18506    }
18507
18508    /**
18509     * Returns the tag associated with this view and the specified key.
18510     *
18511     * @param key The key identifying the tag
18512     *
18513     * @return the Object stored in this view as a tag, or {@code null} if not
18514     *         set
18515     *
18516     * @see #setTag(int, Object)
18517     * @see #getTag()
18518     */
18519    public Object getTag(int key) {
18520        if (mKeyedTags != null) return mKeyedTags.get(key);
18521        return null;
18522    }
18523
18524    /**
18525     * Sets a tag associated with this view and a key. A tag can be used
18526     * to mark a view in its hierarchy and does not have to be unique within
18527     * the hierarchy. Tags can also be used to store data within a view
18528     * without resorting to another data structure.
18529     *
18530     * The specified key should be an id declared in the resources of the
18531     * application to ensure it is unique (see the <a
18532     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
18533     * Keys identified as belonging to
18534     * the Android framework or not associated with any package will cause
18535     * an {@link IllegalArgumentException} to be thrown.
18536     *
18537     * @param key The key identifying the tag
18538     * @param tag An Object to tag the view with
18539     *
18540     * @throws IllegalArgumentException If they specified key is not valid
18541     *
18542     * @see #setTag(Object)
18543     * @see #getTag(int)
18544     */
18545    public void setTag(int key, final Object tag) {
18546        // If the package id is 0x00 or 0x01, it's either an undefined package
18547        // or a framework id
18548        if ((key >>> 24) < 2) {
18549            throw new IllegalArgumentException("The key must be an application-specific "
18550                    + "resource id.");
18551        }
18552
18553        setKeyedTag(key, tag);
18554    }
18555
18556    /**
18557     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
18558     * framework id.
18559     *
18560     * @hide
18561     */
18562    public void setTagInternal(int key, Object tag) {
18563        if ((key >>> 24) != 0x1) {
18564            throw new IllegalArgumentException("The key must be a framework-specific "
18565                    + "resource id.");
18566        }
18567
18568        setKeyedTag(key, tag);
18569    }
18570
18571    private void setKeyedTag(int key, Object tag) {
18572        if (mKeyedTags == null) {
18573            mKeyedTags = new SparseArray<Object>(2);
18574        }
18575
18576        mKeyedTags.put(key, tag);
18577    }
18578
18579    /**
18580     * Prints information about this view in the log output, with the tag
18581     * {@link #VIEW_LOG_TAG}.
18582     *
18583     * @hide
18584     */
18585    public void debug() {
18586        debug(0);
18587    }
18588
18589    /**
18590     * Prints information about this view in the log output, with the tag
18591     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
18592     * indentation defined by the <code>depth</code>.
18593     *
18594     * @param depth the indentation level
18595     *
18596     * @hide
18597     */
18598    protected void debug(int depth) {
18599        String output = debugIndent(depth - 1);
18600
18601        output += "+ " + this;
18602        int id = getId();
18603        if (id != -1) {
18604            output += " (id=" + id + ")";
18605        }
18606        Object tag = getTag();
18607        if (tag != null) {
18608            output += " (tag=" + tag + ")";
18609        }
18610        Log.d(VIEW_LOG_TAG, output);
18611
18612        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
18613            output = debugIndent(depth) + " FOCUSED";
18614            Log.d(VIEW_LOG_TAG, output);
18615        }
18616
18617        output = debugIndent(depth);
18618        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
18619                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
18620                + "} ";
18621        Log.d(VIEW_LOG_TAG, output);
18622
18623        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
18624                || mPaddingBottom != 0) {
18625            output = debugIndent(depth);
18626            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
18627                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
18628            Log.d(VIEW_LOG_TAG, output);
18629        }
18630
18631        output = debugIndent(depth);
18632        output += "mMeasureWidth=" + mMeasuredWidth +
18633                " mMeasureHeight=" + mMeasuredHeight;
18634        Log.d(VIEW_LOG_TAG, output);
18635
18636        output = debugIndent(depth);
18637        if (mLayoutParams == null) {
18638            output += "BAD! no layout params";
18639        } else {
18640            output = mLayoutParams.debug(output);
18641        }
18642        Log.d(VIEW_LOG_TAG, output);
18643
18644        output = debugIndent(depth);
18645        output += "flags={";
18646        output += View.printFlags(mViewFlags);
18647        output += "}";
18648        Log.d(VIEW_LOG_TAG, output);
18649
18650        output = debugIndent(depth);
18651        output += "privateFlags={";
18652        output += View.printPrivateFlags(mPrivateFlags);
18653        output += "}";
18654        Log.d(VIEW_LOG_TAG, output);
18655    }
18656
18657    /**
18658     * Creates a string of whitespaces used for indentation.
18659     *
18660     * @param depth the indentation level
18661     * @return a String containing (depth * 2 + 3) * 2 white spaces
18662     *
18663     * @hide
18664     */
18665    protected static String debugIndent(int depth) {
18666        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18667        for (int i = 0; i < (depth * 2) + 3; i++) {
18668            spaces.append(' ').append(' ');
18669        }
18670        return spaces.toString();
18671    }
18672
18673    /**
18674     * <p>Return the offset of the widget's text baseline from the widget's top
18675     * boundary. If this widget does not support baseline alignment, this
18676     * method returns -1. </p>
18677     *
18678     * @return the offset of the baseline within the widget's bounds or -1
18679     *         if baseline alignment is not supported
18680     */
18681    @ViewDebug.ExportedProperty(category = "layout")
18682    public int getBaseline() {
18683        return -1;
18684    }
18685
18686    /**
18687     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18688     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18689     * a layout pass.
18690     *
18691     * @return whether the view hierarchy is currently undergoing a layout pass
18692     */
18693    public boolean isInLayout() {
18694        ViewRootImpl viewRoot = getViewRootImpl();
18695        return (viewRoot != null && viewRoot.isInLayout());
18696    }
18697
18698    /**
18699     * Call this when something has changed which has invalidated the
18700     * layout of this view. This will schedule a layout pass of the view
18701     * tree. This should not be called while the view hierarchy is currently in a layout
18702     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18703     * end of the current layout pass (and then layout will run again) or after the current
18704     * frame is drawn and the next layout occurs.
18705     *
18706     * <p>Subclasses which override this method should call the superclass method to
18707     * handle possible request-during-layout errors correctly.</p>
18708     */
18709    @CallSuper
18710    public void requestLayout() {
18711        if (mMeasureCache != null) mMeasureCache.clear();
18712
18713        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18714            // Only trigger request-during-layout logic if this is the view requesting it,
18715            // not the views in its parent hierarchy
18716            ViewRootImpl viewRoot = getViewRootImpl();
18717            if (viewRoot != null && viewRoot.isInLayout()) {
18718                if (!viewRoot.requestLayoutDuringLayout(this)) {
18719                    return;
18720                }
18721            }
18722            mAttachInfo.mViewRequestingLayout = this;
18723        }
18724
18725        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18726        mPrivateFlags |= PFLAG_INVALIDATED;
18727
18728        if (mParent != null && !mParent.isLayoutRequested()) {
18729            mParent.requestLayout();
18730        }
18731        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18732            mAttachInfo.mViewRequestingLayout = null;
18733        }
18734    }
18735
18736    /**
18737     * Forces this view to be laid out during the next layout pass.
18738     * This method does not call requestLayout() or forceLayout()
18739     * on the parent.
18740     */
18741    public void forceLayout() {
18742        if (mMeasureCache != null) mMeasureCache.clear();
18743
18744        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18745        mPrivateFlags |= PFLAG_INVALIDATED;
18746    }
18747
18748    /**
18749     * <p>
18750     * This is called to find out how big a view should be. The parent
18751     * supplies constraint information in the width and height parameters.
18752     * </p>
18753     *
18754     * <p>
18755     * The actual measurement work of a view is performed in
18756     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18757     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18758     * </p>
18759     *
18760     *
18761     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18762     *        parent
18763     * @param heightMeasureSpec Vertical space requirements as imposed by the
18764     *        parent
18765     *
18766     * @see #onMeasure(int, int)
18767     */
18768    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18769        boolean optical = isLayoutModeOptical(this);
18770        if (optical != isLayoutModeOptical(mParent)) {
18771            Insets insets = getOpticalInsets();
18772            int oWidth  = insets.left + insets.right;
18773            int oHeight = insets.top  + insets.bottom;
18774            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18775            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18776        }
18777
18778        // Suppress sign extension for the low bytes
18779        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18780        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18781
18782        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18783        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18784                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18785        final boolean matchingSize = isExactly &&
18786                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18787                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18788        if (forceLayout || !matchingSize &&
18789                (widthMeasureSpec != mOldWidthMeasureSpec ||
18790                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18791
18792            // first clears the measured dimension flag
18793            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18794
18795            resolveRtlPropertiesIfNeeded();
18796
18797            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18798            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18799                // measure ourselves, this should set the measured dimension flag back
18800                onMeasure(widthMeasureSpec, heightMeasureSpec);
18801                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18802            } else {
18803                long value = mMeasureCache.valueAt(cacheIndex);
18804                // Casting a long to int drops the high 32 bits, no mask needed
18805                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18806                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18807            }
18808
18809            // flag not set, setMeasuredDimension() was not invoked, we raise
18810            // an exception to warn the developer
18811            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18812                throw new IllegalStateException("View with id " + getId() + ": "
18813                        + getClass().getName() + "#onMeasure() did not set the"
18814                        + " measured dimension by calling"
18815                        + " setMeasuredDimension()");
18816            }
18817
18818            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18819        }
18820
18821        mOldWidthMeasureSpec = widthMeasureSpec;
18822        mOldHeightMeasureSpec = heightMeasureSpec;
18823
18824        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18825                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18826    }
18827
18828    /**
18829     * <p>
18830     * Measure the view and its content to determine the measured width and the
18831     * measured height. This method is invoked by {@link #measure(int, int)} and
18832     * should be overridden by subclasses to provide accurate and efficient
18833     * measurement of their contents.
18834     * </p>
18835     *
18836     * <p>
18837     * <strong>CONTRACT:</strong> When overriding this method, you
18838     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18839     * measured width and height of this view. Failure to do so will trigger an
18840     * <code>IllegalStateException</code>, thrown by
18841     * {@link #measure(int, int)}. Calling the superclass'
18842     * {@link #onMeasure(int, int)} is a valid use.
18843     * </p>
18844     *
18845     * <p>
18846     * The base class implementation of measure defaults to the background size,
18847     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18848     * override {@link #onMeasure(int, int)} to provide better measurements of
18849     * their content.
18850     * </p>
18851     *
18852     * <p>
18853     * If this method is overridden, it is the subclass's responsibility to make
18854     * sure the measured height and width are at least the view's minimum height
18855     * and width ({@link #getSuggestedMinimumHeight()} and
18856     * {@link #getSuggestedMinimumWidth()}).
18857     * </p>
18858     *
18859     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18860     *                         The requirements are encoded with
18861     *                         {@link android.view.View.MeasureSpec}.
18862     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18863     *                         The requirements are encoded with
18864     *                         {@link android.view.View.MeasureSpec}.
18865     *
18866     * @see #getMeasuredWidth()
18867     * @see #getMeasuredHeight()
18868     * @see #setMeasuredDimension(int, int)
18869     * @see #getSuggestedMinimumHeight()
18870     * @see #getSuggestedMinimumWidth()
18871     * @see android.view.View.MeasureSpec#getMode(int)
18872     * @see android.view.View.MeasureSpec#getSize(int)
18873     */
18874    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18875        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18876                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18877    }
18878
18879    /**
18880     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18881     * measured width and measured height. Failing to do so will trigger an
18882     * exception at measurement time.</p>
18883     *
18884     * @param measuredWidth The measured width of this view.  May be a complex
18885     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18886     * {@link #MEASURED_STATE_TOO_SMALL}.
18887     * @param measuredHeight The measured height of this view.  May be a complex
18888     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18889     * {@link #MEASURED_STATE_TOO_SMALL}.
18890     */
18891    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18892        boolean optical = isLayoutModeOptical(this);
18893        if (optical != isLayoutModeOptical(mParent)) {
18894            Insets insets = getOpticalInsets();
18895            int opticalWidth  = insets.left + insets.right;
18896            int opticalHeight = insets.top  + insets.bottom;
18897
18898            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18899            measuredHeight += optical ? opticalHeight : -opticalHeight;
18900        }
18901        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18902    }
18903
18904    /**
18905     * Sets the measured dimension without extra processing for things like optical bounds.
18906     * Useful for reapplying consistent values that have already been cooked with adjustments
18907     * for optical bounds, etc. such as those from the measurement cache.
18908     *
18909     * @param measuredWidth The measured width of this view.  May be a complex
18910     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18911     * {@link #MEASURED_STATE_TOO_SMALL}.
18912     * @param measuredHeight The measured height of this view.  May be a complex
18913     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18914     * {@link #MEASURED_STATE_TOO_SMALL}.
18915     */
18916    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18917        mMeasuredWidth = measuredWidth;
18918        mMeasuredHeight = measuredHeight;
18919
18920        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18921    }
18922
18923    /**
18924     * Merge two states as returned by {@link #getMeasuredState()}.
18925     * @param curState The current state as returned from a view or the result
18926     * of combining multiple views.
18927     * @param newState The new view state to combine.
18928     * @return Returns a new integer reflecting the combination of the two
18929     * states.
18930     */
18931    public static int combineMeasuredStates(int curState, int newState) {
18932        return curState | newState;
18933    }
18934
18935    /**
18936     * Version of {@link #resolveSizeAndState(int, int, int)}
18937     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18938     */
18939    public static int resolveSize(int size, int measureSpec) {
18940        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18941    }
18942
18943    /**
18944     * Utility to reconcile a desired size and state, with constraints imposed
18945     * by a MeasureSpec. Will take the desired size, unless a different size
18946     * is imposed by the constraints. The returned value is a compound integer,
18947     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18948     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18949     * resulting size is smaller than the size the view wants to be.
18950     *
18951     * @param size How big the view wants to be.
18952     * @param measureSpec Constraints imposed by the parent.
18953     * @param childMeasuredState Size information bit mask for the view's
18954     *                           children.
18955     * @return Size information bit mask as defined by
18956     *         {@link #MEASURED_SIZE_MASK} and
18957     *         {@link #MEASURED_STATE_TOO_SMALL}.
18958     */
18959    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18960        final int specMode = MeasureSpec.getMode(measureSpec);
18961        final int specSize = MeasureSpec.getSize(measureSpec);
18962        final int result;
18963        switch (specMode) {
18964            case MeasureSpec.AT_MOST:
18965                if (specSize < size) {
18966                    result = specSize | MEASURED_STATE_TOO_SMALL;
18967                } else {
18968                    result = size;
18969                }
18970                break;
18971            case MeasureSpec.EXACTLY:
18972                result = specSize;
18973                break;
18974            case MeasureSpec.UNSPECIFIED:
18975            default:
18976                result = size;
18977        }
18978        return result | (childMeasuredState & MEASURED_STATE_MASK);
18979    }
18980
18981    /**
18982     * Utility to return a default size. Uses the supplied size if the
18983     * MeasureSpec imposed no constraints. Will get larger if allowed
18984     * by the MeasureSpec.
18985     *
18986     * @param size Default size for this view
18987     * @param measureSpec Constraints imposed by the parent
18988     * @return The size this view should be.
18989     */
18990    public static int getDefaultSize(int size, int measureSpec) {
18991        int result = size;
18992        int specMode = MeasureSpec.getMode(measureSpec);
18993        int specSize = MeasureSpec.getSize(measureSpec);
18994
18995        switch (specMode) {
18996        case MeasureSpec.UNSPECIFIED:
18997            result = size;
18998            break;
18999        case MeasureSpec.AT_MOST:
19000        case MeasureSpec.EXACTLY:
19001            result = specSize;
19002            break;
19003        }
19004        return result;
19005    }
19006
19007    /**
19008     * Returns the suggested minimum height that the view should use. This
19009     * returns the maximum of the view's minimum height
19010     * and the background's minimum height
19011     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19012     * <p>
19013     * When being used in {@link #onMeasure(int, int)}, the caller should still
19014     * ensure the returned height is within the requirements of the parent.
19015     *
19016     * @return The suggested minimum height of the view.
19017     */
19018    protected int getSuggestedMinimumHeight() {
19019        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19020
19021    }
19022
19023    /**
19024     * Returns the suggested minimum width that the view should use. This
19025     * returns the maximum of the view's minimum width)
19026     * and the background's minimum width
19027     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19028     * <p>
19029     * When being used in {@link #onMeasure(int, int)}, the caller should still
19030     * ensure the returned width is within the requirements of the parent.
19031     *
19032     * @return The suggested minimum width of the view.
19033     */
19034    protected int getSuggestedMinimumWidth() {
19035        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19036    }
19037
19038    /**
19039     * Returns the minimum height of the view.
19040     *
19041     * @return the minimum height the view will try to be.
19042     *
19043     * @see #setMinimumHeight(int)
19044     *
19045     * @attr ref android.R.styleable#View_minHeight
19046     */
19047    public int getMinimumHeight() {
19048        return mMinHeight;
19049    }
19050
19051    /**
19052     * Sets the minimum height of the view. It is not guaranteed the view will
19053     * be able to achieve this minimum height (for example, if its parent layout
19054     * constrains it with less available height).
19055     *
19056     * @param minHeight The minimum height the view will try to be.
19057     *
19058     * @see #getMinimumHeight()
19059     *
19060     * @attr ref android.R.styleable#View_minHeight
19061     */
19062    public void setMinimumHeight(int minHeight) {
19063        mMinHeight = minHeight;
19064        requestLayout();
19065    }
19066
19067    /**
19068     * Returns the minimum width of the view.
19069     *
19070     * @return the minimum width the view will try to be.
19071     *
19072     * @see #setMinimumWidth(int)
19073     *
19074     * @attr ref android.R.styleable#View_minWidth
19075     */
19076    public int getMinimumWidth() {
19077        return mMinWidth;
19078    }
19079
19080    /**
19081     * Sets the minimum width of the view. It is not guaranteed the view will
19082     * be able to achieve this minimum width (for example, if its parent layout
19083     * constrains it with less available width).
19084     *
19085     * @param minWidth The minimum width the view will try to be.
19086     *
19087     * @see #getMinimumWidth()
19088     *
19089     * @attr ref android.R.styleable#View_minWidth
19090     */
19091    public void setMinimumWidth(int minWidth) {
19092        mMinWidth = minWidth;
19093        requestLayout();
19094
19095    }
19096
19097    /**
19098     * Get the animation currently associated with this view.
19099     *
19100     * @return The animation that is currently playing or
19101     *         scheduled to play for this view.
19102     */
19103    public Animation getAnimation() {
19104        return mCurrentAnimation;
19105    }
19106
19107    /**
19108     * Start the specified animation now.
19109     *
19110     * @param animation the animation to start now
19111     */
19112    public void startAnimation(Animation animation) {
19113        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
19114        setAnimation(animation);
19115        invalidateParentCaches();
19116        invalidate(true);
19117    }
19118
19119    /**
19120     * Cancels any animations for this view.
19121     */
19122    public void clearAnimation() {
19123        if (mCurrentAnimation != null) {
19124            mCurrentAnimation.detach();
19125        }
19126        mCurrentAnimation = null;
19127        invalidateParentIfNeeded();
19128    }
19129
19130    /**
19131     * Sets the next animation to play for this view.
19132     * If you want the animation to play immediately, use
19133     * {@link #startAnimation(android.view.animation.Animation)} instead.
19134     * This method provides allows fine-grained
19135     * control over the start time and invalidation, but you
19136     * must make sure that 1) the animation has a start time set, and
19137     * 2) the view's parent (which controls animations on its children)
19138     * will be invalidated when the animation is supposed to
19139     * start.
19140     *
19141     * @param animation The next animation, or null.
19142     */
19143    public void setAnimation(Animation animation) {
19144        mCurrentAnimation = animation;
19145
19146        if (animation != null) {
19147            // If the screen is off assume the animation start time is now instead of
19148            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
19149            // would cause the animation to start when the screen turns back on
19150            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
19151                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
19152                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
19153            }
19154            animation.reset();
19155        }
19156    }
19157
19158    /**
19159     * Invoked by a parent ViewGroup to notify the start of the animation
19160     * currently associated with this view. If you override this method,
19161     * always call super.onAnimationStart();
19162     *
19163     * @see #setAnimation(android.view.animation.Animation)
19164     * @see #getAnimation()
19165     */
19166    @CallSuper
19167    protected void onAnimationStart() {
19168        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
19169    }
19170
19171    /**
19172     * Invoked by a parent ViewGroup to notify the end of the animation
19173     * currently associated with this view. If you override this method,
19174     * always call super.onAnimationEnd();
19175     *
19176     * @see #setAnimation(android.view.animation.Animation)
19177     * @see #getAnimation()
19178     */
19179    @CallSuper
19180    protected void onAnimationEnd() {
19181        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
19182    }
19183
19184    /**
19185     * Invoked if there is a Transform that involves alpha. Subclass that can
19186     * draw themselves with the specified alpha should return true, and then
19187     * respect that alpha when their onDraw() is called. If this returns false
19188     * then the view may be redirected to draw into an offscreen buffer to
19189     * fulfill the request, which will look fine, but may be slower than if the
19190     * subclass handles it internally. The default implementation returns false.
19191     *
19192     * @param alpha The alpha (0..255) to apply to the view's drawing
19193     * @return true if the view can draw with the specified alpha.
19194     */
19195    protected boolean onSetAlpha(int alpha) {
19196        return false;
19197    }
19198
19199    /**
19200     * This is used by the RootView to perform an optimization when
19201     * the view hierarchy contains one or several SurfaceView.
19202     * SurfaceView is always considered transparent, but its children are not,
19203     * therefore all View objects remove themselves from the global transparent
19204     * region (passed as a parameter to this function).
19205     *
19206     * @param region The transparent region for this ViewAncestor (window).
19207     *
19208     * @return Returns true if the effective visibility of the view at this
19209     * point is opaque, regardless of the transparent region; returns false
19210     * if it is possible for underlying windows to be seen behind the view.
19211     *
19212     * {@hide}
19213     */
19214    public boolean gatherTransparentRegion(Region region) {
19215        final AttachInfo attachInfo = mAttachInfo;
19216        if (region != null && attachInfo != null) {
19217            final int pflags = mPrivateFlags;
19218            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
19219                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
19220                // remove it from the transparent region.
19221                final int[] location = attachInfo.mTransparentLocation;
19222                getLocationInWindow(location);
19223                region.op(location[0], location[1], location[0] + mRight - mLeft,
19224                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
19225            } else {
19226                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
19227                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
19228                    // the background drawable's non-transparent parts from this transparent region.
19229                    applyDrawableToTransparentRegion(mBackground, region);
19230                }
19231                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
19232                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
19233                    // Similarly, we remove the foreground drawable's non-transparent parts.
19234                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
19235                }
19236            }
19237        }
19238        return true;
19239    }
19240
19241    /**
19242     * Play a sound effect for this view.
19243     *
19244     * <p>The framework will play sound effects for some built in actions, such as
19245     * clicking, but you may wish to play these effects in your widget,
19246     * for instance, for internal navigation.
19247     *
19248     * <p>The sound effect will only be played if sound effects are enabled by the user, and
19249     * {@link #isSoundEffectsEnabled()} is true.
19250     *
19251     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
19252     */
19253    public void playSoundEffect(int soundConstant) {
19254        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
19255            return;
19256        }
19257        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
19258    }
19259
19260    /**
19261     * BZZZTT!!1!
19262     *
19263     * <p>Provide haptic feedback to the user for this view.
19264     *
19265     * <p>The framework will provide haptic feedback for some built in actions,
19266     * such as long presses, but you may wish to provide feedback for your
19267     * own widget.
19268     *
19269     * <p>The feedback will only be performed if
19270     * {@link #isHapticFeedbackEnabled()} is true.
19271     *
19272     * @param feedbackConstant One of the constants defined in
19273     * {@link HapticFeedbackConstants}
19274     */
19275    public boolean performHapticFeedback(int feedbackConstant) {
19276        return performHapticFeedback(feedbackConstant, 0);
19277    }
19278
19279    /**
19280     * BZZZTT!!1!
19281     *
19282     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
19283     *
19284     * @param feedbackConstant One of the constants defined in
19285     * {@link HapticFeedbackConstants}
19286     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
19287     */
19288    public boolean performHapticFeedback(int feedbackConstant, int flags) {
19289        if (mAttachInfo == null) {
19290            return false;
19291        }
19292        //noinspection SimplifiableIfStatement
19293        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
19294                && !isHapticFeedbackEnabled()) {
19295            return false;
19296        }
19297        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
19298                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
19299    }
19300
19301    /**
19302     * Request that the visibility of the status bar or other screen/window
19303     * decorations be changed.
19304     *
19305     * <p>This method is used to put the over device UI into temporary modes
19306     * where the user's attention is focused more on the application content,
19307     * by dimming or hiding surrounding system affordances.  This is typically
19308     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
19309     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
19310     * to be placed behind the action bar (and with these flags other system
19311     * affordances) so that smooth transitions between hiding and showing them
19312     * can be done.
19313     *
19314     * <p>Two representative examples of the use of system UI visibility is
19315     * implementing a content browsing application (like a magazine reader)
19316     * and a video playing application.
19317     *
19318     * <p>The first code shows a typical implementation of a View in a content
19319     * browsing application.  In this implementation, the application goes
19320     * into a content-oriented mode by hiding the status bar and action bar,
19321     * and putting the navigation elements into lights out mode.  The user can
19322     * then interact with content while in this mode.  Such an application should
19323     * provide an easy way for the user to toggle out of the mode (such as to
19324     * check information in the status bar or access notifications).  In the
19325     * implementation here, this is done simply by tapping on the content.
19326     *
19327     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
19328     *      content}
19329     *
19330     * <p>This second code sample shows a typical implementation of a View
19331     * in a video playing application.  In this situation, while the video is
19332     * playing the application would like to go into a complete full-screen mode,
19333     * to use as much of the display as possible for the video.  When in this state
19334     * the user can not interact with the application; the system intercepts
19335     * touching on the screen to pop the UI out of full screen mode.  See
19336     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
19337     *
19338     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
19339     *      content}
19340     *
19341     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19342     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
19343     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
19344     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
19345     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
19346     */
19347    public void setSystemUiVisibility(int visibility) {
19348        if (visibility != mSystemUiVisibility) {
19349            mSystemUiVisibility = visibility;
19350            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
19351                mParent.recomputeViewAttributes(this);
19352            }
19353        }
19354    }
19355
19356    /**
19357     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
19358     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19359     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
19360     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
19361     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
19362     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
19363     */
19364    public int getSystemUiVisibility() {
19365        return mSystemUiVisibility;
19366    }
19367
19368    /**
19369     * Returns the current system UI visibility that is currently set for
19370     * the entire window.  This is the combination of the
19371     * {@link #setSystemUiVisibility(int)} values supplied by all of the
19372     * views in the window.
19373     */
19374    public int getWindowSystemUiVisibility() {
19375        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
19376    }
19377
19378    /**
19379     * Override to find out when the window's requested system UI visibility
19380     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
19381     * This is different from the callbacks received through
19382     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
19383     * in that this is only telling you about the local request of the window,
19384     * not the actual values applied by the system.
19385     */
19386    public void onWindowSystemUiVisibilityChanged(int visible) {
19387    }
19388
19389    /**
19390     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
19391     * the view hierarchy.
19392     */
19393    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
19394        onWindowSystemUiVisibilityChanged(visible);
19395    }
19396
19397    /**
19398     * Set a listener to receive callbacks when the visibility of the system bar changes.
19399     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
19400     */
19401    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
19402        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
19403        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
19404            mParent.recomputeViewAttributes(this);
19405        }
19406    }
19407
19408    /**
19409     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
19410     * the view hierarchy.
19411     */
19412    public void dispatchSystemUiVisibilityChanged(int visibility) {
19413        ListenerInfo li = mListenerInfo;
19414        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
19415            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
19416                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
19417        }
19418    }
19419
19420    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
19421        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
19422        if (val != mSystemUiVisibility) {
19423            setSystemUiVisibility(val);
19424            return true;
19425        }
19426        return false;
19427    }
19428
19429    /** @hide */
19430    public void setDisabledSystemUiVisibility(int flags) {
19431        if (mAttachInfo != null) {
19432            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
19433                mAttachInfo.mDisabledSystemUiVisibility = flags;
19434                if (mParent != null) {
19435                    mParent.recomputeViewAttributes(this);
19436                }
19437            }
19438        }
19439    }
19440
19441    /**
19442     * Creates an image that the system displays during the drag and drop
19443     * operation. This is called a &quot;drag shadow&quot;. The default implementation
19444     * for a DragShadowBuilder based on a View returns an image that has exactly the same
19445     * appearance as the given View. The default also positions the center of the drag shadow
19446     * directly under the touch point. If no View is provided (the constructor with no parameters
19447     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
19448     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
19449     * default is an invisible drag shadow.
19450     * <p>
19451     * You are not required to use the View you provide to the constructor as the basis of the
19452     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
19453     * anything you want as the drag shadow.
19454     * </p>
19455     * <p>
19456     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
19457     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
19458     *  size and position of the drag shadow. It uses this data to construct a
19459     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
19460     *  so that your application can draw the shadow image in the Canvas.
19461     * </p>
19462     *
19463     * <div class="special reference">
19464     * <h3>Developer Guides</h3>
19465     * <p>For a guide to implementing drag and drop features, read the
19466     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19467     * </div>
19468     */
19469    public static class DragShadowBuilder {
19470        private final WeakReference<View> mView;
19471
19472        /**
19473         * Constructs a shadow image builder based on a View. By default, the resulting drag
19474         * shadow will have the same appearance and dimensions as the View, with the touch point
19475         * over the center of the View.
19476         * @param view A View. Any View in scope can be used.
19477         */
19478        public DragShadowBuilder(View view) {
19479            mView = new WeakReference<View>(view);
19480        }
19481
19482        /**
19483         * Construct a shadow builder object with no associated View.  This
19484         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
19485         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
19486         * to supply the drag shadow's dimensions and appearance without
19487         * reference to any View object. If they are not overridden, then the result is an
19488         * invisible drag shadow.
19489         */
19490        public DragShadowBuilder() {
19491            mView = new WeakReference<View>(null);
19492        }
19493
19494        /**
19495         * Returns the View object that had been passed to the
19496         * {@link #View.DragShadowBuilder(View)}
19497         * constructor.  If that View parameter was {@code null} or if the
19498         * {@link #View.DragShadowBuilder()}
19499         * constructor was used to instantiate the builder object, this method will return
19500         * null.
19501         *
19502         * @return The View object associate with this builder object.
19503         */
19504        @SuppressWarnings({"JavadocReference"})
19505        final public View getView() {
19506            return mView.get();
19507        }
19508
19509        /**
19510         * Provides the metrics for the shadow image. These include the dimensions of
19511         * the shadow image, and the point within that shadow that should
19512         * be centered under the touch location while dragging.
19513         * <p>
19514         * The default implementation sets the dimensions of the shadow to be the
19515         * same as the dimensions of the View itself and centers the shadow under
19516         * the touch point.
19517         * </p>
19518         *
19519         * @param shadowSize A {@link android.graphics.Point} containing the width and height
19520         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
19521         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
19522         * image.
19523         *
19524         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
19525         * shadow image that should be underneath the touch point during the drag and drop
19526         * operation. Your application must set {@link android.graphics.Point#x} to the
19527         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
19528         */
19529        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
19530            final View view = mView.get();
19531            if (view != null) {
19532                shadowSize.set(view.getWidth(), view.getHeight());
19533                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
19534            } else {
19535                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
19536            }
19537        }
19538
19539        /**
19540         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
19541         * based on the dimensions it received from the
19542         * {@link #onProvideShadowMetrics(Point, Point)} callback.
19543         *
19544         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
19545         */
19546        public void onDrawShadow(Canvas canvas) {
19547            final View view = mView.get();
19548            if (view != null) {
19549                view.draw(canvas);
19550            } else {
19551                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
19552            }
19553        }
19554    }
19555
19556    /**
19557     * Starts a drag and drop operation. When your application calls this method, it passes a
19558     * {@link android.view.View.DragShadowBuilder} object to the system. The
19559     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
19560     * to get metrics for the drag shadow, and then calls the object's
19561     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
19562     * <p>
19563     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
19564     *  drag events to all the View objects in your application that are currently visible. It does
19565     *  this either by calling the View object's drag listener (an implementation of
19566     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
19567     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
19568     *  Both are passed a {@link android.view.DragEvent} object that has a
19569     *  {@link android.view.DragEvent#getAction()} value of
19570     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
19571     * </p>
19572     * <p>
19573     * Your application can invoke startDrag() on any attached View object. The View object does not
19574     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
19575     * be related to the View the user selected for dragging.
19576     * </p>
19577     * @param data A {@link android.content.ClipData} object pointing to the data to be
19578     * transferred by the drag and drop operation.
19579     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
19580     * drag shadow.
19581     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
19582     * drop operation. This Object is put into every DragEvent object sent by the system during the
19583     * current drag.
19584     * <p>
19585     * myLocalState is a lightweight mechanism for the sending information from the dragged View
19586     * to the target Views. For example, it can contain flags that differentiate between a
19587     * a copy operation and a move operation.
19588     * </p>
19589     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
19590     * so the parameter should be set to 0.
19591     * @return {@code true} if the method completes successfully, or
19592     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
19593     * do a drag, and so no drag operation is in progress.
19594     */
19595    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
19596            Object myLocalState, int flags) {
19597        if (ViewDebug.DEBUG_DRAG) {
19598            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
19599        }
19600        boolean okay = false;
19601
19602        Point shadowSize = new Point();
19603        Point shadowTouchPoint = new Point();
19604        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
19605
19606        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
19607                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
19608            throw new IllegalStateException("Drag shadow dimensions must not be negative");
19609        }
19610
19611        if (ViewDebug.DEBUG_DRAG) {
19612            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
19613                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
19614        }
19615        Surface surface = new Surface();
19616        try {
19617            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
19618                    flags, shadowSize.x, shadowSize.y, surface);
19619            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
19620                    + " surface=" + surface);
19621            if (token != null) {
19622                Canvas canvas = surface.lockCanvas(null);
19623                try {
19624                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
19625                    shadowBuilder.onDrawShadow(canvas);
19626                } finally {
19627                    surface.unlockCanvasAndPost(canvas);
19628                }
19629
19630                final ViewRootImpl root = getViewRootImpl();
19631
19632                // Cache the local state object for delivery with DragEvents
19633                root.setLocalDragState(myLocalState);
19634
19635                // repurpose 'shadowSize' for the last touch point
19636                root.getLastTouchPoint(shadowSize);
19637
19638                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19639                        shadowSize.x, shadowSize.y,
19640                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19641                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19642
19643                // Off and running!  Release our local surface instance; the drag
19644                // shadow surface is now managed by the system process.
19645                surface.release();
19646            }
19647        } catch (Exception e) {
19648            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19649            surface.destroy();
19650        }
19651
19652        return okay;
19653    }
19654
19655    /**
19656     * Handles drag events sent by the system following a call to
19657     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19658     *<p>
19659     * When the system calls this method, it passes a
19660     * {@link android.view.DragEvent} object. A call to
19661     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19662     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19663     * operation.
19664     * @param event The {@link android.view.DragEvent} sent by the system.
19665     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19666     * in DragEvent, indicating the type of drag event represented by this object.
19667     * @return {@code true} if the method was successful, otherwise {@code false}.
19668     * <p>
19669     *  The method should return {@code true} in response to an action type of
19670     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19671     *  operation.
19672     * </p>
19673     * <p>
19674     *  The method should also return {@code true} in response to an action type of
19675     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19676     *  {@code false} if it didn't.
19677     * </p>
19678     */
19679    public boolean onDragEvent(DragEvent event) {
19680        return false;
19681    }
19682
19683    /**
19684     * Detects if this View is enabled and has a drag event listener.
19685     * If both are true, then it calls the drag event listener with the
19686     * {@link android.view.DragEvent} it received. If the drag event listener returns
19687     * {@code true}, then dispatchDragEvent() returns {@code true}.
19688     * <p>
19689     * For all other cases, the method calls the
19690     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19691     * method and returns its result.
19692     * </p>
19693     * <p>
19694     * This ensures that a drag event is always consumed, even if the View does not have a drag
19695     * event listener. However, if the View has a listener and the listener returns true, then
19696     * onDragEvent() is not called.
19697     * </p>
19698     */
19699    public boolean dispatchDragEvent(DragEvent event) {
19700        ListenerInfo li = mListenerInfo;
19701        //noinspection SimplifiableIfStatement
19702        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19703                && li.mOnDragListener.onDrag(this, event)) {
19704            return true;
19705        }
19706        return onDragEvent(event);
19707    }
19708
19709    boolean canAcceptDrag() {
19710        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19711    }
19712
19713    /**
19714     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19715     * it is ever exposed at all.
19716     * @hide
19717     */
19718    public void onCloseSystemDialogs(String reason) {
19719    }
19720
19721    /**
19722     * Given a Drawable whose bounds have been set to draw into this view,
19723     * update a Region being computed for
19724     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19725     * that any non-transparent parts of the Drawable are removed from the
19726     * given transparent region.
19727     *
19728     * @param dr The Drawable whose transparency is to be applied to the region.
19729     * @param region A Region holding the current transparency information,
19730     * where any parts of the region that are set are considered to be
19731     * transparent.  On return, this region will be modified to have the
19732     * transparency information reduced by the corresponding parts of the
19733     * Drawable that are not transparent.
19734     * {@hide}
19735     */
19736    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19737        if (DBG) {
19738            Log.i("View", "Getting transparent region for: " + this);
19739        }
19740        final Region r = dr.getTransparentRegion();
19741        final Rect db = dr.getBounds();
19742        final AttachInfo attachInfo = mAttachInfo;
19743        if (r != null && attachInfo != null) {
19744            final int w = getRight()-getLeft();
19745            final int h = getBottom()-getTop();
19746            if (db.left > 0) {
19747                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19748                r.op(0, 0, db.left, h, Region.Op.UNION);
19749            }
19750            if (db.right < w) {
19751                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19752                r.op(db.right, 0, w, h, Region.Op.UNION);
19753            }
19754            if (db.top > 0) {
19755                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19756                r.op(0, 0, w, db.top, Region.Op.UNION);
19757            }
19758            if (db.bottom < h) {
19759                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19760                r.op(0, db.bottom, w, h, Region.Op.UNION);
19761            }
19762            final int[] location = attachInfo.mTransparentLocation;
19763            getLocationInWindow(location);
19764            r.translate(location[0], location[1]);
19765            region.op(r, Region.Op.INTERSECT);
19766        } else {
19767            region.op(db, Region.Op.DIFFERENCE);
19768        }
19769    }
19770
19771    private void checkForLongClick(int delayOffset) {
19772        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19773            mHasPerformedLongPress = false;
19774
19775            if (mPendingCheckForLongPress == null) {
19776                mPendingCheckForLongPress = new CheckForLongPress();
19777            }
19778            mPendingCheckForLongPress.rememberWindowAttachCount();
19779            postDelayed(mPendingCheckForLongPress,
19780                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19781        }
19782    }
19783
19784    /**
19785     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19786     * LayoutInflater} class, which provides a full range of options for view inflation.
19787     *
19788     * @param context The Context object for your activity or application.
19789     * @param resource The resource ID to inflate
19790     * @param root A view group that will be the parent.  Used to properly inflate the
19791     * layout_* parameters.
19792     * @see LayoutInflater
19793     */
19794    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19795        LayoutInflater factory = LayoutInflater.from(context);
19796        return factory.inflate(resource, root);
19797    }
19798
19799    /**
19800     * Scroll the view with standard behavior for scrolling beyond the normal
19801     * content boundaries. Views that call this method should override
19802     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19803     * results of an over-scroll operation.
19804     *
19805     * Views can use this method to handle any touch or fling-based scrolling.
19806     *
19807     * @param deltaX Change in X in pixels
19808     * @param deltaY Change in Y in pixels
19809     * @param scrollX Current X scroll value in pixels before applying deltaX
19810     * @param scrollY Current Y scroll value in pixels before applying deltaY
19811     * @param scrollRangeX Maximum content scroll range along the X axis
19812     * @param scrollRangeY Maximum content scroll range along the Y axis
19813     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19814     *          along the X axis.
19815     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19816     *          along the Y axis.
19817     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19818     * @return true if scrolling was clamped to an over-scroll boundary along either
19819     *          axis, false otherwise.
19820     */
19821    @SuppressWarnings({"UnusedParameters"})
19822    protected boolean overScrollBy(int deltaX, int deltaY,
19823            int scrollX, int scrollY,
19824            int scrollRangeX, int scrollRangeY,
19825            int maxOverScrollX, int maxOverScrollY,
19826            boolean isTouchEvent) {
19827        final int overScrollMode = mOverScrollMode;
19828        final boolean canScrollHorizontal =
19829                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19830        final boolean canScrollVertical =
19831                computeVerticalScrollRange() > computeVerticalScrollExtent();
19832        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19833                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19834        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19835                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19836
19837        int newScrollX = scrollX + deltaX;
19838        if (!overScrollHorizontal) {
19839            maxOverScrollX = 0;
19840        }
19841
19842        int newScrollY = scrollY + deltaY;
19843        if (!overScrollVertical) {
19844            maxOverScrollY = 0;
19845        }
19846
19847        // Clamp values if at the limits and record
19848        final int left = -maxOverScrollX;
19849        final int right = maxOverScrollX + scrollRangeX;
19850        final int top = -maxOverScrollY;
19851        final int bottom = maxOverScrollY + scrollRangeY;
19852
19853        boolean clampedX = false;
19854        if (newScrollX > right) {
19855            newScrollX = right;
19856            clampedX = true;
19857        } else if (newScrollX < left) {
19858            newScrollX = left;
19859            clampedX = true;
19860        }
19861
19862        boolean clampedY = false;
19863        if (newScrollY > bottom) {
19864            newScrollY = bottom;
19865            clampedY = true;
19866        } else if (newScrollY < top) {
19867            newScrollY = top;
19868            clampedY = true;
19869        }
19870
19871        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19872
19873        return clampedX || clampedY;
19874    }
19875
19876    /**
19877     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19878     * respond to the results of an over-scroll operation.
19879     *
19880     * @param scrollX New X scroll value in pixels
19881     * @param scrollY New Y scroll value in pixels
19882     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19883     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19884     */
19885    protected void onOverScrolled(int scrollX, int scrollY,
19886            boolean clampedX, boolean clampedY) {
19887        // Intentionally empty.
19888    }
19889
19890    /**
19891     * Returns the over-scroll mode for this view. The result will be
19892     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19893     * (allow over-scrolling only if the view content is larger than the container),
19894     * or {@link #OVER_SCROLL_NEVER}.
19895     *
19896     * @return This view's over-scroll mode.
19897     */
19898    public int getOverScrollMode() {
19899        return mOverScrollMode;
19900    }
19901
19902    /**
19903     * Set the over-scroll mode for this view. Valid over-scroll modes are
19904     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19905     * (allow over-scrolling only if the view content is larger than the container),
19906     * or {@link #OVER_SCROLL_NEVER}.
19907     *
19908     * Setting the over-scroll mode of a view will have an effect only if the
19909     * view is capable of scrolling.
19910     *
19911     * @param overScrollMode The new over-scroll mode for this view.
19912     */
19913    public void setOverScrollMode(int overScrollMode) {
19914        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19915                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19916                overScrollMode != OVER_SCROLL_NEVER) {
19917            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19918        }
19919        mOverScrollMode = overScrollMode;
19920    }
19921
19922    /**
19923     * Enable or disable nested scrolling for this view.
19924     *
19925     * <p>If this property is set to true the view will be permitted to initiate nested
19926     * scrolling operations with a compatible parent view in the current hierarchy. If this
19927     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19928     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19929     * the nested scroll.</p>
19930     *
19931     * @param enabled true to enable nested scrolling, false to disable
19932     *
19933     * @see #isNestedScrollingEnabled()
19934     */
19935    public void setNestedScrollingEnabled(boolean enabled) {
19936        if (enabled) {
19937            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19938        } else {
19939            stopNestedScroll();
19940            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19941        }
19942    }
19943
19944    /**
19945     * Returns true if nested scrolling is enabled for this view.
19946     *
19947     * <p>If nested scrolling is enabled and this View class implementation supports it,
19948     * this view will act as a nested scrolling child view when applicable, forwarding data
19949     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19950     * parent.</p>
19951     *
19952     * @return true if nested scrolling is enabled
19953     *
19954     * @see #setNestedScrollingEnabled(boolean)
19955     */
19956    public boolean isNestedScrollingEnabled() {
19957        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19958                PFLAG3_NESTED_SCROLLING_ENABLED;
19959    }
19960
19961    /**
19962     * Begin a nestable scroll operation along the given axes.
19963     *
19964     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19965     *
19966     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19967     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19968     * In the case of touch scrolling the nested scroll will be terminated automatically in
19969     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19970     * In the event of programmatic scrolling the caller must explicitly call
19971     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19972     *
19973     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19974     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19975     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19976     *
19977     * <p>At each incremental step of the scroll the caller should invoke
19978     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19979     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19980     * parent at least partially consumed the scroll and the caller should adjust the amount it
19981     * scrolls by.</p>
19982     *
19983     * <p>After applying the remainder of the scroll delta the caller should invoke
19984     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19985     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19986     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19987     * </p>
19988     *
19989     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19990     *             {@link #SCROLL_AXIS_VERTICAL}.
19991     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19992     *         the current gesture.
19993     *
19994     * @see #stopNestedScroll()
19995     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19996     * @see #dispatchNestedScroll(int, int, int, int, int[])
19997     */
19998    public boolean startNestedScroll(int axes) {
19999        if (hasNestedScrollingParent()) {
20000            // Already in progress
20001            return true;
20002        }
20003        if (isNestedScrollingEnabled()) {
20004            ViewParent p = getParent();
20005            View child = this;
20006            while (p != null) {
20007                try {
20008                    if (p.onStartNestedScroll(child, this, axes)) {
20009                        mNestedScrollingParent = p;
20010                        p.onNestedScrollAccepted(child, this, axes);
20011                        return true;
20012                    }
20013                } catch (AbstractMethodError e) {
20014                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
20015                            "method onStartNestedScroll", e);
20016                    // Allow the search upward to continue
20017                }
20018                if (p instanceof View) {
20019                    child = (View) p;
20020                }
20021                p = p.getParent();
20022            }
20023        }
20024        return false;
20025    }
20026
20027    /**
20028     * Stop a nested scroll in progress.
20029     *
20030     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
20031     *
20032     * @see #startNestedScroll(int)
20033     */
20034    public void stopNestedScroll() {
20035        if (mNestedScrollingParent != null) {
20036            mNestedScrollingParent.onStopNestedScroll(this);
20037            mNestedScrollingParent = null;
20038        }
20039    }
20040
20041    /**
20042     * Returns true if this view has a nested scrolling parent.
20043     *
20044     * <p>The presence of a nested scrolling parent indicates that this view has initiated
20045     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
20046     *
20047     * @return whether this view has a nested scrolling parent
20048     */
20049    public boolean hasNestedScrollingParent() {
20050        return mNestedScrollingParent != null;
20051    }
20052
20053    /**
20054     * Dispatch one step of a nested scroll in progress.
20055     *
20056     * <p>Implementations of views that support nested scrolling should call this to report
20057     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
20058     * is not currently in progress or nested scrolling is not
20059     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
20060     *
20061     * <p>Compatible View implementations should also call
20062     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
20063     * consuming a component of the scroll event themselves.</p>
20064     *
20065     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
20066     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
20067     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
20068     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
20069     * @param offsetInWindow Optional. If not null, on return this will contain the offset
20070     *                       in local view coordinates of this view from before this operation
20071     *                       to after it completes. View implementations may use this to adjust
20072     *                       expected input coordinate tracking.
20073     * @return true if the event was dispatched, false if it could not be dispatched.
20074     * @see #dispatchNestedPreScroll(int, int, int[], int[])
20075     */
20076    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
20077            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
20078        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20079            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
20080                int startX = 0;
20081                int startY = 0;
20082                if (offsetInWindow != null) {
20083                    getLocationInWindow(offsetInWindow);
20084                    startX = offsetInWindow[0];
20085                    startY = offsetInWindow[1];
20086                }
20087
20088                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
20089                        dxUnconsumed, dyUnconsumed);
20090
20091                if (offsetInWindow != null) {
20092                    getLocationInWindow(offsetInWindow);
20093                    offsetInWindow[0] -= startX;
20094                    offsetInWindow[1] -= startY;
20095                }
20096                return true;
20097            } else if (offsetInWindow != null) {
20098                // No motion, no dispatch. Keep offsetInWindow up to date.
20099                offsetInWindow[0] = 0;
20100                offsetInWindow[1] = 0;
20101            }
20102        }
20103        return false;
20104    }
20105
20106    /**
20107     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
20108     *
20109     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
20110     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
20111     * scrolling operation to consume some or all of the scroll operation before the child view
20112     * consumes it.</p>
20113     *
20114     * @param dx Horizontal scroll distance in pixels
20115     * @param dy Vertical scroll distance in pixels
20116     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
20117     *                 and consumed[1] the consumed dy.
20118     * @param offsetInWindow Optional. If not null, on return this will contain the offset
20119     *                       in local view coordinates of this view from before this operation
20120     *                       to after it completes. View implementations may use this to adjust
20121     *                       expected input coordinate tracking.
20122     * @return true if the parent consumed some or all of the scroll delta
20123     * @see #dispatchNestedScroll(int, int, int, int, int[])
20124     */
20125    public boolean dispatchNestedPreScroll(int dx, int dy,
20126            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
20127        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20128            if (dx != 0 || dy != 0) {
20129                int startX = 0;
20130                int startY = 0;
20131                if (offsetInWindow != null) {
20132                    getLocationInWindow(offsetInWindow);
20133                    startX = offsetInWindow[0];
20134                    startY = offsetInWindow[1];
20135                }
20136
20137                if (consumed == null) {
20138                    if (mTempNestedScrollConsumed == null) {
20139                        mTempNestedScrollConsumed = new int[2];
20140                    }
20141                    consumed = mTempNestedScrollConsumed;
20142                }
20143                consumed[0] = 0;
20144                consumed[1] = 0;
20145                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
20146
20147                if (offsetInWindow != null) {
20148                    getLocationInWindow(offsetInWindow);
20149                    offsetInWindow[0] -= startX;
20150                    offsetInWindow[1] -= startY;
20151                }
20152                return consumed[0] != 0 || consumed[1] != 0;
20153            } else if (offsetInWindow != null) {
20154                offsetInWindow[0] = 0;
20155                offsetInWindow[1] = 0;
20156            }
20157        }
20158        return false;
20159    }
20160
20161    /**
20162     * Dispatch a fling to a nested scrolling parent.
20163     *
20164     * <p>This method should be used to indicate that a nested scrolling child has detected
20165     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
20166     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
20167     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
20168     * along a scrollable axis.</p>
20169     *
20170     * <p>If a nested scrolling child view would normally fling but it is at the edge of
20171     * its own content, it can use this method to delegate the fling to its nested scrolling
20172     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
20173     *
20174     * @param velocityX Horizontal fling velocity in pixels per second
20175     * @param velocityY Vertical fling velocity in pixels per second
20176     * @param consumed true if the child consumed the fling, false otherwise
20177     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
20178     */
20179    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
20180        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20181            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
20182        }
20183        return false;
20184    }
20185
20186    /**
20187     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
20188     *
20189     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
20190     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
20191     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
20192     * before the child view consumes it. If this method returns <code>true</code>, a nested
20193     * parent view consumed the fling and this view should not scroll as a result.</p>
20194     *
20195     * <p>For a better user experience, only one view in a nested scrolling chain should consume
20196     * the fling at a time. If a parent view consumed the fling this method will return false.
20197     * Custom view implementations should account for this in two ways:</p>
20198     *
20199     * <ul>
20200     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
20201     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
20202     *     position regardless.</li>
20203     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
20204     *     even to settle back to a valid idle position.</li>
20205     * </ul>
20206     *
20207     * <p>Views should also not offer fling velocities to nested parent views along an axis
20208     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
20209     * should not offer a horizontal fling velocity to its parents since scrolling along that
20210     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
20211     *
20212     * @param velocityX Horizontal fling velocity in pixels per second
20213     * @param velocityY Vertical fling velocity in pixels per second
20214     * @return true if a nested scrolling parent consumed the fling
20215     */
20216    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
20217        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
20218            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
20219        }
20220        return false;
20221    }
20222
20223    /**
20224     * Gets a scale factor that determines the distance the view should scroll
20225     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
20226     * @return The vertical scroll scale factor.
20227     * @hide
20228     */
20229    protected float getVerticalScrollFactor() {
20230        if (mVerticalScrollFactor == 0) {
20231            TypedValue outValue = new TypedValue();
20232            if (!mContext.getTheme().resolveAttribute(
20233                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
20234                throw new IllegalStateException(
20235                        "Expected theme to define listPreferredItemHeight.");
20236            }
20237            mVerticalScrollFactor = outValue.getDimension(
20238                    mContext.getResources().getDisplayMetrics());
20239        }
20240        return mVerticalScrollFactor;
20241    }
20242
20243    /**
20244     * Gets a scale factor that determines the distance the view should scroll
20245     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
20246     * @return The horizontal scroll scale factor.
20247     * @hide
20248     */
20249    protected float getHorizontalScrollFactor() {
20250        // TODO: Should use something else.
20251        return getVerticalScrollFactor();
20252    }
20253
20254    /**
20255     * Return the value specifying the text direction or policy that was set with
20256     * {@link #setTextDirection(int)}.
20257     *
20258     * @return the defined text direction. It can be one of:
20259     *
20260     * {@link #TEXT_DIRECTION_INHERIT},
20261     * {@link #TEXT_DIRECTION_FIRST_STRONG},
20262     * {@link #TEXT_DIRECTION_ANY_RTL},
20263     * {@link #TEXT_DIRECTION_LTR},
20264     * {@link #TEXT_DIRECTION_RTL},
20265     * {@link #TEXT_DIRECTION_LOCALE},
20266     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
20267     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
20268     *
20269     * @attr ref android.R.styleable#View_textDirection
20270     *
20271     * @hide
20272     */
20273    @ViewDebug.ExportedProperty(category = "text", mapping = {
20274            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
20275            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
20276            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
20277            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
20278            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
20279            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
20280            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
20281            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
20282    })
20283    public int getRawTextDirection() {
20284        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
20285    }
20286
20287    /**
20288     * Set the text direction.
20289     *
20290     * @param textDirection the direction to set. Should be one of:
20291     *
20292     * {@link #TEXT_DIRECTION_INHERIT},
20293     * {@link #TEXT_DIRECTION_FIRST_STRONG},
20294     * {@link #TEXT_DIRECTION_ANY_RTL},
20295     * {@link #TEXT_DIRECTION_LTR},
20296     * {@link #TEXT_DIRECTION_RTL},
20297     * {@link #TEXT_DIRECTION_LOCALE}
20298     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
20299     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
20300     *
20301     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
20302     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
20303     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
20304     *
20305     * @attr ref android.R.styleable#View_textDirection
20306     */
20307    public void setTextDirection(int textDirection) {
20308        if (getRawTextDirection() != textDirection) {
20309            // Reset the current text direction and the resolved one
20310            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
20311            resetResolvedTextDirection();
20312            // Set the new text direction
20313            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
20314            // Do resolution
20315            resolveTextDirection();
20316            // Notify change
20317            onRtlPropertiesChanged(getLayoutDirection());
20318            // Refresh
20319            requestLayout();
20320            invalidate(true);
20321        }
20322    }
20323
20324    /**
20325     * Return the resolved text direction.
20326     *
20327     * @return the resolved text direction. Returns one of:
20328     *
20329     * {@link #TEXT_DIRECTION_FIRST_STRONG},
20330     * {@link #TEXT_DIRECTION_ANY_RTL},
20331     * {@link #TEXT_DIRECTION_LTR},
20332     * {@link #TEXT_DIRECTION_RTL},
20333     * {@link #TEXT_DIRECTION_LOCALE},
20334     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
20335     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
20336     *
20337     * @attr ref android.R.styleable#View_textDirection
20338     */
20339    @ViewDebug.ExportedProperty(category = "text", mapping = {
20340            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
20341            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
20342            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
20343            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
20344            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
20345            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
20346            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
20347            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
20348    })
20349    public int getTextDirection() {
20350        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
20351    }
20352
20353    /**
20354     * Resolve the text direction.
20355     *
20356     * @return true if resolution has been done, false otherwise.
20357     *
20358     * @hide
20359     */
20360    public boolean resolveTextDirection() {
20361        // Reset any previous text direction resolution
20362        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
20363
20364        if (hasRtlSupport()) {
20365            // Set resolved text direction flag depending on text direction flag
20366            final int textDirection = getRawTextDirection();
20367            switch(textDirection) {
20368                case TEXT_DIRECTION_INHERIT:
20369                    if (!canResolveTextDirection()) {
20370                        // We cannot do the resolution if there is no parent, so use the default one
20371                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20372                        // Resolution will need to happen again later
20373                        return false;
20374                    }
20375
20376                    // Parent has not yet resolved, so we still return the default
20377                    try {
20378                        if (!mParent.isTextDirectionResolved()) {
20379                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20380                            // Resolution will need to happen again later
20381                            return false;
20382                        }
20383                    } catch (AbstractMethodError e) {
20384                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20385                                " does not fully implement ViewParent", e);
20386                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
20387                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20388                        return true;
20389                    }
20390
20391                    // Set current resolved direction to the same value as the parent's one
20392                    int parentResolvedDirection;
20393                    try {
20394                        parentResolvedDirection = mParent.getTextDirection();
20395                    } catch (AbstractMethodError e) {
20396                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20397                                " does not fully implement ViewParent", e);
20398                        parentResolvedDirection = TEXT_DIRECTION_LTR;
20399                    }
20400                    switch (parentResolvedDirection) {
20401                        case TEXT_DIRECTION_FIRST_STRONG:
20402                        case TEXT_DIRECTION_ANY_RTL:
20403                        case TEXT_DIRECTION_LTR:
20404                        case TEXT_DIRECTION_RTL:
20405                        case TEXT_DIRECTION_LOCALE:
20406                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
20407                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
20408                            mPrivateFlags2 |=
20409                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20410                            break;
20411                        default:
20412                            // Default resolved direction is "first strong" heuristic
20413                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20414                    }
20415                    break;
20416                case TEXT_DIRECTION_FIRST_STRONG:
20417                case TEXT_DIRECTION_ANY_RTL:
20418                case TEXT_DIRECTION_LTR:
20419                case TEXT_DIRECTION_RTL:
20420                case TEXT_DIRECTION_LOCALE:
20421                case TEXT_DIRECTION_FIRST_STRONG_LTR:
20422                case TEXT_DIRECTION_FIRST_STRONG_RTL:
20423                    // Resolved direction is the same as text direction
20424                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20425                    break;
20426                default:
20427                    // Default resolved direction is "first strong" heuristic
20428                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20429            }
20430        } else {
20431            // Default resolved direction is "first strong" heuristic
20432            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20433        }
20434
20435        // Set to resolved
20436        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
20437        return true;
20438    }
20439
20440    /**
20441     * Check if text direction resolution can be done.
20442     *
20443     * @return true if text direction resolution can be done otherwise return false.
20444     */
20445    public boolean canResolveTextDirection() {
20446        switch (getRawTextDirection()) {
20447            case TEXT_DIRECTION_INHERIT:
20448                if (mParent != null) {
20449                    try {
20450                        return mParent.canResolveTextDirection();
20451                    } catch (AbstractMethodError e) {
20452                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20453                                " does not fully implement ViewParent", e);
20454                    }
20455                }
20456                return false;
20457
20458            default:
20459                return true;
20460        }
20461    }
20462
20463    /**
20464     * Reset resolved text direction. Text direction will be resolved during a call to
20465     * {@link #onMeasure(int, int)}.
20466     *
20467     * @hide
20468     */
20469    public void resetResolvedTextDirection() {
20470        // Reset any previous text direction resolution
20471        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
20472        // Set to default value
20473        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20474    }
20475
20476    /**
20477     * @return true if text direction is inherited.
20478     *
20479     * @hide
20480     */
20481    public boolean isTextDirectionInherited() {
20482        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
20483    }
20484
20485    /**
20486     * @return true if text direction is resolved.
20487     */
20488    public boolean isTextDirectionResolved() {
20489        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
20490    }
20491
20492    /**
20493     * Return the value specifying the text alignment or policy that was set with
20494     * {@link #setTextAlignment(int)}.
20495     *
20496     * @return the defined text alignment. It can be one of:
20497     *
20498     * {@link #TEXT_ALIGNMENT_INHERIT},
20499     * {@link #TEXT_ALIGNMENT_GRAVITY},
20500     * {@link #TEXT_ALIGNMENT_CENTER},
20501     * {@link #TEXT_ALIGNMENT_TEXT_START},
20502     * {@link #TEXT_ALIGNMENT_TEXT_END},
20503     * {@link #TEXT_ALIGNMENT_VIEW_START},
20504     * {@link #TEXT_ALIGNMENT_VIEW_END}
20505     *
20506     * @attr ref android.R.styleable#View_textAlignment
20507     *
20508     * @hide
20509     */
20510    @ViewDebug.ExportedProperty(category = "text", mapping = {
20511            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20512            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20513            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20514            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20515            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20516            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20517            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20518    })
20519    @TextAlignment
20520    public int getRawTextAlignment() {
20521        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
20522    }
20523
20524    /**
20525     * Set the text alignment.
20526     *
20527     * @param textAlignment The text alignment to set. Should be one of
20528     *
20529     * {@link #TEXT_ALIGNMENT_INHERIT},
20530     * {@link #TEXT_ALIGNMENT_GRAVITY},
20531     * {@link #TEXT_ALIGNMENT_CENTER},
20532     * {@link #TEXT_ALIGNMENT_TEXT_START},
20533     * {@link #TEXT_ALIGNMENT_TEXT_END},
20534     * {@link #TEXT_ALIGNMENT_VIEW_START},
20535     * {@link #TEXT_ALIGNMENT_VIEW_END}
20536     *
20537     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
20538     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
20539     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
20540     *
20541     * @attr ref android.R.styleable#View_textAlignment
20542     */
20543    public void setTextAlignment(@TextAlignment int textAlignment) {
20544        if (textAlignment != getRawTextAlignment()) {
20545            // Reset the current and resolved text alignment
20546            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
20547            resetResolvedTextAlignment();
20548            // Set the new text alignment
20549            mPrivateFlags2 |=
20550                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
20551            // Do resolution
20552            resolveTextAlignment();
20553            // Notify change
20554            onRtlPropertiesChanged(getLayoutDirection());
20555            // Refresh
20556            requestLayout();
20557            invalidate(true);
20558        }
20559    }
20560
20561    /**
20562     * Return the resolved text alignment.
20563     *
20564     * @return the resolved text alignment. Returns one of:
20565     *
20566     * {@link #TEXT_ALIGNMENT_GRAVITY},
20567     * {@link #TEXT_ALIGNMENT_CENTER},
20568     * {@link #TEXT_ALIGNMENT_TEXT_START},
20569     * {@link #TEXT_ALIGNMENT_TEXT_END},
20570     * {@link #TEXT_ALIGNMENT_VIEW_START},
20571     * {@link #TEXT_ALIGNMENT_VIEW_END}
20572     *
20573     * @attr ref android.R.styleable#View_textAlignment
20574     */
20575    @ViewDebug.ExportedProperty(category = "text", mapping = {
20576            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20577            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20578            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20579            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20580            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20581            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20582            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20583    })
20584    @TextAlignment
20585    public int getTextAlignment() {
20586        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
20587                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
20588    }
20589
20590    /**
20591     * Resolve the text alignment.
20592     *
20593     * @return true if resolution has been done, false otherwise.
20594     *
20595     * @hide
20596     */
20597    public boolean resolveTextAlignment() {
20598        // Reset any previous text alignment resolution
20599        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20600
20601        if (hasRtlSupport()) {
20602            // Set resolved text alignment flag depending on text alignment flag
20603            final int textAlignment = getRawTextAlignment();
20604            switch (textAlignment) {
20605                case TEXT_ALIGNMENT_INHERIT:
20606                    // Check if we can resolve the text alignment
20607                    if (!canResolveTextAlignment()) {
20608                        // We cannot do the resolution if there is no parent so use the default
20609                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20610                        // Resolution will need to happen again later
20611                        return false;
20612                    }
20613
20614                    // Parent has not yet resolved, so we still return the default
20615                    try {
20616                        if (!mParent.isTextAlignmentResolved()) {
20617                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20618                            // Resolution will need to happen again later
20619                            return false;
20620                        }
20621                    } catch (AbstractMethodError e) {
20622                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20623                                " does not fully implement ViewParent", e);
20624                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
20625                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20626                        return true;
20627                    }
20628
20629                    int parentResolvedTextAlignment;
20630                    try {
20631                        parentResolvedTextAlignment = mParent.getTextAlignment();
20632                    } catch (AbstractMethodError e) {
20633                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20634                                " does not fully implement ViewParent", e);
20635                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
20636                    }
20637                    switch (parentResolvedTextAlignment) {
20638                        case TEXT_ALIGNMENT_GRAVITY:
20639                        case TEXT_ALIGNMENT_TEXT_START:
20640                        case TEXT_ALIGNMENT_TEXT_END:
20641                        case TEXT_ALIGNMENT_CENTER:
20642                        case TEXT_ALIGNMENT_VIEW_START:
20643                        case TEXT_ALIGNMENT_VIEW_END:
20644                            // Resolved text alignment is the same as the parent resolved
20645                            // text alignment
20646                            mPrivateFlags2 |=
20647                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20648                            break;
20649                        default:
20650                            // Use default resolved text alignment
20651                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20652                    }
20653                    break;
20654                case TEXT_ALIGNMENT_GRAVITY:
20655                case TEXT_ALIGNMENT_TEXT_START:
20656                case TEXT_ALIGNMENT_TEXT_END:
20657                case TEXT_ALIGNMENT_CENTER:
20658                case TEXT_ALIGNMENT_VIEW_START:
20659                case TEXT_ALIGNMENT_VIEW_END:
20660                    // Resolved text alignment is the same as text alignment
20661                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20662                    break;
20663                default:
20664                    // Use default resolved text alignment
20665                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20666            }
20667        } else {
20668            // Use default resolved text alignment
20669            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20670        }
20671
20672        // Set the resolved
20673        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20674        return true;
20675    }
20676
20677    /**
20678     * Check if text alignment resolution can be done.
20679     *
20680     * @return true if text alignment resolution can be done otherwise return false.
20681     */
20682    public boolean canResolveTextAlignment() {
20683        switch (getRawTextAlignment()) {
20684            case TEXT_DIRECTION_INHERIT:
20685                if (mParent != null) {
20686                    try {
20687                        return mParent.canResolveTextAlignment();
20688                    } catch (AbstractMethodError e) {
20689                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20690                                " does not fully implement ViewParent", e);
20691                    }
20692                }
20693                return false;
20694
20695            default:
20696                return true;
20697        }
20698    }
20699
20700    /**
20701     * Reset resolved text alignment. Text alignment will be resolved during a call to
20702     * {@link #onMeasure(int, int)}.
20703     *
20704     * @hide
20705     */
20706    public void resetResolvedTextAlignment() {
20707        // Reset any previous text alignment resolution
20708        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20709        // Set to default
20710        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20711    }
20712
20713    /**
20714     * @return true if text alignment is inherited.
20715     *
20716     * @hide
20717     */
20718    public boolean isTextAlignmentInherited() {
20719        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20720    }
20721
20722    /**
20723     * @return true if text alignment is resolved.
20724     */
20725    public boolean isTextAlignmentResolved() {
20726        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20727    }
20728
20729    /**
20730     * Generate a value suitable for use in {@link #setId(int)}.
20731     * This value will not collide with ID values generated at build time by aapt for R.id.
20732     *
20733     * @return a generated ID value
20734     */
20735    public static int generateViewId() {
20736        for (;;) {
20737            final int result = sNextGeneratedId.get();
20738            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20739            int newValue = result + 1;
20740            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20741            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20742                return result;
20743            }
20744        }
20745    }
20746
20747    /**
20748     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20749     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20750     *                           a normal View or a ViewGroup with
20751     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20752     * @hide
20753     */
20754    public void captureTransitioningViews(List<View> transitioningViews) {
20755        if (getVisibility() == View.VISIBLE) {
20756            transitioningViews.add(this);
20757        }
20758    }
20759
20760    /**
20761     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20762     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20763     * @hide
20764     */
20765    public void findNamedViews(Map<String, View> namedElements) {
20766        if (getVisibility() == VISIBLE || mGhostView != null) {
20767            String transitionName = getTransitionName();
20768            if (transitionName != null) {
20769                namedElements.put(transitionName, this);
20770            }
20771        }
20772    }
20773
20774    //
20775    // Properties
20776    //
20777    /**
20778     * A Property wrapper around the <code>alpha</code> functionality handled by the
20779     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20780     */
20781    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20782        @Override
20783        public void setValue(View object, float value) {
20784            object.setAlpha(value);
20785        }
20786
20787        @Override
20788        public Float get(View object) {
20789            return object.getAlpha();
20790        }
20791    };
20792
20793    /**
20794     * A Property wrapper around the <code>translationX</code> functionality handled by the
20795     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20796     */
20797    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20798        @Override
20799        public void setValue(View object, float value) {
20800            object.setTranslationX(value);
20801        }
20802
20803                @Override
20804        public Float get(View object) {
20805            return object.getTranslationX();
20806        }
20807    };
20808
20809    /**
20810     * A Property wrapper around the <code>translationY</code> functionality handled by the
20811     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20812     */
20813    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20814        @Override
20815        public void setValue(View object, float value) {
20816            object.setTranslationY(value);
20817        }
20818
20819        @Override
20820        public Float get(View object) {
20821            return object.getTranslationY();
20822        }
20823    };
20824
20825    /**
20826     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20827     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20828     */
20829    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20830        @Override
20831        public void setValue(View object, float value) {
20832            object.setTranslationZ(value);
20833        }
20834
20835        @Override
20836        public Float get(View object) {
20837            return object.getTranslationZ();
20838        }
20839    };
20840
20841    /**
20842     * A Property wrapper around the <code>x</code> functionality handled by the
20843     * {@link View#setX(float)} and {@link View#getX()} methods.
20844     */
20845    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20846        @Override
20847        public void setValue(View object, float value) {
20848            object.setX(value);
20849        }
20850
20851        @Override
20852        public Float get(View object) {
20853            return object.getX();
20854        }
20855    };
20856
20857    /**
20858     * A Property wrapper around the <code>y</code> functionality handled by the
20859     * {@link View#setY(float)} and {@link View#getY()} methods.
20860     */
20861    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20862        @Override
20863        public void setValue(View object, float value) {
20864            object.setY(value);
20865        }
20866
20867        @Override
20868        public Float get(View object) {
20869            return object.getY();
20870        }
20871    };
20872
20873    /**
20874     * A Property wrapper around the <code>z</code> functionality handled by the
20875     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20876     */
20877    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20878        @Override
20879        public void setValue(View object, float value) {
20880            object.setZ(value);
20881        }
20882
20883        @Override
20884        public Float get(View object) {
20885            return object.getZ();
20886        }
20887    };
20888
20889    /**
20890     * A Property wrapper around the <code>rotation</code> functionality handled by the
20891     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20892     */
20893    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20894        @Override
20895        public void setValue(View object, float value) {
20896            object.setRotation(value);
20897        }
20898
20899        @Override
20900        public Float get(View object) {
20901            return object.getRotation();
20902        }
20903    };
20904
20905    /**
20906     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20907     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20908     */
20909    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20910        @Override
20911        public void setValue(View object, float value) {
20912            object.setRotationX(value);
20913        }
20914
20915        @Override
20916        public Float get(View object) {
20917            return object.getRotationX();
20918        }
20919    };
20920
20921    /**
20922     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20923     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20924     */
20925    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20926        @Override
20927        public void setValue(View object, float value) {
20928            object.setRotationY(value);
20929        }
20930
20931        @Override
20932        public Float get(View object) {
20933            return object.getRotationY();
20934        }
20935    };
20936
20937    /**
20938     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20939     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20940     */
20941    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20942        @Override
20943        public void setValue(View object, float value) {
20944            object.setScaleX(value);
20945        }
20946
20947        @Override
20948        public Float get(View object) {
20949            return object.getScaleX();
20950        }
20951    };
20952
20953    /**
20954     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20955     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20956     */
20957    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20958        @Override
20959        public void setValue(View object, float value) {
20960            object.setScaleY(value);
20961        }
20962
20963        @Override
20964        public Float get(View object) {
20965            return object.getScaleY();
20966        }
20967    };
20968
20969    /**
20970     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20971     * Each MeasureSpec represents a requirement for either the width or the height.
20972     * A MeasureSpec is comprised of a size and a mode. There are three possible
20973     * modes:
20974     * <dl>
20975     * <dt>UNSPECIFIED</dt>
20976     * <dd>
20977     * The parent has not imposed any constraint on the child. It can be whatever size
20978     * it wants.
20979     * </dd>
20980     *
20981     * <dt>EXACTLY</dt>
20982     * <dd>
20983     * The parent has determined an exact size for the child. The child is going to be
20984     * given those bounds regardless of how big it wants to be.
20985     * </dd>
20986     *
20987     * <dt>AT_MOST</dt>
20988     * <dd>
20989     * The child can be as large as it wants up to the specified size.
20990     * </dd>
20991     * </dl>
20992     *
20993     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20994     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20995     */
20996    public static class MeasureSpec {
20997        private static final int MODE_SHIFT = 30;
20998        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
20999
21000        /**
21001         * Measure specification mode: The parent has not imposed any constraint
21002         * on the child. It can be whatever size it wants.
21003         */
21004        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
21005
21006        /**
21007         * Measure specification mode: The parent has determined an exact size
21008         * for the child. The child is going to be given those bounds regardless
21009         * of how big it wants to be.
21010         */
21011        public static final int EXACTLY     = 1 << MODE_SHIFT;
21012
21013        /**
21014         * Measure specification mode: The child can be as large as it wants up
21015         * to the specified size.
21016         */
21017        public static final int AT_MOST     = 2 << MODE_SHIFT;
21018
21019        /**
21020         * Creates a measure specification based on the supplied size and mode.
21021         *
21022         * The mode must always be one of the following:
21023         * <ul>
21024         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
21025         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
21026         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
21027         * </ul>
21028         *
21029         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
21030         * implementation was such that the order of arguments did not matter
21031         * and overflow in either value could impact the resulting MeasureSpec.
21032         * {@link android.widget.RelativeLayout} was affected by this bug.
21033         * Apps targeting API levels greater than 17 will get the fixed, more strict
21034         * behavior.</p>
21035         *
21036         * @param size the size of the measure specification
21037         * @param mode the mode of the measure specification
21038         * @return the measure specification based on size and mode
21039         */
21040        public static int makeMeasureSpec(int size, int mode) {
21041            if (sUseBrokenMakeMeasureSpec) {
21042                return size + mode;
21043            } else {
21044                return (size & ~MODE_MASK) | (mode & MODE_MASK);
21045            }
21046        }
21047
21048        /**
21049         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
21050         * will automatically get a size of 0. Older apps expect this.
21051         *
21052         * @hide internal use only for compatibility with system widgets and older apps
21053         */
21054        public static int makeSafeMeasureSpec(int size, int mode) {
21055            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
21056                return 0;
21057            }
21058            return makeMeasureSpec(size, mode);
21059        }
21060
21061        /**
21062         * Extracts the mode from the supplied measure specification.
21063         *
21064         * @param measureSpec the measure specification to extract the mode from
21065         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
21066         *         {@link android.view.View.MeasureSpec#AT_MOST} or
21067         *         {@link android.view.View.MeasureSpec#EXACTLY}
21068         */
21069        public static int getMode(int measureSpec) {
21070            return (measureSpec & MODE_MASK);
21071        }
21072
21073        /**
21074         * Extracts the size from the supplied measure specification.
21075         *
21076         * @param measureSpec the measure specification to extract the size from
21077         * @return the size in pixels defined in the supplied measure specification
21078         */
21079        public static int getSize(int measureSpec) {
21080            return (measureSpec & ~MODE_MASK);
21081        }
21082
21083        static int adjust(int measureSpec, int delta) {
21084            final int mode = getMode(measureSpec);
21085            int size = getSize(measureSpec);
21086            if (mode == UNSPECIFIED) {
21087                // No need to adjust size for UNSPECIFIED mode.
21088                return makeMeasureSpec(size, UNSPECIFIED);
21089            }
21090            size += delta;
21091            if (size < 0) {
21092                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
21093                        ") spec: " + toString(measureSpec) + " delta: " + delta);
21094                size = 0;
21095            }
21096            return makeMeasureSpec(size, mode);
21097        }
21098
21099        /**
21100         * Returns a String representation of the specified measure
21101         * specification.
21102         *
21103         * @param measureSpec the measure specification to convert to a String
21104         * @return a String with the following format: "MeasureSpec: MODE SIZE"
21105         */
21106        public static String toString(int measureSpec) {
21107            int mode = getMode(measureSpec);
21108            int size = getSize(measureSpec);
21109
21110            StringBuilder sb = new StringBuilder("MeasureSpec: ");
21111
21112            if (mode == UNSPECIFIED)
21113                sb.append("UNSPECIFIED ");
21114            else if (mode == EXACTLY)
21115                sb.append("EXACTLY ");
21116            else if (mode == AT_MOST)
21117                sb.append("AT_MOST ");
21118            else
21119                sb.append(mode).append(" ");
21120
21121            sb.append(size);
21122            return sb.toString();
21123        }
21124    }
21125
21126    private final class CheckForLongPress implements Runnable {
21127        private int mOriginalWindowAttachCount;
21128
21129        @Override
21130        public void run() {
21131            if (isPressed() && (mParent != null)
21132                    && mOriginalWindowAttachCount == mWindowAttachCount) {
21133                if (performLongClick()) {
21134                    mHasPerformedLongPress = true;
21135                }
21136            }
21137        }
21138
21139        public void rememberWindowAttachCount() {
21140            mOriginalWindowAttachCount = mWindowAttachCount;
21141        }
21142    }
21143
21144    private final class CheckForTap implements Runnable {
21145        public float x;
21146        public float y;
21147
21148        @Override
21149        public void run() {
21150            mPrivateFlags &= ~PFLAG_PREPRESSED;
21151            setPressed(true, x, y);
21152            checkForLongClick(ViewConfiguration.getTapTimeout());
21153        }
21154    }
21155
21156    private final class PerformClick implements Runnable {
21157        @Override
21158        public void run() {
21159            performClick();
21160        }
21161    }
21162
21163    /** @hide */
21164    public void hackTurnOffWindowResizeAnim(boolean off) {
21165        mAttachInfo.mTurnOffWindowResizeAnim = off;
21166    }
21167
21168    /**
21169     * This method returns a ViewPropertyAnimator object, which can be used to animate
21170     * specific properties on this View.
21171     *
21172     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
21173     */
21174    public ViewPropertyAnimator animate() {
21175        if (mAnimator == null) {
21176            mAnimator = new ViewPropertyAnimator(this);
21177        }
21178        return mAnimator;
21179    }
21180
21181    /**
21182     * Sets the name of the View to be used to identify Views in Transitions.
21183     * Names should be unique in the View hierarchy.
21184     *
21185     * @param transitionName The name of the View to uniquely identify it for Transitions.
21186     */
21187    public final void setTransitionName(String transitionName) {
21188        mTransitionName = transitionName;
21189    }
21190
21191    /**
21192     * Returns the name of the View to be used to identify Views in Transitions.
21193     * Names should be unique in the View hierarchy.
21194     *
21195     * <p>This returns null if the View has not been given a name.</p>
21196     *
21197     * @return The name used of the View to be used to identify Views in Transitions or null
21198     * if no name has been given.
21199     */
21200    @ViewDebug.ExportedProperty
21201    public String getTransitionName() {
21202        return mTransitionName;
21203    }
21204
21205    /**
21206     * Interface definition for a callback to be invoked when a hardware key event is
21207     * dispatched to this view. The callback will be invoked before the key event is
21208     * given to the view. This is only useful for hardware keyboards; a software input
21209     * method has no obligation to trigger this listener.
21210     */
21211    public interface OnKeyListener {
21212        /**
21213         * Called when a hardware key is dispatched to a view. This allows listeners to
21214         * get a chance to respond before the target view.
21215         * <p>Key presses in software keyboards will generally NOT trigger this method,
21216         * although some may elect to do so in some situations. Do not assume a
21217         * software input method has to be key-based; even if it is, it may use key presses
21218         * in a different way than you expect, so there is no way to reliably catch soft
21219         * input key presses.
21220         *
21221         * @param v The view the key has been dispatched to.
21222         * @param keyCode The code for the physical key that was pressed
21223         * @param event The KeyEvent object containing full information about
21224         *        the event.
21225         * @return True if the listener has consumed the event, false otherwise.
21226         */
21227        boolean onKey(View v, int keyCode, KeyEvent event);
21228    }
21229
21230    /**
21231     * Interface definition for a callback to be invoked when a touch event is
21232     * dispatched to this view. The callback will be invoked before the touch
21233     * event is given to the view.
21234     */
21235    public interface OnTouchListener {
21236        /**
21237         * Called when a touch event is dispatched to a view. This allows listeners to
21238         * get a chance to respond before the target view.
21239         *
21240         * @param v The view the touch event has been dispatched to.
21241         * @param event The MotionEvent object containing full information about
21242         *        the event.
21243         * @return True if the listener has consumed the event, false otherwise.
21244         */
21245        boolean onTouch(View v, MotionEvent event);
21246    }
21247
21248    /**
21249     * Interface definition for a callback to be invoked when a hover event is
21250     * dispatched to this view. The callback will be invoked before the hover
21251     * event is given to the view.
21252     */
21253    public interface OnHoverListener {
21254        /**
21255         * Called when a hover event is dispatched to a view. This allows listeners to
21256         * get a chance to respond before the target view.
21257         *
21258         * @param v The view the hover event has been dispatched to.
21259         * @param event The MotionEvent object containing full information about
21260         *        the event.
21261         * @return True if the listener has consumed the event, false otherwise.
21262         */
21263        boolean onHover(View v, MotionEvent event);
21264    }
21265
21266    /**
21267     * Interface definition for a callback to be invoked when a generic motion event is
21268     * dispatched to this view. The callback will be invoked before the generic motion
21269     * event is given to the view.
21270     */
21271    public interface OnGenericMotionListener {
21272        /**
21273         * Called when a generic motion event is dispatched to a view. This allows listeners to
21274         * get a chance to respond before the target view.
21275         *
21276         * @param v The view the generic motion event has been dispatched to.
21277         * @param event The MotionEvent object containing full information about
21278         *        the event.
21279         * @return True if the listener has consumed the event, false otherwise.
21280         */
21281        boolean onGenericMotion(View v, MotionEvent event);
21282    }
21283
21284    /**
21285     * Interface definition for a callback to be invoked when a view has been clicked and held.
21286     */
21287    public interface OnLongClickListener {
21288        /**
21289         * Called when a view has been clicked and held.
21290         *
21291         * @param v The view that was clicked and held.
21292         *
21293         * @return true if the callback consumed the long click, false otherwise.
21294         */
21295        boolean onLongClick(View v);
21296    }
21297
21298    /**
21299     * Interface definition for a callback to be invoked when a drag is being dispatched
21300     * to this view.  The callback will be invoked before the hosting view's own
21301     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
21302     * onDrag(event) behavior, it should return 'false' from this callback.
21303     *
21304     * <div class="special reference">
21305     * <h3>Developer Guides</h3>
21306     * <p>For a guide to implementing drag and drop features, read the
21307     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
21308     * </div>
21309     */
21310    public interface OnDragListener {
21311        /**
21312         * Called when a drag event is dispatched to a view. This allows listeners
21313         * to get a chance to override base View behavior.
21314         *
21315         * @param v The View that received the drag event.
21316         * @param event The {@link android.view.DragEvent} object for the drag event.
21317         * @return {@code true} if the drag event was handled successfully, or {@code false}
21318         * if the drag event was not handled. Note that {@code false} will trigger the View
21319         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
21320         */
21321        boolean onDrag(View v, DragEvent event);
21322    }
21323
21324    /**
21325     * Interface definition for a callback to be invoked when the focus state of
21326     * a view changed.
21327     */
21328    public interface OnFocusChangeListener {
21329        /**
21330         * Called when the focus state of a view has changed.
21331         *
21332         * @param v The view whose state has changed.
21333         * @param hasFocus The new focus state of v.
21334         */
21335        void onFocusChange(View v, boolean hasFocus);
21336    }
21337
21338    /**
21339     * Interface definition for a callback to be invoked when a view is clicked.
21340     */
21341    public interface OnClickListener {
21342        /**
21343         * Called when a view has been clicked.
21344         *
21345         * @param v The view that was clicked.
21346         */
21347        void onClick(View v);
21348    }
21349
21350    /**
21351     * Interface definition for a callback to be invoked when a view is context clicked.
21352     */
21353    public interface OnContextClickListener {
21354        /**
21355         * Called when a view is context clicked.
21356         *
21357         * @param v The view that has been context clicked.
21358         * @return true if the callback consumed the context click, false otherwise.
21359         */
21360        boolean onContextClick(View v);
21361    }
21362
21363    /**
21364     * Interface definition for a callback to be invoked when the context menu
21365     * for this view is being built.
21366     */
21367    public interface OnCreateContextMenuListener {
21368        /**
21369         * Called when the context menu for this view is being built. It is not
21370         * safe to hold onto the menu after this method returns.
21371         *
21372         * @param menu The context menu that is being built
21373         * @param v The view for which the context menu is being built
21374         * @param menuInfo Extra information about the item for which the
21375         *            context menu should be shown. This information will vary
21376         *            depending on the class of v.
21377         */
21378        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
21379    }
21380
21381    /**
21382     * Interface definition for a callback to be invoked when the status bar changes
21383     * visibility.  This reports <strong>global</strong> changes to the system UI
21384     * state, not what the application is requesting.
21385     *
21386     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
21387     */
21388    public interface OnSystemUiVisibilityChangeListener {
21389        /**
21390         * Called when the status bar changes visibility because of a call to
21391         * {@link View#setSystemUiVisibility(int)}.
21392         *
21393         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
21394         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
21395         * This tells you the <strong>global</strong> state of these UI visibility
21396         * flags, not what your app is currently applying.
21397         */
21398        public void onSystemUiVisibilityChange(int visibility);
21399    }
21400
21401    /**
21402     * Interface definition for a callback to be invoked when this view is attached
21403     * or detached from its window.
21404     */
21405    public interface OnAttachStateChangeListener {
21406        /**
21407         * Called when the view is attached to a window.
21408         * @param v The view that was attached
21409         */
21410        public void onViewAttachedToWindow(View v);
21411        /**
21412         * Called when the view is detached from a window.
21413         * @param v The view that was detached
21414         */
21415        public void onViewDetachedFromWindow(View v);
21416    }
21417
21418    /**
21419     * Listener for applying window insets on a view in a custom way.
21420     *
21421     * <p>Apps may choose to implement this interface if they want to apply custom policy
21422     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
21423     * is set, its
21424     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
21425     * method will be called instead of the View's own
21426     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
21427     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
21428     * the View's normal behavior as part of its own.</p>
21429     */
21430    public interface OnApplyWindowInsetsListener {
21431        /**
21432         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
21433         * on a View, this listener method will be called instead of the view's own
21434         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
21435         *
21436         * @param v The view applying window insets
21437         * @param insets The insets to apply
21438         * @return The insets supplied, minus any insets that were consumed
21439         */
21440        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
21441    }
21442
21443    private final class UnsetPressedState implements Runnable {
21444        @Override
21445        public void run() {
21446            setPressed(false);
21447        }
21448    }
21449
21450    /**
21451     * Base class for derived classes that want to save and restore their own
21452     * state in {@link android.view.View#onSaveInstanceState()}.
21453     */
21454    public static class BaseSavedState extends AbsSavedState {
21455        String mStartActivityRequestWhoSaved;
21456
21457        /**
21458         * Constructor used when reading from a parcel. Reads the state of the superclass.
21459         *
21460         * @param source
21461         */
21462        public BaseSavedState(Parcel source) {
21463            super(source);
21464            mStartActivityRequestWhoSaved = source.readString();
21465        }
21466
21467        /**
21468         * Constructor called by derived classes when creating their SavedState objects
21469         *
21470         * @param superState The state of the superclass of this view
21471         */
21472        public BaseSavedState(Parcelable superState) {
21473            super(superState);
21474        }
21475
21476        @Override
21477        public void writeToParcel(Parcel out, int flags) {
21478            super.writeToParcel(out, flags);
21479            out.writeString(mStartActivityRequestWhoSaved);
21480        }
21481
21482        public static final Parcelable.Creator<BaseSavedState> CREATOR =
21483                new Parcelable.Creator<BaseSavedState>() {
21484            public BaseSavedState createFromParcel(Parcel in) {
21485                return new BaseSavedState(in);
21486            }
21487
21488            public BaseSavedState[] newArray(int size) {
21489                return new BaseSavedState[size];
21490            }
21491        };
21492    }
21493
21494    /**
21495     * A set of information given to a view when it is attached to its parent
21496     * window.
21497     */
21498    final static class AttachInfo {
21499        interface Callbacks {
21500            void playSoundEffect(int effectId);
21501            boolean performHapticFeedback(int effectId, boolean always);
21502        }
21503
21504        /**
21505         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
21506         * to a Handler. This class contains the target (View) to invalidate and
21507         * the coordinates of the dirty rectangle.
21508         *
21509         * For performance purposes, this class also implements a pool of up to
21510         * POOL_LIMIT objects that get reused. This reduces memory allocations
21511         * whenever possible.
21512         */
21513        static class InvalidateInfo {
21514            private static final int POOL_LIMIT = 10;
21515
21516            private static final SynchronizedPool<InvalidateInfo> sPool =
21517                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
21518
21519            View target;
21520
21521            int left;
21522            int top;
21523            int right;
21524            int bottom;
21525
21526            public static InvalidateInfo obtain() {
21527                InvalidateInfo instance = sPool.acquire();
21528                return (instance != null) ? instance : new InvalidateInfo();
21529            }
21530
21531            public void recycle() {
21532                target = null;
21533                sPool.release(this);
21534            }
21535        }
21536
21537        final IWindowSession mSession;
21538
21539        final IWindow mWindow;
21540
21541        final IBinder mWindowToken;
21542
21543        final Display mDisplay;
21544
21545        final Callbacks mRootCallbacks;
21546
21547        IWindowId mIWindowId;
21548        WindowId mWindowId;
21549
21550        /**
21551         * The top view of the hierarchy.
21552         */
21553        View mRootView;
21554
21555        IBinder mPanelParentWindowToken;
21556
21557        boolean mHardwareAccelerated;
21558        boolean mHardwareAccelerationRequested;
21559        HardwareRenderer mHardwareRenderer;
21560        List<RenderNode> mPendingAnimatingRenderNodes;
21561
21562        /**
21563         * The state of the display to which the window is attached, as reported
21564         * by {@link Display#getState()}.  Note that the display state constants
21565         * declared by {@link Display} do not exactly line up with the screen state
21566         * constants declared by {@link View} (there are more display states than
21567         * screen states).
21568         */
21569        int mDisplayState = Display.STATE_UNKNOWN;
21570
21571        /**
21572         * Scale factor used by the compatibility mode
21573         */
21574        float mApplicationScale;
21575
21576        /**
21577         * Indicates whether the application is in compatibility mode
21578         */
21579        boolean mScalingRequired;
21580
21581        /**
21582         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
21583         */
21584        boolean mTurnOffWindowResizeAnim;
21585
21586        /**
21587         * Left position of this view's window
21588         */
21589        int mWindowLeft;
21590
21591        /**
21592         * Top position of this view's window
21593         */
21594        int mWindowTop;
21595
21596        /**
21597         * Indicates whether views need to use 32-bit drawing caches
21598         */
21599        boolean mUse32BitDrawingCache;
21600
21601        /**
21602         * For windows that are full-screen but using insets to layout inside
21603         * of the screen areas, these are the current insets to appear inside
21604         * the overscan area of the display.
21605         */
21606        final Rect mOverscanInsets = new Rect();
21607
21608        /**
21609         * For windows that are full-screen but using insets to layout inside
21610         * of the screen decorations, these are the current insets for the
21611         * content of the window.
21612         */
21613        final Rect mContentInsets = new Rect();
21614
21615        /**
21616         * For windows that are full-screen but using insets to layout inside
21617         * of the screen decorations, these are the current insets for the
21618         * actual visible parts of the window.
21619         */
21620        final Rect mVisibleInsets = new Rect();
21621
21622        /**
21623         * For windows that are full-screen but using insets to layout inside
21624         * of the screen decorations, these are the current insets for the
21625         * stable system windows.
21626         */
21627        final Rect mStableInsets = new Rect();
21628
21629        /**
21630         * For windows that include areas that are not covered by real surface these are the outsets
21631         * for real surface.
21632         */
21633        final Rect mOutsets = new Rect();
21634
21635        /**
21636         * The internal insets given by this window.  This value is
21637         * supplied by the client (through
21638         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
21639         * be given to the window manager when changed to be used in laying
21640         * out windows behind it.
21641         */
21642        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
21643                = new ViewTreeObserver.InternalInsetsInfo();
21644
21645        /**
21646         * Set to true when mGivenInternalInsets is non-empty.
21647         */
21648        boolean mHasNonEmptyGivenInternalInsets;
21649
21650        /**
21651         * All views in the window's hierarchy that serve as scroll containers,
21652         * used to determine if the window can be resized or must be panned
21653         * to adjust for a soft input area.
21654         */
21655        final ArrayList<View> mScrollContainers = new ArrayList<View>();
21656
21657        final KeyEvent.DispatcherState mKeyDispatchState
21658                = new KeyEvent.DispatcherState();
21659
21660        /**
21661         * Indicates whether the view's window currently has the focus.
21662         */
21663        boolean mHasWindowFocus;
21664
21665        /**
21666         * The current visibility of the window.
21667         */
21668        int mWindowVisibility;
21669
21670        /**
21671         * Indicates the time at which drawing started to occur.
21672         */
21673        long mDrawingTime;
21674
21675        /**
21676         * Indicates whether or not ignoring the DIRTY_MASK flags.
21677         */
21678        boolean mIgnoreDirtyState;
21679
21680        /**
21681         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21682         * to avoid clearing that flag prematurely.
21683         */
21684        boolean mSetIgnoreDirtyState = false;
21685
21686        /**
21687         * Indicates whether the view's window is currently in touch mode.
21688         */
21689        boolean mInTouchMode;
21690
21691        /**
21692         * Indicates whether the view has requested unbuffered input dispatching for the current
21693         * event stream.
21694         */
21695        boolean mUnbufferedDispatchRequested;
21696
21697        /**
21698         * Indicates that ViewAncestor should trigger a global layout change
21699         * the next time it performs a traversal
21700         */
21701        boolean mRecomputeGlobalAttributes;
21702
21703        /**
21704         * Always report new attributes at next traversal.
21705         */
21706        boolean mForceReportNewAttributes;
21707
21708        /**
21709         * Set during a traveral if any views want to keep the screen on.
21710         */
21711        boolean mKeepScreenOn;
21712
21713        /**
21714         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21715         */
21716        int mSystemUiVisibility;
21717
21718        /**
21719         * Hack to force certain system UI visibility flags to be cleared.
21720         */
21721        int mDisabledSystemUiVisibility;
21722
21723        /**
21724         * Last global system UI visibility reported by the window manager.
21725         */
21726        int mGlobalSystemUiVisibility;
21727
21728        /**
21729         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21730         * attached.
21731         */
21732        boolean mHasSystemUiListeners;
21733
21734        /**
21735         * Set if the window has requested to extend into the overscan region
21736         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21737         */
21738        boolean mOverscanRequested;
21739
21740        /**
21741         * Set if the visibility of any views has changed.
21742         */
21743        boolean mViewVisibilityChanged;
21744
21745        /**
21746         * Set to true if a view has been scrolled.
21747         */
21748        boolean mViewScrollChanged;
21749
21750        /**
21751         * Set to true if high contrast mode enabled
21752         */
21753        boolean mHighContrastText;
21754
21755        /**
21756         * Global to the view hierarchy used as a temporary for dealing with
21757         * x/y points in the transparent region computations.
21758         */
21759        final int[] mTransparentLocation = new int[2];
21760
21761        /**
21762         * Global to the view hierarchy used as a temporary for dealing with
21763         * x/y points in the ViewGroup.invalidateChild implementation.
21764         */
21765        final int[] mInvalidateChildLocation = new int[2];
21766
21767        /**
21768         * Global to the view hierarchy used as a temporary for dealng with
21769         * computing absolute on-screen location.
21770         */
21771        final int[] mTmpLocation = new int[2];
21772
21773        /**
21774         * Global to the view hierarchy used as a temporary for dealing with
21775         * x/y location when view is transformed.
21776         */
21777        final float[] mTmpTransformLocation = new float[2];
21778
21779        /**
21780         * The view tree observer used to dispatch global events like
21781         * layout, pre-draw, touch mode change, etc.
21782         */
21783        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21784
21785        /**
21786         * A Canvas used by the view hierarchy to perform bitmap caching.
21787         */
21788        Canvas mCanvas;
21789
21790        /**
21791         * The view root impl.
21792         */
21793        final ViewRootImpl mViewRootImpl;
21794
21795        /**
21796         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21797         * handler can be used to pump events in the UI events queue.
21798         */
21799        final Handler mHandler;
21800
21801        /**
21802         * Temporary for use in computing invalidate rectangles while
21803         * calling up the hierarchy.
21804         */
21805        final Rect mTmpInvalRect = new Rect();
21806
21807        /**
21808         * Temporary for use in computing hit areas with transformed views
21809         */
21810        final RectF mTmpTransformRect = new RectF();
21811
21812        /**
21813         * Temporary for use in computing hit areas with transformed views
21814         */
21815        final RectF mTmpTransformRect1 = new RectF();
21816
21817        /**
21818         * Temporary list of rectanges.
21819         */
21820        final List<RectF> mTmpRectList = new ArrayList<>();
21821
21822        /**
21823         * Temporary for use in transforming invalidation rect
21824         */
21825        final Matrix mTmpMatrix = new Matrix();
21826
21827        /**
21828         * Temporary for use in transforming invalidation rect
21829         */
21830        final Transformation mTmpTransformation = new Transformation();
21831
21832        /**
21833         * Temporary for use in querying outlines from OutlineProviders
21834         */
21835        final Outline mTmpOutline = new Outline();
21836
21837        /**
21838         * Temporary list for use in collecting focusable descendents of a view.
21839         */
21840        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21841
21842        /**
21843         * The id of the window for accessibility purposes.
21844         */
21845        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21846
21847        /**
21848         * Flags related to accessibility processing.
21849         *
21850         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21851         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21852         */
21853        int mAccessibilityFetchFlags;
21854
21855        /**
21856         * The drawable for highlighting accessibility focus.
21857         */
21858        Drawable mAccessibilityFocusDrawable;
21859
21860        /**
21861         * Show where the margins, bounds and layout bounds are for each view.
21862         */
21863        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21864
21865        /**
21866         * Point used to compute visible regions.
21867         */
21868        final Point mPoint = new Point();
21869
21870        /**
21871         * Used to track which View originated a requestLayout() call, used when
21872         * requestLayout() is called during layout.
21873         */
21874        View mViewRequestingLayout;
21875
21876        /**
21877         * Creates a new set of attachment information with the specified
21878         * events handler and thread.
21879         *
21880         * @param handler the events handler the view must use
21881         */
21882        AttachInfo(IWindowSession session, IWindow window, Display display,
21883                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21884            mSession = session;
21885            mWindow = window;
21886            mWindowToken = window.asBinder();
21887            mDisplay = display;
21888            mViewRootImpl = viewRootImpl;
21889            mHandler = handler;
21890            mRootCallbacks = effectPlayer;
21891        }
21892    }
21893
21894    /**
21895     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21896     * is supported. This avoids keeping too many unused fields in most
21897     * instances of View.</p>
21898     */
21899    private static class ScrollabilityCache implements Runnable {
21900
21901        /**
21902         * Scrollbars are not visible
21903         */
21904        public static final int OFF = 0;
21905
21906        /**
21907         * Scrollbars are visible
21908         */
21909        public static final int ON = 1;
21910
21911        /**
21912         * Scrollbars are fading away
21913         */
21914        public static final int FADING = 2;
21915
21916        public boolean fadeScrollBars;
21917
21918        public int fadingEdgeLength;
21919        public int scrollBarDefaultDelayBeforeFade;
21920        public int scrollBarFadeDuration;
21921
21922        public int scrollBarSize;
21923        public ScrollBarDrawable scrollBar;
21924        public float[] interpolatorValues;
21925        public View host;
21926
21927        public final Paint paint;
21928        public final Matrix matrix;
21929        public Shader shader;
21930
21931        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21932
21933        private static final float[] OPAQUE = { 255 };
21934        private static final float[] TRANSPARENT = { 0.0f };
21935
21936        /**
21937         * When fading should start. This time moves into the future every time
21938         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21939         */
21940        public long fadeStartTime;
21941
21942
21943        /**
21944         * The current state of the scrollbars: ON, OFF, or FADING
21945         */
21946        public int state = OFF;
21947
21948        private int mLastColor;
21949
21950        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21951            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21952            scrollBarSize = configuration.getScaledScrollBarSize();
21953            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21954            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21955
21956            paint = new Paint();
21957            matrix = new Matrix();
21958            // use use a height of 1, and then wack the matrix each time we
21959            // actually use it.
21960            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21961            paint.setShader(shader);
21962            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21963
21964            this.host = host;
21965        }
21966
21967        public void setFadeColor(int color) {
21968            if (color != mLastColor) {
21969                mLastColor = color;
21970
21971                if (color != 0) {
21972                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21973                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21974                    paint.setShader(shader);
21975                    // Restore the default transfer mode (src_over)
21976                    paint.setXfermode(null);
21977                } else {
21978                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21979                    paint.setShader(shader);
21980                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21981                }
21982            }
21983        }
21984
21985        public void run() {
21986            long now = AnimationUtils.currentAnimationTimeMillis();
21987            if (now >= fadeStartTime) {
21988
21989                // the animation fades the scrollbars out by changing
21990                // the opacity (alpha) from fully opaque to fully
21991                // transparent
21992                int nextFrame = (int) now;
21993                int framesCount = 0;
21994
21995                Interpolator interpolator = scrollBarInterpolator;
21996
21997                // Start opaque
21998                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21999
22000                // End transparent
22001                nextFrame += scrollBarFadeDuration;
22002                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
22003
22004                state = FADING;
22005
22006                // Kick off the fade animation
22007                host.invalidate(true);
22008            }
22009        }
22010    }
22011
22012    /**
22013     * Resuable callback for sending
22014     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
22015     */
22016    private class SendViewScrolledAccessibilityEvent implements Runnable {
22017        public volatile boolean mIsPending;
22018
22019        public void run() {
22020            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
22021            mIsPending = false;
22022        }
22023    }
22024
22025    /**
22026     * <p>
22027     * This class represents a delegate that can be registered in a {@link View}
22028     * to enhance accessibility support via composition rather via inheritance.
22029     * It is specifically targeted to widget developers that extend basic View
22030     * classes i.e. classes in package android.view, that would like their
22031     * applications to be backwards compatible.
22032     * </p>
22033     * <div class="special reference">
22034     * <h3>Developer Guides</h3>
22035     * <p>For more information about making applications accessible, read the
22036     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
22037     * developer guide.</p>
22038     * </div>
22039     * <p>
22040     * A scenario in which a developer would like to use an accessibility delegate
22041     * is overriding a method introduced in a later API version then the minimal API
22042     * version supported by the application. For example, the method
22043     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
22044     * in API version 4 when the accessibility APIs were first introduced. If a
22045     * developer would like his application to run on API version 4 devices (assuming
22046     * all other APIs used by the application are version 4 or lower) and take advantage
22047     * of this method, instead of overriding the method which would break the application's
22048     * backwards compatibility, he can override the corresponding method in this
22049     * delegate and register the delegate in the target View if the API version of
22050     * the system is high enough i.e. the API version is same or higher to the API
22051     * version that introduced
22052     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
22053     * </p>
22054     * <p>
22055     * Here is an example implementation:
22056     * </p>
22057     * <code><pre><p>
22058     * if (Build.VERSION.SDK_INT >= 14) {
22059     *     // If the API version is equal of higher than the version in
22060     *     // which onInitializeAccessibilityNodeInfo was introduced we
22061     *     // register a delegate with a customized implementation.
22062     *     View view = findViewById(R.id.view_id);
22063     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
22064     *         public void onInitializeAccessibilityNodeInfo(View host,
22065     *                 AccessibilityNodeInfo info) {
22066     *             // Let the default implementation populate the info.
22067     *             super.onInitializeAccessibilityNodeInfo(host, info);
22068     *             // Set some other information.
22069     *             info.setEnabled(host.isEnabled());
22070     *         }
22071     *     });
22072     * }
22073     * </code></pre></p>
22074     * <p>
22075     * This delegate contains methods that correspond to the accessibility methods
22076     * in View. If a delegate has been specified the implementation in View hands
22077     * off handling to the corresponding method in this delegate. The default
22078     * implementation the delegate methods behaves exactly as the corresponding
22079     * method in View for the case of no accessibility delegate been set. Hence,
22080     * to customize the behavior of a View method, clients can override only the
22081     * corresponding delegate method without altering the behavior of the rest
22082     * accessibility related methods of the host view.
22083     * </p>
22084     */
22085    public static class AccessibilityDelegate {
22086
22087        /**
22088         * Sends an accessibility event of the given type. If accessibility is not
22089         * enabled this method has no effect.
22090         * <p>
22091         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
22092         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
22093         * been set.
22094         * </p>
22095         *
22096         * @param host The View hosting the delegate.
22097         * @param eventType The type of the event to send.
22098         *
22099         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
22100         */
22101        public void sendAccessibilityEvent(View host, int eventType) {
22102            host.sendAccessibilityEventInternal(eventType);
22103        }
22104
22105        /**
22106         * Performs the specified accessibility action on the view. For
22107         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
22108         * <p>
22109         * The default implementation behaves as
22110         * {@link View#performAccessibilityAction(int, Bundle)
22111         *  View#performAccessibilityAction(int, Bundle)} for the case of
22112         *  no accessibility delegate been set.
22113         * </p>
22114         *
22115         * @param action The action to perform.
22116         * @return Whether the action was performed.
22117         *
22118         * @see View#performAccessibilityAction(int, Bundle)
22119         *      View#performAccessibilityAction(int, Bundle)
22120         */
22121        public boolean performAccessibilityAction(View host, int action, Bundle args) {
22122            return host.performAccessibilityActionInternal(action, args);
22123        }
22124
22125        /**
22126         * Sends an accessibility event. This method behaves exactly as
22127         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
22128         * empty {@link AccessibilityEvent} and does not perform a check whether
22129         * accessibility is enabled.
22130         * <p>
22131         * The default implementation behaves as
22132         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
22133         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
22134         * the case of no accessibility delegate been set.
22135         * </p>
22136         *
22137         * @param host The View hosting the delegate.
22138         * @param event The event to send.
22139         *
22140         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
22141         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
22142         */
22143        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
22144            host.sendAccessibilityEventUncheckedInternal(event);
22145        }
22146
22147        /**
22148         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
22149         * to its children for adding their text content to the event.
22150         * <p>
22151         * The default implementation behaves as
22152         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
22153         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
22154         * the case of no accessibility delegate been set.
22155         * </p>
22156         *
22157         * @param host The View hosting the delegate.
22158         * @param event The event.
22159         * @return True if the event population was completed.
22160         *
22161         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
22162         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
22163         */
22164        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
22165            return host.dispatchPopulateAccessibilityEventInternal(event);
22166        }
22167
22168        /**
22169         * Gives a chance to the host View to populate the accessibility event with its
22170         * text content.
22171         * <p>
22172         * The default implementation behaves as
22173         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
22174         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
22175         * the case of no accessibility delegate been set.
22176         * </p>
22177         *
22178         * @param host The View hosting the delegate.
22179         * @param event The accessibility event which to populate.
22180         *
22181         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
22182         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
22183         */
22184        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
22185            host.onPopulateAccessibilityEventInternal(event);
22186        }
22187
22188        /**
22189         * Initializes an {@link AccessibilityEvent} with information about the
22190         * the host View which is the event source.
22191         * <p>
22192         * The default implementation behaves as
22193         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
22194         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
22195         * the case of no accessibility delegate been set.
22196         * </p>
22197         *
22198         * @param host The View hosting the delegate.
22199         * @param event The event to initialize.
22200         *
22201         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
22202         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
22203         */
22204        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
22205            host.onInitializeAccessibilityEventInternal(event);
22206        }
22207
22208        /**
22209         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
22210         * <p>
22211         * The default implementation behaves as
22212         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
22213         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
22214         * the case of no accessibility delegate been set.
22215         * </p>
22216         *
22217         * @param host The View hosting the delegate.
22218         * @param info The instance to initialize.
22219         *
22220         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
22221         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
22222         */
22223        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
22224            host.onInitializeAccessibilityNodeInfoInternal(info);
22225        }
22226
22227        /**
22228         * Called when a child of the host View has requested sending an
22229         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
22230         * to augment the event.
22231         * <p>
22232         * The default implementation behaves as
22233         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
22234         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
22235         * the case of no accessibility delegate been set.
22236         * </p>
22237         *
22238         * @param host The View hosting the delegate.
22239         * @param child The child which requests sending the event.
22240         * @param event The event to be sent.
22241         * @return True if the event should be sent
22242         *
22243         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
22244         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
22245         */
22246        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
22247                AccessibilityEvent event) {
22248            return host.onRequestSendAccessibilityEventInternal(child, event);
22249        }
22250
22251        /**
22252         * Gets the provider for managing a virtual view hierarchy rooted at this View
22253         * and reported to {@link android.accessibilityservice.AccessibilityService}s
22254         * that explore the window content.
22255         * <p>
22256         * The default implementation behaves as
22257         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
22258         * the case of no accessibility delegate been set.
22259         * </p>
22260         *
22261         * @return The provider.
22262         *
22263         * @see AccessibilityNodeProvider
22264         */
22265        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
22266            return null;
22267        }
22268
22269        /**
22270         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
22271         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
22272         * This method is responsible for obtaining an accessibility node info from a
22273         * pool of reusable instances and calling
22274         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
22275         * view to initialize the former.
22276         * <p>
22277         * <strong>Note:</strong> The client is responsible for recycling the obtained
22278         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
22279         * creation.
22280         * </p>
22281         * <p>
22282         * The default implementation behaves as
22283         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
22284         * the case of no accessibility delegate been set.
22285         * </p>
22286         * @return A populated {@link AccessibilityNodeInfo}.
22287         *
22288         * @see AccessibilityNodeInfo
22289         *
22290         * @hide
22291         */
22292        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
22293            return host.createAccessibilityNodeInfoInternal();
22294        }
22295    }
22296
22297    private class MatchIdPredicate implements Predicate<View> {
22298        public int mId;
22299
22300        @Override
22301        public boolean apply(View view) {
22302            return (view.mID == mId);
22303        }
22304    }
22305
22306    private class MatchLabelForPredicate implements Predicate<View> {
22307        private int mLabeledId;
22308
22309        @Override
22310        public boolean apply(View view) {
22311            return (view.mLabelForId == mLabeledId);
22312        }
22313    }
22314
22315    private class SendViewStateChangedAccessibilityEvent implements Runnable {
22316        private int mChangeTypes = 0;
22317        private boolean mPosted;
22318        private boolean mPostedWithDelay;
22319        private long mLastEventTimeMillis;
22320
22321        @Override
22322        public void run() {
22323            mPosted = false;
22324            mPostedWithDelay = false;
22325            mLastEventTimeMillis = SystemClock.uptimeMillis();
22326            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
22327                final AccessibilityEvent event = AccessibilityEvent.obtain();
22328                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
22329                event.setContentChangeTypes(mChangeTypes);
22330                sendAccessibilityEventUnchecked(event);
22331            }
22332            mChangeTypes = 0;
22333        }
22334
22335        public void runOrPost(int changeType) {
22336            mChangeTypes |= changeType;
22337
22338            // If this is a live region or the child of a live region, collect
22339            // all events from this frame and send them on the next frame.
22340            if (inLiveRegion()) {
22341                // If we're already posted with a delay, remove that.
22342                if (mPostedWithDelay) {
22343                    removeCallbacks(this);
22344                    mPostedWithDelay = false;
22345                }
22346                // Only post if we're not already posted.
22347                if (!mPosted) {
22348                    post(this);
22349                    mPosted = true;
22350                }
22351                return;
22352            }
22353
22354            if (mPosted) {
22355                return;
22356            }
22357
22358            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
22359            final long minEventIntevalMillis =
22360                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
22361            if (timeSinceLastMillis >= minEventIntevalMillis) {
22362                removeCallbacks(this);
22363                run();
22364            } else {
22365                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
22366                mPostedWithDelay = true;
22367            }
22368        }
22369    }
22370
22371    private boolean inLiveRegion() {
22372        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
22373            return true;
22374        }
22375
22376        ViewParent parent = getParent();
22377        while (parent instanceof View) {
22378            if (((View) parent).getAccessibilityLiveRegion()
22379                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
22380                return true;
22381            }
22382            parent = parent.getParent();
22383        }
22384
22385        return false;
22386    }
22387
22388    /**
22389     * Dump all private flags in readable format, useful for documentation and
22390     * sanity checking.
22391     */
22392    private static void dumpFlags() {
22393        final HashMap<String, String> found = Maps.newHashMap();
22394        try {
22395            for (Field field : View.class.getDeclaredFields()) {
22396                final int modifiers = field.getModifiers();
22397                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
22398                    if (field.getType().equals(int.class)) {
22399                        final int value = field.getInt(null);
22400                        dumpFlag(found, field.getName(), value);
22401                    } else if (field.getType().equals(int[].class)) {
22402                        final int[] values = (int[]) field.get(null);
22403                        for (int i = 0; i < values.length; i++) {
22404                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
22405                        }
22406                    }
22407                }
22408            }
22409        } catch (IllegalAccessException e) {
22410            throw new RuntimeException(e);
22411        }
22412
22413        final ArrayList<String> keys = Lists.newArrayList();
22414        keys.addAll(found.keySet());
22415        Collections.sort(keys);
22416        for (String key : keys) {
22417            Log.d(VIEW_LOG_TAG, found.get(key));
22418        }
22419    }
22420
22421    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
22422        // Sort flags by prefix, then by bits, always keeping unique keys
22423        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
22424        final int prefix = name.indexOf('_');
22425        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
22426        final String output = bits + " " + name;
22427        found.put(key, output);
22428    }
22429
22430    /** {@hide} */
22431    public void encode(@NonNull ViewHierarchyEncoder stream) {
22432        stream.beginObject(this);
22433        encodeProperties(stream);
22434        stream.endObject();
22435    }
22436
22437    /** {@hide} */
22438    @CallSuper
22439    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
22440        Object resolveId = ViewDebug.resolveId(getContext(), mID);
22441        if (resolveId instanceof String) {
22442            stream.addProperty("id", (String) resolveId);
22443        } else {
22444            stream.addProperty("id", mID);
22445        }
22446
22447        stream.addProperty("misc:transformation.alpha",
22448                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
22449        stream.addProperty("misc:transitionName", getTransitionName());
22450
22451        // layout
22452        stream.addProperty("layout:left", mLeft);
22453        stream.addProperty("layout:right", mRight);
22454        stream.addProperty("layout:top", mTop);
22455        stream.addProperty("layout:bottom", mBottom);
22456        stream.addProperty("layout:width", getWidth());
22457        stream.addProperty("layout:height", getHeight());
22458        stream.addProperty("layout:layoutDirection", getLayoutDirection());
22459        stream.addProperty("layout:layoutRtl", isLayoutRtl());
22460        stream.addProperty("layout:hasTransientState", hasTransientState());
22461        stream.addProperty("layout:baseline", getBaseline());
22462
22463        // layout params
22464        ViewGroup.LayoutParams layoutParams = getLayoutParams();
22465        if (layoutParams != null) {
22466            stream.addPropertyKey("layoutParams");
22467            layoutParams.encode(stream);
22468        }
22469
22470        // scrolling
22471        stream.addProperty("scrolling:scrollX", mScrollX);
22472        stream.addProperty("scrolling:scrollY", mScrollY);
22473
22474        // padding
22475        stream.addProperty("padding:paddingLeft", mPaddingLeft);
22476        stream.addProperty("padding:paddingRight", mPaddingRight);
22477        stream.addProperty("padding:paddingTop", mPaddingTop);
22478        stream.addProperty("padding:paddingBottom", mPaddingBottom);
22479        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
22480        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
22481        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
22482        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
22483        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
22484
22485        // measurement
22486        stream.addProperty("measurement:minHeight", mMinHeight);
22487        stream.addProperty("measurement:minWidth", mMinWidth);
22488        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
22489        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
22490
22491        // drawing
22492        stream.addProperty("drawing:elevation", getElevation());
22493        stream.addProperty("drawing:translationX", getTranslationX());
22494        stream.addProperty("drawing:translationY", getTranslationY());
22495        stream.addProperty("drawing:translationZ", getTranslationZ());
22496        stream.addProperty("drawing:rotation", getRotation());
22497        stream.addProperty("drawing:rotationX", getRotationX());
22498        stream.addProperty("drawing:rotationY", getRotationY());
22499        stream.addProperty("drawing:scaleX", getScaleX());
22500        stream.addProperty("drawing:scaleY", getScaleY());
22501        stream.addProperty("drawing:pivotX", getPivotX());
22502        stream.addProperty("drawing:pivotY", getPivotY());
22503        stream.addProperty("drawing:opaque", isOpaque());
22504        stream.addProperty("drawing:alpha", getAlpha());
22505        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
22506        stream.addProperty("drawing:shadow", hasShadow());
22507        stream.addProperty("drawing:solidColor", getSolidColor());
22508        stream.addProperty("drawing:layerType", mLayerType);
22509        stream.addProperty("drawing:willNotDraw", willNotDraw());
22510        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
22511        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
22512        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
22513        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
22514
22515        // focus
22516        stream.addProperty("focus:hasFocus", hasFocus());
22517        stream.addProperty("focus:isFocused", isFocused());
22518        stream.addProperty("focus:isFocusable", isFocusable());
22519        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
22520
22521        stream.addProperty("misc:clickable", isClickable());
22522        stream.addProperty("misc:pressed", isPressed());
22523        stream.addProperty("misc:selected", isSelected());
22524        stream.addProperty("misc:touchMode", isInTouchMode());
22525        stream.addProperty("misc:hovered", isHovered());
22526        stream.addProperty("misc:activated", isActivated());
22527
22528        stream.addProperty("misc:visibility", getVisibility());
22529        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
22530        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
22531
22532        stream.addProperty("misc:enabled", isEnabled());
22533        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
22534        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
22535
22536        // theme attributes
22537        Resources.Theme theme = getContext().getTheme();
22538        if (theme != null) {
22539            stream.addPropertyKey("theme");
22540            theme.encode(stream);
22541        }
22542
22543        // view attribute information
22544        int n = mAttributes != null ? mAttributes.length : 0;
22545        stream.addProperty("meta:__attrCount__", n/2);
22546        for (int i = 0; i < n; i += 2) {
22547            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
22548        }
22549
22550        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
22551
22552        // text
22553        stream.addProperty("text:textDirection", getTextDirection());
22554        stream.addProperty("text:textAlignment", getTextAlignment());
22555
22556        // accessibility
22557        CharSequence contentDescription = getContentDescription();
22558        stream.addProperty("accessibility:contentDescription",
22559                contentDescription == null ? "" : contentDescription.toString());
22560        stream.addProperty("accessibility:labelFor", getLabelFor());
22561        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
22562    }
22563}
22564