View.java revision 04e15b8a2319bb451cd884c35df0dcf656c55f15
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.IntRange;
28import android.annotation.LayoutRes;
29import android.annotation.NonNull;
30import android.annotation.Nullable;
31import android.annotation.Size;
32import android.annotation.UiThread;
33import android.content.ClipData;
34import android.content.Context;
35import android.content.ContextWrapper;
36import android.content.Intent;
37import android.content.res.ColorStateList;
38import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.content.res.TypedArray;
41import android.graphics.Bitmap;
42import android.graphics.Canvas;
43import android.graphics.Insets;
44import android.graphics.Interpolator;
45import android.graphics.LinearGradient;
46import android.graphics.Matrix;
47import android.graphics.Outline;
48import android.graphics.Paint;
49import android.graphics.PixelFormat;
50import android.graphics.Point;
51import android.graphics.PorterDuff;
52import android.graphics.PorterDuffXfermode;
53import android.graphics.Rect;
54import android.graphics.RectF;
55import android.graphics.Region;
56import android.graphics.Shader;
57import android.graphics.drawable.ColorDrawable;
58import android.graphics.drawable.Drawable;
59import android.hardware.display.DisplayManagerGlobal;
60import android.os.Build.VERSION_CODES;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Parcel;
65import android.os.Parcelable;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.SystemProperties;
69import android.os.Trace;
70import android.text.TextUtils;
71import android.util.AttributeSet;
72import android.util.FloatProperty;
73import android.util.LayoutDirection;
74import android.util.Log;
75import android.util.LongSparseLongArray;
76import android.util.Pools.SynchronizedPool;
77import android.util.Property;
78import android.util.SparseArray;
79import android.util.StateSet;
80import android.util.SuperNotCalledException;
81import android.util.TypedValue;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.AccessibilityIterators.TextSegmentIterator;
86import android.view.AccessibilityIterators.WordTextSegmentIterator;
87import android.view.accessibility.AccessibilityEvent;
88import android.view.accessibility.AccessibilityEventSource;
89import android.view.accessibility.AccessibilityManager;
90import android.view.accessibility.AccessibilityNodeInfo;
91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
92import android.view.accessibility.AccessibilityNodeProvider;
93import android.view.animation.Animation;
94import android.view.animation.AnimationUtils;
95import android.view.animation.Transformation;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputConnection;
98import android.view.inputmethod.InputMethodManager;
99import android.widget.Checkable;
100import android.widget.FrameLayout;
101import android.widget.ScrollBarDrawable;
102import static android.os.Build.VERSION_CODES.*;
103import static java.lang.Math.max;
104
105import com.android.internal.R;
106import com.android.internal.util.Predicate;
107import com.android.internal.view.menu.MenuBuilder;
108import com.android.internal.widget.ScrollBarUtils;
109import com.google.android.collect.Lists;
110import com.google.android.collect.Maps;
111
112import java.lang.NullPointerException;
113import java.lang.annotation.Retention;
114import java.lang.annotation.RetentionPolicy;
115import java.lang.ref.WeakReference;
116import java.lang.reflect.Field;
117import java.lang.reflect.InvocationTargetException;
118import java.lang.reflect.Method;
119import java.lang.reflect.Modifier;
120import java.util.ArrayList;
121import java.util.Arrays;
122import java.util.Collections;
123import java.util.HashMap;
124import java.util.List;
125import java.util.Locale;
126import java.util.Map;
127import java.util.concurrent.CopyOnWriteArrayList;
128import java.util.concurrent.atomic.AtomicInteger;
129
130/**
131 * <p>
132 * This class represents the basic building block for user interface components. A View
133 * occupies a rectangular area on the screen and is responsible for drawing and
134 * event handling. View is the base class for <em>widgets</em>, which are
135 * used to create interactive UI components (buttons, text fields, etc.). The
136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
137 * are invisible containers that hold other Views (or other ViewGroups) and define
138 * their layout properties.
139 * </p>
140 *
141 * <div class="special reference">
142 * <h3>Developer Guides</h3>
143 * <p>For information about using this class to develop your application's user interface,
144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
145 * </div>
146 *
147 * <a name="Using"></a>
148 * <h3>Using Views</h3>
149 * <p>
150 * All of the views in a window are arranged in a single tree. You can add views
151 * either from code or by specifying a tree of views in one or more XML layout
152 * files. There are many specialized subclasses of views that act as controls or
153 * are capable of displaying text, images, or other content.
154 * </p>
155 * <p>
156 * Once you have created a tree of views, there are typically a few types of
157 * common operations you may wish to perform:
158 * <ul>
159 * <li><strong>Set properties:</strong> for example setting the text of a
160 * {@link android.widget.TextView}. The available properties and the methods
161 * that set them will vary among the different subclasses of views. Note that
162 * properties that are known at build time can be set in the XML layout
163 * files.</li>
164 * <li><strong>Set focus:</strong> The framework will handle moving focus in
165 * response to user input. To force focus to a specific view, call
166 * {@link #requestFocus}.</li>
167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
168 * that will be notified when something interesting happens to the view. For
169 * example, all views will let you set a listener to be notified when the view
170 * gains or loses focus. You can register such a listener using
171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
172 * Other view subclasses offer more specialized listeners. For example, a Button
173 * exposes a listener to notify clients when the button is clicked.</li>
174 * <li><strong>Set visibility:</strong> You can hide or show views using
175 * {@link #setVisibility(int)}.</li>
176 * </ul>
177 * </p>
178 * <p><em>
179 * Note: The Android framework is responsible for measuring, laying out and
180 * drawing views. You should not call methods that perform these actions on
181 * views yourself unless you are actually implementing a
182 * {@link android.view.ViewGroup}.
183 * </em></p>
184 *
185 * <a name="Lifecycle"></a>
186 * <h3>Implementing a Custom View</h3>
187 *
188 * <p>
189 * To implement a custom view, you will usually begin by providing overrides for
190 * some of the standard methods that the framework calls on all views. You do
191 * not need to override all of these methods. In fact, you can start by just
192 * overriding {@link #onDraw(android.graphics.Canvas)}.
193 * <table border="2" width="85%" align="center" cellpadding="5">
194 *     <thead>
195 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
196 *     </thead>
197 *
198 *     <tbody>
199 *     <tr>
200 *         <td rowspan="2">Creation</td>
201 *         <td>Constructors</td>
202 *         <td>There is a form of the constructor that are called when the view
203 *         is created from code and a form that is called when the view is
204 *         inflated from a layout file. The second form should parse and apply
205 *         any attributes defined in the layout file.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onFinishInflate()}</code></td>
210 *         <td>Called after a view and all of its children has been inflated
211 *         from XML.</td>
212 *     </tr>
213 *
214 *     <tr>
215 *         <td rowspan="3">Layout</td>
216 *         <td><code>{@link #onMeasure(int, int)}</code></td>
217 *         <td>Called to determine the size requirements for this view and all
218 *         of its children.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
223 *         <td>Called when this view should assign a size and position to all
224 *         of its children.
225 *         </td>
226 *     </tr>
227 *     <tr>
228 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
229 *         <td>Called when the size of this view has changed.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td>Drawing</td>
235 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
236 *         <td>Called when the view should render its content.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="4">Event processing</td>
242 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
243 *         <td>Called when a new hardware key event occurs.
244 *         </td>
245 *     </tr>
246 *     <tr>
247 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
248 *         <td>Called when a hardware key up event occurs.
249 *         </td>
250 *     </tr>
251 *     <tr>
252 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
253 *         <td>Called when a trackball motion event occurs.
254 *         </td>
255 *     </tr>
256 *     <tr>
257 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
258 *         <td>Called when a touch screen motion event occurs.
259 *         </td>
260 *     </tr>
261 *
262 *     <tr>
263 *         <td rowspan="2">Focus</td>
264 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
265 *         <td>Called when the view gains or loses focus.
266 *         </td>
267 *     </tr>
268 *
269 *     <tr>
270 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
271 *         <td>Called when the window containing the view gains or loses focus.
272 *         </td>
273 *     </tr>
274 *
275 *     <tr>
276 *         <td rowspan="3">Attaching</td>
277 *         <td><code>{@link #onAttachedToWindow()}</code></td>
278 *         <td>Called when the view is attached to a window.
279 *         </td>
280 *     </tr>
281 *
282 *     <tr>
283 *         <td><code>{@link #onDetachedFromWindow}</code></td>
284 *         <td>Called when the view is detached from its window.
285 *         </td>
286 *     </tr>
287 *
288 *     <tr>
289 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
290 *         <td>Called when the visibility of the window containing the view
291 *         has changed.
292 *         </td>
293 *     </tr>
294 *     </tbody>
295 *
296 * </table>
297 * </p>
298 *
299 * <a name="IDs"></a>
300 * <h3>IDs</h3>
301 * Views may have an integer id associated with them. These ids are typically
302 * assigned in the layout XML files, and are used to find specific views within
303 * the view tree. A common pattern is to:
304 * <ul>
305 * <li>Define a Button in the layout file and assign it a unique ID.
306 * <pre>
307 * &lt;Button
308 *     android:id="@+id/my_button"
309 *     android:layout_width="wrap_content"
310 *     android:layout_height="wrap_content"
311 *     android:text="@string/my_button_text"/&gt;
312 * </pre></li>
313 * <li>From the onCreate method of an Activity, find the Button
314 * <pre class="prettyprint">
315 *      Button myButton = (Button) findViewById(R.id.my_button);
316 * </pre></li>
317 * </ul>
318 * <p>
319 * View IDs need not be unique throughout the tree, but it is good practice to
320 * ensure that they are at least unique within the part of the tree you are
321 * searching.
322 * </p>
323 *
324 * <a name="Position"></a>
325 * <h3>Position</h3>
326 * <p>
327 * The geometry of a view is that of a rectangle. A view has a location,
328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
329 * two dimensions, expressed as a width and a height. The unit for location
330 * and dimensions is the pixel.
331 * </p>
332 *
333 * <p>
334 * It is possible to retrieve the location of a view by invoking the methods
335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
336 * coordinate of the rectangle representing the view. The latter returns the
337 * top, or Y, coordinate of the rectangle representing the view. These methods
338 * both return the location of the view relative to its parent. For instance,
339 * when getLeft() returns 20, that means the view is located 20 pixels to the
340 * right of the left edge of its direct parent.
341 * </p>
342 *
343 * <p>
344 * In addition, several convenience methods are offered to avoid unnecessary
345 * computations, namely {@link #getRight()} and {@link #getBottom()}.
346 * These methods return the coordinates of the right and bottom edges of the
347 * rectangle representing the view. For instance, calling {@link #getRight()}
348 * is similar to the following computation: <code>getLeft() + getWidth()</code>
349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
350 * </p>
351 *
352 * <a name="SizePaddingMargins"></a>
353 * <h3>Size, padding and margins</h3>
354 * <p>
355 * The size of a view is expressed with a width and a height. A view actually
356 * possess two pairs of width and height values.
357 * </p>
358 *
359 * <p>
360 * The first pair is known as <em>measured width</em> and
361 * <em>measured height</em>. These dimensions define how big a view wants to be
362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
364 * and {@link #getMeasuredHeight()}.
365 * </p>
366 *
367 * <p>
368 * The second pair is simply known as <em>width</em> and <em>height</em>, or
369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
370 * dimensions define the actual size of the view on screen, at drawing time and
371 * after layout. These values may, but do not have to, be different from the
372 * measured width and height. The width and height can be obtained by calling
373 * {@link #getWidth()} and {@link #getHeight()}.
374 * </p>
375 *
376 * <p>
377 * To measure its dimensions, a view takes into account its padding. The padding
378 * is expressed in pixels for the left, top, right and bottom parts of the view.
379 * Padding can be used to offset the content of the view by a specific amount of
380 * pixels. For instance, a left padding of 2 will push the view's content by
381 * 2 pixels to the right of the left edge. Padding can be set using the
382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
385 * {@link #getPaddingEnd()}.
386 * </p>
387 *
388 * <p>
389 * Even though a view can define a padding, it does not provide any support for
390 * margins. However, view groups provide such a support. Refer to
391 * {@link android.view.ViewGroup} and
392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
393 * </p>
394 *
395 * <a name="Layout"></a>
396 * <h3>Layout</h3>
397 * <p>
398 * Layout is a two pass process: a measure pass and a layout pass. The measuring
399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
400 * of the view tree. Each view pushes dimension specifications down the tree
401 * during the recursion. At the end of the measure pass, every view has stored
402 * its measurements. The second pass happens in
403 * {@link #layout(int,int,int,int)} and is also top-down. During
404 * this pass each parent is responsible for positioning all of its children
405 * using the sizes computed in the measure pass.
406 * </p>
407 *
408 * <p>
409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
410 * {@link #getMeasuredHeight()} values must be set, along with those for all of
411 * that view's descendants. A view's measured width and measured height values
412 * must respect the constraints imposed by the view's parents. This guarantees
413 * that at the end of the measure pass, all parents accept all of their
414 * children's measurements. A parent view may call measure() more than once on
415 * its children. For example, the parent may measure each child once with
416 * unspecified dimensions to find out how big they want to be, then call
417 * measure() on them again with actual numbers if the sum of all the children's
418 * unconstrained sizes is too big or too small.
419 * </p>
420 *
421 * <p>
422 * The measure pass uses two classes to communicate dimensions. The
423 * {@link MeasureSpec} class is used by views to tell their parents how they
424 * want to be measured and positioned. The base LayoutParams class just
425 * describes how big the view wants to be for both width and height. For each
426 * dimension, it can specify one of:
427 * <ul>
428 * <li> an exact number
429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
430 * (minus padding)
431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
432 * enclose its content (plus padding).
433 * </ul>
434 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
436 * an X and Y value.
437 * </p>
438 *
439 * <p>
440 * MeasureSpecs are used to push requirements down the tree from parent to
441 * child. A MeasureSpec can be in one of three modes:
442 * <ul>
443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
444 * of a child view. For example, a LinearLayout may call measure() on its child
445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
446 * tall the child view wants to be given a width of 240 pixels.
447 * <li>EXACTLY: This is used by the parent to impose an exact size on the
448 * child. The child must use this size, and guarantee that all of its
449 * descendants will fit within this size.
450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
451 * child. The child must guarantee that it and all of its descendants will fit
452 * within this size.
453 * </ul>
454 * </p>
455 *
456 * <p>
457 * To initiate a layout, call {@link #requestLayout}. This method is typically
458 * called by a view on itself when it believes that is can no longer fit within
459 * its current bounds.
460 * </p>
461 *
462 * <a name="Drawing"></a>
463 * <h3>Drawing</h3>
464 * <p>
465 * Drawing is handled by walking the tree and recording the drawing commands of
466 * any View that needs to update. After this, the drawing commands of the
467 * entire tree are issued to screen, clipped to the newly damaged area.
468 * </p>
469 *
470 * <p>
471 * The tree is largely recorded and drawn in order, with parents drawn before
472 * (i.e., behind) their children, with siblings drawn in the order they appear
473 * in the tree. If you set a background drawable for a View, then the View will
474 * draw it before calling back to its <code>onDraw()</code> method. The child
475 * drawing order can be overridden with
476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
478 * </p>
479 *
480 * <p>
481 * To force a view to draw, call {@link #invalidate()}.
482 * </p>
483 *
484 * <a name="EventHandlingThreading"></a>
485 * <h3>Event Handling and Threading</h3>
486 * <p>
487 * The basic cycle of a view is as follows:
488 * <ol>
489 * <li>An event comes in and is dispatched to the appropriate view. The view
490 * handles the event and notifies any listeners.</li>
491 * <li>If in the course of processing the event, the view's bounds may need
492 * to be changed, the view will call {@link #requestLayout()}.</li>
493 * <li>Similarly, if in the course of processing the event the view's appearance
494 * may need to be changed, the view will call {@link #invalidate()}.</li>
495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
496 * the framework will take care of measuring, laying out, and drawing the tree
497 * as appropriate.</li>
498 * </ol>
499 * </p>
500 *
501 * <p><em>Note: The entire view tree is single threaded. You must always be on
502 * the UI thread when calling any method on any view.</em>
503 * If you are doing work on other threads and want to update the state of a view
504 * from that thread, you should use a {@link Handler}.
505 * </p>
506 *
507 * <a name="FocusHandling"></a>
508 * <h3>Focus Handling</h3>
509 * <p>
510 * The framework will handle routine focus movement in response to user input.
511 * This includes changing the focus as views are removed or hidden, or as new
512 * views become available. Views indicate their willingness to take focus
513 * through the {@link #isFocusable} method. To change whether a view can take
514 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
516 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
517 * </p>
518 * <p>
519 * Focus movement is based on an algorithm which finds the nearest neighbor in a
520 * given direction. In rare cases, the default algorithm may not match the
521 * intended behavior of the developer. In these situations, you can provide
522 * explicit overrides by using these XML attributes in the layout file:
523 * <pre>
524 * nextFocusDown
525 * nextFocusLeft
526 * nextFocusRight
527 * nextFocusUp
528 * </pre>
529 * </p>
530 *
531 *
532 * <p>
533 * To get a particular view to take focus, call {@link #requestFocus()}.
534 * </p>
535 *
536 * <a name="TouchMode"></a>
537 * <h3>Touch Mode</h3>
538 * <p>
539 * When a user is navigating a user interface via directional keys such as a D-pad, it is
540 * necessary to give focus to actionable items such as buttons so the user can see
541 * what will take input.  If the device has touch capabilities, however, and the user
542 * begins interacting with the interface by touching it, it is no longer necessary to
543 * always highlight, or give focus to, a particular view.  This motivates a mode
544 * for interaction named 'touch mode'.
545 * </p>
546 * <p>
547 * For a touch capable device, once the user touches the screen, the device
548 * will enter touch mode.  From this point onward, only views for which
549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
550 * Other views that are touchable, like buttons, will not take focus when touched; they will
551 * only fire the on click listeners.
552 * </p>
553 * <p>
554 * Any time a user hits a directional key, such as a D-pad direction, the view device will
555 * exit touch mode, and find a view to take focus, so that the user may resume interacting
556 * with the user interface without touching the screen again.
557 * </p>
558 * <p>
559 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
560 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
561 * </p>
562 *
563 * <a name="Scrolling"></a>
564 * <h3>Scrolling</h3>
565 * <p>
566 * The framework provides basic support for views that wish to internally
567 * scroll their content. This includes keeping track of the X and Y scroll
568 * offset as well as mechanisms for drawing scrollbars. See
569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
570 * {@link #awakenScrollBars()} for more details.
571 * </p>
572 *
573 * <a name="Tags"></a>
574 * <h3>Tags</h3>
575 * <p>
576 * Unlike IDs, tags are not used to identify views. Tags are essentially an
577 * extra piece of information that can be associated with a view. They are most
578 * often used as a convenience to store data related to views in the views
579 * themselves rather than by putting them in a separate structure.
580 * </p>
581 * <p>
582 * Tags may be specified with character sequence values in layout XML as either
583 * a single tag using the {@link android.R.styleable#View_tag android:tag}
584 * attribute or multiple tags using the {@code <tag>} child element:
585 * <pre>
586 *     &ltView ...
587 *           android:tag="@string/mytag_value" /&gt;
588 *     &ltView ...&gt;
589 *         &lttag android:id="@+id/mytag"
590 *              android:value="@string/mytag_value" /&gt;
591 *     &lt/View>
592 * </pre>
593 * </p>
594 * <p>
595 * Tags may also be specified with arbitrary objects from code using
596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}.
597 * </p>
598 *
599 * <a name="Themes"></a>
600 * <h3>Themes</h3>
601 * <p>
602 * By default, Views are created using the theme of the Context object supplied
603 * to their constructor; however, a different theme may be specified by using
604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout
605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from
606 * code.
607 * </p>
608 * <p>
609 * When the {@link android.R.styleable#View_theme android:theme} attribute is
610 * used in XML, the specified theme is applied on top of the inflation
611 * context's theme (see {@link LayoutInflater}) and used for the view itself as
612 * well as any child elements.
613 * </p>
614 * <p>
615 * In the following example, both views will be created using the Material dark
616 * color scheme; however, because an overlay theme is used which only defines a
617 * subset of attributes, the value of
618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on
619 * the inflation context's theme (e.g. the Activity theme) will be preserved.
620 * <pre>
621 *     &ltLinearLayout
622 *             ...
623 *             android:theme="@android:theme/ThemeOverlay.Material.Dark"&gt;
624 *         &ltView ...&gt;
625 *     &lt/LinearLayout&gt;
626 * </pre>
627 * </p>
628 *
629 * <a name="Properties"></a>
630 * <h3>Properties</h3>
631 * <p>
632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
634 * available both in the {@link Property} form as well as in similarly-named setter/getter
635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
636 * be used to set persistent state associated with these rendering-related properties on the view.
637 * The properties and methods can also be used in conjunction with
638 * {@link android.animation.Animator Animator}-based animations, described more in the
639 * <a href="#Animation">Animation</a> section.
640 * </p>
641 *
642 * <a name="Animation"></a>
643 * <h3>Animation</h3>
644 * <p>
645 * Starting with Android 3.0, the preferred way of animating views is to use the
646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
651 * makes animating these View properties particularly easy and efficient.
652 * </p>
653 * <p>
654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
655 * You can attach an {@link Animation} object to a view using
656 * {@link #setAnimation(Animation)} or
657 * {@link #startAnimation(Animation)}. The animation can alter the scale,
658 * rotation, translation and alpha of a view over time. If the animation is
659 * attached to a view that has children, the animation will affect the entire
660 * subtree rooted by that node. When an animation is started, the framework will
661 * take care of redrawing the appropriate views until the animation completes.
662 * </p>
663 *
664 * <a name="Security"></a>
665 * <h3>Security</h3>
666 * <p>
667 * Sometimes it is essential that an application be able to verify that an action
668 * is being performed with the full knowledge and consent of the user, such as
669 * granting a permission request, making a purchase or clicking on an advertisement.
670 * Unfortunately, a malicious application could try to spoof the user into
671 * performing these actions, unaware, by concealing the intended purpose of the view.
672 * As a remedy, the framework offers a touch filtering mechanism that can be used to
673 * improve the security of views that provide access to sensitive functionality.
674 * </p><p>
675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
676 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
677 * will discard touches that are received whenever the view's window is obscured by
678 * another visible window.  As a result, the view will not receive touches whenever a
679 * toast, dialog or other window appears above the view's window.
680 * </p><p>
681 * For more fine-grained control over security, consider overriding the
682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
684 * </p>
685 *
686 * @attr ref android.R.styleable#View_alpha
687 * @attr ref android.R.styleable#View_background
688 * @attr ref android.R.styleable#View_clickable
689 * @attr ref android.R.styleable#View_contentDescription
690 * @attr ref android.R.styleable#View_drawingCacheQuality
691 * @attr ref android.R.styleable#View_duplicateParentState
692 * @attr ref android.R.styleable#View_id
693 * @attr ref android.R.styleable#View_requiresFadingEdge
694 * @attr ref android.R.styleable#View_fadeScrollbars
695 * @attr ref android.R.styleable#View_fadingEdgeLength
696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
697 * @attr ref android.R.styleable#View_fitsSystemWindows
698 * @attr ref android.R.styleable#View_isScrollContainer
699 * @attr ref android.R.styleable#View_focusable
700 * @attr ref android.R.styleable#View_focusableInTouchMode
701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
702 * @attr ref android.R.styleable#View_keepScreenOn
703 * @attr ref android.R.styleable#View_layerType
704 * @attr ref android.R.styleable#View_layoutDirection
705 * @attr ref android.R.styleable#View_longClickable
706 * @attr ref android.R.styleable#View_minHeight
707 * @attr ref android.R.styleable#View_minWidth
708 * @attr ref android.R.styleable#View_nextFocusDown
709 * @attr ref android.R.styleable#View_nextFocusLeft
710 * @attr ref android.R.styleable#View_nextFocusRight
711 * @attr ref android.R.styleable#View_nextFocusUp
712 * @attr ref android.R.styleable#View_onClick
713 * @attr ref android.R.styleable#View_padding
714 * @attr ref android.R.styleable#View_paddingBottom
715 * @attr ref android.R.styleable#View_paddingLeft
716 * @attr ref android.R.styleable#View_paddingRight
717 * @attr ref android.R.styleable#View_paddingTop
718 * @attr ref android.R.styleable#View_paddingStart
719 * @attr ref android.R.styleable#View_paddingEnd
720 * @attr ref android.R.styleable#View_saveEnabled
721 * @attr ref android.R.styleable#View_rotation
722 * @attr ref android.R.styleable#View_rotationX
723 * @attr ref android.R.styleable#View_rotationY
724 * @attr ref android.R.styleable#View_scaleX
725 * @attr ref android.R.styleable#View_scaleY
726 * @attr ref android.R.styleable#View_scrollX
727 * @attr ref android.R.styleable#View_scrollY
728 * @attr ref android.R.styleable#View_scrollbarSize
729 * @attr ref android.R.styleable#View_scrollbarStyle
730 * @attr ref android.R.styleable#View_scrollbars
731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
732 * @attr ref android.R.styleable#View_scrollbarFadeDuration
733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
735 * @attr ref android.R.styleable#View_scrollbarThumbVertical
736 * @attr ref android.R.styleable#View_scrollbarTrackVertical
737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
739 * @attr ref android.R.styleable#View_stateListAnimator
740 * @attr ref android.R.styleable#View_transitionName
741 * @attr ref android.R.styleable#View_soundEffectsEnabled
742 * @attr ref android.R.styleable#View_tag
743 * @attr ref android.R.styleable#View_textAlignment
744 * @attr ref android.R.styleable#View_textDirection
745 * @attr ref android.R.styleable#View_transformPivotX
746 * @attr ref android.R.styleable#View_transformPivotY
747 * @attr ref android.R.styleable#View_translationX
748 * @attr ref android.R.styleable#View_translationY
749 * @attr ref android.R.styleable#View_translationZ
750 * @attr ref android.R.styleable#View_visibility
751 * @attr ref android.R.styleable#View_theme
752 *
753 * @see android.view.ViewGroup
754 */
755@UiThread
756public class View implements Drawable.Callback, KeyEvent.Callback,
757        AccessibilityEventSource {
758    private static final boolean DBG = false;
759
760    /**
761     * The logging tag used by this class with android.util.Log.
762     */
763    protected static final String VIEW_LOG_TAG = "View";
764
765    /**
766     * When set to true, apps will draw debugging information about their layouts.
767     *
768     * @hide
769     */
770    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
771
772    /**
773     * When set to true, this view will save its attribute data.
774     *
775     * @hide
776     */
777    public static boolean mDebugViewAttributes = false;
778
779    /**
780     * Used to mark a View that has no ID.
781     */
782    public static final int NO_ID = -1;
783
784    /**
785     * Signals that compatibility booleans have been initialized according to
786     * target SDK versions.
787     */
788    private static boolean sCompatibilityDone = false;
789
790    /**
791     * Use the old (broken) way of building MeasureSpecs.
792     */
793    private static boolean sUseBrokenMakeMeasureSpec = false;
794
795    /**
796     * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED
797     */
798    static boolean sUseZeroUnspecifiedMeasureSpec = false;
799
800    /**
801     * Ignore any optimizations using the measure cache.
802     */
803    private static boolean sIgnoreMeasureCache = false;
804
805    /**
806     * Ignore an optimization that skips unnecessary EXACTLY layout passes.
807     */
808    private static boolean sAlwaysRemeasureExactly = false;
809
810    /**
811     * Relax constraints around whether setLayoutParams() must be called after
812     * modifying the layout params.
813     */
814    private static boolean sLayoutParamsAlwaysChanged = false;
815
816    /**
817     * Allow setForeground/setBackground to be called (and ignored) on a textureview,
818     * without throwing
819     */
820    static boolean sTextureViewIgnoresDrawableSetters = false;
821
822    /**
823     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
824     * calling setFlags.
825     */
826    private static final int NOT_FOCUSABLE = 0x00000000;
827
828    /**
829     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
830     * setFlags.
831     */
832    private static final int FOCUSABLE = 0x00000001;
833
834    /**
835     * Mask for use with setFlags indicating bits used for focus.
836     */
837    private static final int FOCUSABLE_MASK = 0x00000001;
838
839    /**
840     * This view will adjust its padding to fit sytem windows (e.g. status bar)
841     */
842    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
843
844    /** @hide */
845    @IntDef({VISIBLE, INVISIBLE, GONE})
846    @Retention(RetentionPolicy.SOURCE)
847    public @interface Visibility {}
848
849    /**
850     * This view is visible.
851     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
852     * android:visibility}.
853     */
854    public static final int VISIBLE = 0x00000000;
855
856    /**
857     * This view is invisible, but it still takes up space for layout purposes.
858     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
859     * android:visibility}.
860     */
861    public static final int INVISIBLE = 0x00000004;
862
863    /**
864     * This view is invisible, and it doesn't take any space for layout
865     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
866     * android:visibility}.
867     */
868    public static final int GONE = 0x00000008;
869
870    /**
871     * Mask for use with setFlags indicating bits used for visibility.
872     * {@hide}
873     */
874    static final int VISIBILITY_MASK = 0x0000000C;
875
876    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
877
878    /**
879     * This view is enabled. Interpretation varies by subclass.
880     * Use with ENABLED_MASK when calling setFlags.
881     * {@hide}
882     */
883    static final int ENABLED = 0x00000000;
884
885    /**
886     * This view is disabled. Interpretation varies by subclass.
887     * Use with ENABLED_MASK when calling setFlags.
888     * {@hide}
889     */
890    static final int DISABLED = 0x00000020;
891
892   /**
893    * Mask for use with setFlags indicating bits used for indicating whether
894    * this view is enabled
895    * {@hide}
896    */
897    static final int ENABLED_MASK = 0x00000020;
898
899    /**
900     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
901     * called and further optimizations will be performed. It is okay to have
902     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
903     * {@hide}
904     */
905    static final int WILL_NOT_DRAW = 0x00000080;
906
907    /**
908     * Mask for use with setFlags indicating bits used for indicating whether
909     * this view is will draw
910     * {@hide}
911     */
912    static final int DRAW_MASK = 0x00000080;
913
914    /**
915     * <p>This view doesn't show scrollbars.</p>
916     * {@hide}
917     */
918    static final int SCROLLBARS_NONE = 0x00000000;
919
920    /**
921     * <p>This view shows horizontal scrollbars.</p>
922     * {@hide}
923     */
924    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
925
926    /**
927     * <p>This view shows vertical scrollbars.</p>
928     * {@hide}
929     */
930    static final int SCROLLBARS_VERTICAL = 0x00000200;
931
932    /**
933     * <p>Mask for use with setFlags indicating bits used for indicating which
934     * scrollbars are enabled.</p>
935     * {@hide}
936     */
937    static final int SCROLLBARS_MASK = 0x00000300;
938
939    /**
940     * Indicates that the view should filter touches when its window is obscured.
941     * Refer to the class comments for more information about this security feature.
942     * {@hide}
943     */
944    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
945
946    /**
947     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
948     * that they are optional and should be skipped if the window has
949     * requested system UI flags that ignore those insets for layout.
950     */
951    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
952
953    /**
954     * <p>This view doesn't show fading edges.</p>
955     * {@hide}
956     */
957    static final int FADING_EDGE_NONE = 0x00000000;
958
959    /**
960     * <p>This view shows horizontal fading edges.</p>
961     * {@hide}
962     */
963    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
964
965    /**
966     * <p>This view shows vertical fading edges.</p>
967     * {@hide}
968     */
969    static final int FADING_EDGE_VERTICAL = 0x00002000;
970
971    /**
972     * <p>Mask for use with setFlags indicating bits used for indicating which
973     * fading edges are enabled.</p>
974     * {@hide}
975     */
976    static final int FADING_EDGE_MASK = 0x00003000;
977
978    /**
979     * <p>Indicates this view can be clicked. When clickable, a View reacts
980     * to clicks by notifying the OnClickListener.<p>
981     * {@hide}
982     */
983    static final int CLICKABLE = 0x00004000;
984
985    /**
986     * <p>Indicates this view is caching its drawing into a bitmap.</p>
987     * {@hide}
988     */
989    static final int DRAWING_CACHE_ENABLED = 0x00008000;
990
991    /**
992     * <p>Indicates that no icicle should be saved for this view.<p>
993     * {@hide}
994     */
995    static final int SAVE_DISABLED = 0x000010000;
996
997    /**
998     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
999     * property.</p>
1000     * {@hide}
1001     */
1002    static final int SAVE_DISABLED_MASK = 0x000010000;
1003
1004    /**
1005     * <p>Indicates that no drawing cache should ever be created for this view.<p>
1006     * {@hide}
1007     */
1008    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
1009
1010    /**
1011     * <p>Indicates this view can take / keep focus when int touch mode.</p>
1012     * {@hide}
1013     */
1014    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
1015
1016    /** @hide */
1017    @Retention(RetentionPolicy.SOURCE)
1018    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
1019    public @interface DrawingCacheQuality {}
1020
1021    /**
1022     * <p>Enables low quality mode for the drawing cache.</p>
1023     */
1024    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
1025
1026    /**
1027     * <p>Enables high quality mode for the drawing cache.</p>
1028     */
1029    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
1030
1031    /**
1032     * <p>Enables automatic quality mode for the drawing cache.</p>
1033     */
1034    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
1035
1036    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
1037            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
1038    };
1039
1040    /**
1041     * <p>Mask for use with setFlags indicating bits used for the cache
1042     * quality property.</p>
1043     * {@hide}
1044     */
1045    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
1046
1047    /**
1048     * <p>
1049     * Indicates this view can be long clicked. When long clickable, a View
1050     * reacts to long clicks by notifying the OnLongClickListener or showing a
1051     * context menu.
1052     * </p>
1053     * {@hide}
1054     */
1055    static final int LONG_CLICKABLE = 0x00200000;
1056
1057    /**
1058     * <p>Indicates that this view gets its drawable states from its direct parent
1059     * and ignores its original internal states.</p>
1060     *
1061     * @hide
1062     */
1063    static final int DUPLICATE_PARENT_STATE = 0x00400000;
1064
1065    /**
1066     * <p>
1067     * Indicates this view can be context clicked. When context clickable, a View reacts to a
1068     * context click (e.g. a primary stylus button press or right mouse click) by notifying the
1069     * OnContextClickListener.
1070     * </p>
1071     * {@hide}
1072     */
1073    static final int CONTEXT_CLICKABLE = 0x00800000;
1074
1075
1076    /** @hide */
1077    @IntDef({
1078        SCROLLBARS_INSIDE_OVERLAY,
1079        SCROLLBARS_INSIDE_INSET,
1080        SCROLLBARS_OUTSIDE_OVERLAY,
1081        SCROLLBARS_OUTSIDE_INSET
1082    })
1083    @Retention(RetentionPolicy.SOURCE)
1084    public @interface ScrollBarStyle {}
1085
1086    /**
1087     * The scrollbar style to display the scrollbars inside the content area,
1088     * without increasing the padding. The scrollbars will be overlaid with
1089     * translucency on the view's content.
1090     */
1091    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1092
1093    /**
1094     * The scrollbar style to display the scrollbars inside the padded area,
1095     * increasing the padding of the view. The scrollbars will not overlap the
1096     * content area of the view.
1097     */
1098    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1099
1100    /**
1101     * The scrollbar style to display the scrollbars at the edge of the view,
1102     * without increasing the padding. The scrollbars will be overlaid with
1103     * translucency.
1104     */
1105    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1106
1107    /**
1108     * The scrollbar style to display the scrollbars at the edge of the view,
1109     * increasing the padding of the view. The scrollbars will only overlap the
1110     * background, if any.
1111     */
1112    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1113
1114    /**
1115     * Mask to check if the scrollbar style is overlay or inset.
1116     * {@hide}
1117     */
1118    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1119
1120    /**
1121     * Mask to check if the scrollbar style is inside or outside.
1122     * {@hide}
1123     */
1124    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1125
1126    /**
1127     * Mask for scrollbar style.
1128     * {@hide}
1129     */
1130    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1131
1132    /**
1133     * View flag indicating that the screen should remain on while the
1134     * window containing this view is visible to the user.  This effectively
1135     * takes care of automatically setting the WindowManager's
1136     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1137     */
1138    public static final int KEEP_SCREEN_ON = 0x04000000;
1139
1140    /**
1141     * View flag indicating whether this view should have sound effects enabled
1142     * for events such as clicking and touching.
1143     */
1144    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1145
1146    /**
1147     * View flag indicating whether this view should have haptic feedback
1148     * enabled for events such as long presses.
1149     */
1150    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1151
1152    /**
1153     * <p>Indicates that the view hierarchy should stop saving state when
1154     * it reaches this view.  If state saving is initiated immediately at
1155     * the view, it will be allowed.
1156     * {@hide}
1157     */
1158    static final int PARENT_SAVE_DISABLED = 0x20000000;
1159
1160    /**
1161     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1162     * {@hide}
1163     */
1164    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1165
1166    /** @hide */
1167    @IntDef(flag = true,
1168            value = {
1169                FOCUSABLES_ALL,
1170                FOCUSABLES_TOUCH_MODE
1171            })
1172    @Retention(RetentionPolicy.SOURCE)
1173    public @interface FocusableMode {}
1174
1175    /**
1176     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1177     * should add all focusable Views regardless if they are focusable in touch mode.
1178     */
1179    public static final int FOCUSABLES_ALL = 0x00000000;
1180
1181    /**
1182     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1183     * should add only Views focusable in touch mode.
1184     */
1185    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1186
1187    /** @hide */
1188    @IntDef({
1189            FOCUS_BACKWARD,
1190            FOCUS_FORWARD,
1191            FOCUS_LEFT,
1192            FOCUS_UP,
1193            FOCUS_RIGHT,
1194            FOCUS_DOWN
1195    })
1196    @Retention(RetentionPolicy.SOURCE)
1197    public @interface FocusDirection {}
1198
1199    /** @hide */
1200    @IntDef({
1201            FOCUS_LEFT,
1202            FOCUS_UP,
1203            FOCUS_RIGHT,
1204            FOCUS_DOWN
1205    })
1206    @Retention(RetentionPolicy.SOURCE)
1207    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1208
1209    /**
1210     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1211     * item.
1212     */
1213    public static final int FOCUS_BACKWARD = 0x00000001;
1214
1215    /**
1216     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1217     * item.
1218     */
1219    public static final int FOCUS_FORWARD = 0x00000002;
1220
1221    /**
1222     * Use with {@link #focusSearch(int)}. Move focus to the left.
1223     */
1224    public static final int FOCUS_LEFT = 0x00000011;
1225
1226    /**
1227     * Use with {@link #focusSearch(int)}. Move focus up.
1228     */
1229    public static final int FOCUS_UP = 0x00000021;
1230
1231    /**
1232     * Use with {@link #focusSearch(int)}. Move focus to the right.
1233     */
1234    public static final int FOCUS_RIGHT = 0x00000042;
1235
1236    /**
1237     * Use with {@link #focusSearch(int)}. Move focus down.
1238     */
1239    public static final int FOCUS_DOWN = 0x00000082;
1240
1241    /**
1242     * Bits of {@link #getMeasuredWidthAndState()} and
1243     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1244     */
1245    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1246
1247    /**
1248     * Bits of {@link #getMeasuredWidthAndState()} and
1249     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1250     */
1251    public static final int MEASURED_STATE_MASK = 0xff000000;
1252
1253    /**
1254     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1255     * for functions that combine both width and height into a single int,
1256     * such as {@link #getMeasuredState()} and the childState argument of
1257     * {@link #resolveSizeAndState(int, int, int)}.
1258     */
1259    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1260
1261    /**
1262     * Bit of {@link #getMeasuredWidthAndState()} and
1263     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1264     * is smaller that the space the view would like to have.
1265     */
1266    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1267
1268    /**
1269     * Base View state sets
1270     */
1271    // Singles
1272    /**
1273     * Indicates the view has no states set. States are used with
1274     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1275     * view depending on its state.
1276     *
1277     * @see android.graphics.drawable.Drawable
1278     * @see #getDrawableState()
1279     */
1280    protected static final int[] EMPTY_STATE_SET;
1281    /**
1282     * Indicates the view is enabled. States are used with
1283     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1284     * view depending on its state.
1285     *
1286     * @see android.graphics.drawable.Drawable
1287     * @see #getDrawableState()
1288     */
1289    protected static final int[] ENABLED_STATE_SET;
1290    /**
1291     * Indicates the view is focused. States are used with
1292     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1293     * view depending on its state.
1294     *
1295     * @see android.graphics.drawable.Drawable
1296     * @see #getDrawableState()
1297     */
1298    protected static final int[] FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is selected. States are used with
1301     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1302     * view depending on its state.
1303     *
1304     * @see android.graphics.drawable.Drawable
1305     * @see #getDrawableState()
1306     */
1307    protected static final int[] SELECTED_STATE_SET;
1308    /**
1309     * Indicates the view is pressed. States are used with
1310     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1311     * view depending on its state.
1312     *
1313     * @see android.graphics.drawable.Drawable
1314     * @see #getDrawableState()
1315     */
1316    protected static final int[] PRESSED_STATE_SET;
1317    /**
1318     * Indicates the view's window has focus. States are used with
1319     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1320     * view depending on its state.
1321     *
1322     * @see android.graphics.drawable.Drawable
1323     * @see #getDrawableState()
1324     */
1325    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1326    // Doubles
1327    /**
1328     * Indicates the view is enabled and has the focus.
1329     *
1330     * @see #ENABLED_STATE_SET
1331     * @see #FOCUSED_STATE_SET
1332     */
1333    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1334    /**
1335     * Indicates the view is enabled and selected.
1336     *
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     */
1340    protected static final int[] ENABLED_SELECTED_STATE_SET;
1341    /**
1342     * Indicates the view is enabled and that its window has focus.
1343     *
1344     * @see #ENABLED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1348    /**
1349     * Indicates the view is focused and selected.
1350     *
1351     * @see #FOCUSED_STATE_SET
1352     * @see #SELECTED_STATE_SET
1353     */
1354    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1355    /**
1356     * Indicates the view has the focus and that its window has the focus.
1357     *
1358     * @see #FOCUSED_STATE_SET
1359     * @see #WINDOW_FOCUSED_STATE_SET
1360     */
1361    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1362    /**
1363     * Indicates the view is selected and that its window has the focus.
1364     *
1365     * @see #SELECTED_STATE_SET
1366     * @see #WINDOW_FOCUSED_STATE_SET
1367     */
1368    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1369    // Triples
1370    /**
1371     * Indicates the view is enabled, focused and selected.
1372     *
1373     * @see #ENABLED_STATE_SET
1374     * @see #FOCUSED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     */
1377    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1378    /**
1379     * Indicates the view is enabled, focused and its window has the focus.
1380     *
1381     * @see #ENABLED_STATE_SET
1382     * @see #FOCUSED_STATE_SET
1383     * @see #WINDOW_FOCUSED_STATE_SET
1384     */
1385    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1386    /**
1387     * Indicates the view is enabled, selected and its window has the focus.
1388     *
1389     * @see #ENABLED_STATE_SET
1390     * @see #SELECTED_STATE_SET
1391     * @see #WINDOW_FOCUSED_STATE_SET
1392     */
1393    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1394    /**
1395     * Indicates the view is focused, selected and its window has the focus.
1396     *
1397     * @see #FOCUSED_STATE_SET
1398     * @see #SELECTED_STATE_SET
1399     * @see #WINDOW_FOCUSED_STATE_SET
1400     */
1401    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1402    /**
1403     * Indicates the view is enabled, focused, selected and its window
1404     * has the focus.
1405     *
1406     * @see #ENABLED_STATE_SET
1407     * @see #FOCUSED_STATE_SET
1408     * @see #SELECTED_STATE_SET
1409     * @see #WINDOW_FOCUSED_STATE_SET
1410     */
1411    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1412    /**
1413     * Indicates the view is pressed and its window has the focus.
1414     *
1415     * @see #PRESSED_STATE_SET
1416     * @see #WINDOW_FOCUSED_STATE_SET
1417     */
1418    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1419    /**
1420     * Indicates the view is pressed and selected.
1421     *
1422     * @see #PRESSED_STATE_SET
1423     * @see #SELECTED_STATE_SET
1424     */
1425    protected static final int[] PRESSED_SELECTED_STATE_SET;
1426    /**
1427     * Indicates the view is pressed, selected and its window has the focus.
1428     *
1429     * @see #PRESSED_STATE_SET
1430     * @see #SELECTED_STATE_SET
1431     * @see #WINDOW_FOCUSED_STATE_SET
1432     */
1433    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1434    /**
1435     * Indicates the view is pressed and focused.
1436     *
1437     * @see #PRESSED_STATE_SET
1438     * @see #FOCUSED_STATE_SET
1439     */
1440    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1441    /**
1442     * Indicates the view is pressed, focused and its window has the focus.
1443     *
1444     * @see #PRESSED_STATE_SET
1445     * @see #FOCUSED_STATE_SET
1446     * @see #WINDOW_FOCUSED_STATE_SET
1447     */
1448    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1449    /**
1450     * Indicates the view is pressed, focused and selected.
1451     *
1452     * @see #PRESSED_STATE_SET
1453     * @see #SELECTED_STATE_SET
1454     * @see #FOCUSED_STATE_SET
1455     */
1456    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1457    /**
1458     * Indicates the view is pressed, focused, selected and its window has the focus.
1459     *
1460     * @see #PRESSED_STATE_SET
1461     * @see #FOCUSED_STATE_SET
1462     * @see #SELECTED_STATE_SET
1463     * @see #WINDOW_FOCUSED_STATE_SET
1464     */
1465    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1466    /**
1467     * Indicates the view is pressed and enabled.
1468     *
1469     * @see #PRESSED_STATE_SET
1470     * @see #ENABLED_STATE_SET
1471     */
1472    protected static final int[] PRESSED_ENABLED_STATE_SET;
1473    /**
1474     * Indicates the view is pressed, enabled and its window has the focus.
1475     *
1476     * @see #PRESSED_STATE_SET
1477     * @see #ENABLED_STATE_SET
1478     * @see #WINDOW_FOCUSED_STATE_SET
1479     */
1480    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1481    /**
1482     * Indicates the view is pressed, enabled and selected.
1483     *
1484     * @see #PRESSED_STATE_SET
1485     * @see #ENABLED_STATE_SET
1486     * @see #SELECTED_STATE_SET
1487     */
1488    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1489    /**
1490     * Indicates the view is pressed, enabled, selected and its window has the
1491     * focus.
1492     *
1493     * @see #PRESSED_STATE_SET
1494     * @see #ENABLED_STATE_SET
1495     * @see #SELECTED_STATE_SET
1496     * @see #WINDOW_FOCUSED_STATE_SET
1497     */
1498    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1499    /**
1500     * Indicates the view is pressed, enabled and focused.
1501     *
1502     * @see #PRESSED_STATE_SET
1503     * @see #ENABLED_STATE_SET
1504     * @see #FOCUSED_STATE_SET
1505     */
1506    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1507    /**
1508     * Indicates the view is pressed, enabled, focused and its window has the
1509     * focus.
1510     *
1511     * @see #PRESSED_STATE_SET
1512     * @see #ENABLED_STATE_SET
1513     * @see #FOCUSED_STATE_SET
1514     * @see #WINDOW_FOCUSED_STATE_SET
1515     */
1516    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1517    /**
1518     * Indicates the view is pressed, enabled, focused and selected.
1519     *
1520     * @see #PRESSED_STATE_SET
1521     * @see #ENABLED_STATE_SET
1522     * @see #SELECTED_STATE_SET
1523     * @see #FOCUSED_STATE_SET
1524     */
1525    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1526    /**
1527     * Indicates the view is pressed, enabled, focused, selected and its window
1528     * has the focus.
1529     *
1530     * @see #PRESSED_STATE_SET
1531     * @see #ENABLED_STATE_SET
1532     * @see #SELECTED_STATE_SET
1533     * @see #FOCUSED_STATE_SET
1534     * @see #WINDOW_FOCUSED_STATE_SET
1535     */
1536    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1537
1538    static {
1539        EMPTY_STATE_SET = StateSet.get(0);
1540
1541        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1542
1543        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1544        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1545                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1546
1547        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1548        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1549                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1550        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1551                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1552        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1553                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1554                        | StateSet.VIEW_STATE_FOCUSED);
1555
1556        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1557        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1558                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1559        ENABLED_SELECTED_STATE_SET = StateSet.get(
1560                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1561        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1562                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1563                        | StateSet.VIEW_STATE_ENABLED);
1564        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1565                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1566        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1567                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1568                        | StateSet.VIEW_STATE_ENABLED);
1569        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1570                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1571                        | StateSet.VIEW_STATE_ENABLED);
1572        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1573                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1574                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1575
1576        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1577        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1578                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1579        PRESSED_SELECTED_STATE_SET = StateSet.get(
1580                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1581        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1582                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1583                        | StateSet.VIEW_STATE_PRESSED);
1584        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1585                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1586        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1587                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1588                        | StateSet.VIEW_STATE_PRESSED);
1589        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1590                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1591                        | StateSet.VIEW_STATE_PRESSED);
1592        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1593                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1594                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1595        PRESSED_ENABLED_STATE_SET = StateSet.get(
1596                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1597        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1598                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1599                        | StateSet.VIEW_STATE_PRESSED);
1600        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1601                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1602                        | StateSet.VIEW_STATE_PRESSED);
1603        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1604                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1605                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1606        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1607                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1608                        | StateSet.VIEW_STATE_PRESSED);
1609        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1610                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1611                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1612        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1613                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1614                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1615        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1616                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1617                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1618                        | StateSet.VIEW_STATE_PRESSED);
1619    }
1620
1621    /**
1622     * Accessibility event types that are dispatched for text population.
1623     */
1624    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1625            AccessibilityEvent.TYPE_VIEW_CLICKED
1626            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1627            | AccessibilityEvent.TYPE_VIEW_SELECTED
1628            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1629            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1630            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1631            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1632            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1633            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1634            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1635            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1636
1637    /**
1638     * Temporary Rect currently for use in setBackground().  This will probably
1639     * be extended in the future to hold our own class with more than just
1640     * a Rect. :)
1641     */
1642    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1643
1644    /**
1645     * Map used to store views' tags.
1646     */
1647    private SparseArray<Object> mKeyedTags;
1648
1649    /**
1650     * The next available accessibility id.
1651     */
1652    private static int sNextAccessibilityViewId;
1653
1654    /**
1655     * The animation currently associated with this view.
1656     * @hide
1657     */
1658    protected Animation mCurrentAnimation = null;
1659
1660    /**
1661     * Width as measured during measure pass.
1662     * {@hide}
1663     */
1664    @ViewDebug.ExportedProperty(category = "measurement")
1665    int mMeasuredWidth;
1666
1667    /**
1668     * Height as measured during measure pass.
1669     * {@hide}
1670     */
1671    @ViewDebug.ExportedProperty(category = "measurement")
1672    int mMeasuredHeight;
1673
1674    /**
1675     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1676     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1677     * its display list. This flag, used only when hw accelerated, allows us to clear the
1678     * flag while retaining this information until it's needed (at getDisplayList() time and
1679     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1680     *
1681     * {@hide}
1682     */
1683    boolean mRecreateDisplayList = false;
1684
1685    /**
1686     * The view's identifier.
1687     * {@hide}
1688     *
1689     * @see #setId(int)
1690     * @see #getId()
1691     */
1692    @IdRes
1693    @ViewDebug.ExportedProperty(resolveId = true)
1694    int mID = NO_ID;
1695
1696    /**
1697     * The stable ID of this view for accessibility purposes.
1698     */
1699    int mAccessibilityViewId = NO_ID;
1700
1701    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1702
1703    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1704
1705    /**
1706     * The view's tag.
1707     * {@hide}
1708     *
1709     * @see #setTag(Object)
1710     * @see #getTag()
1711     */
1712    protected Object mTag = null;
1713
1714    // for mPrivateFlags:
1715    /** {@hide} */
1716    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1717    /** {@hide} */
1718    static final int PFLAG_FOCUSED                     = 0x00000002;
1719    /** {@hide} */
1720    static final int PFLAG_SELECTED                    = 0x00000004;
1721    /** {@hide} */
1722    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1723    /** {@hide} */
1724    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1725    /** {@hide} */
1726    static final int PFLAG_DRAWN                       = 0x00000020;
1727    /**
1728     * When this flag is set, this view is running an animation on behalf of its
1729     * children and should therefore not cancel invalidate requests, even if they
1730     * lie outside of this view's bounds.
1731     *
1732     * {@hide}
1733     */
1734    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1735    /** {@hide} */
1736    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1737    /** {@hide} */
1738    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1739    /** {@hide} */
1740    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1741    /** {@hide} */
1742    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1743    /** {@hide} */
1744    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1745    /** {@hide} */
1746    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1747
1748    private static final int PFLAG_PRESSED             = 0x00004000;
1749
1750    /** {@hide} */
1751    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1752    /**
1753     * Flag used to indicate that this view should be drawn once more (and only once
1754     * more) after its animation has completed.
1755     * {@hide}
1756     */
1757    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1758
1759    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1760
1761    /**
1762     * Indicates that the View returned true when onSetAlpha() was called and that
1763     * the alpha must be restored.
1764     * {@hide}
1765     */
1766    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1767
1768    /**
1769     * Set by {@link #setScrollContainer(boolean)}.
1770     */
1771    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1772
1773    /**
1774     * Set by {@link #setScrollContainer(boolean)}.
1775     */
1776    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1777
1778    /**
1779     * View flag indicating whether this view was invalidated (fully or partially.)
1780     *
1781     * @hide
1782     */
1783    static final int PFLAG_DIRTY                       = 0x00200000;
1784
1785    /**
1786     * View flag indicating whether this view was invalidated by an opaque
1787     * invalidate request.
1788     *
1789     * @hide
1790     */
1791    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1792
1793    /**
1794     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1795     *
1796     * @hide
1797     */
1798    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1799
1800    /**
1801     * Indicates whether the background is opaque.
1802     *
1803     * @hide
1804     */
1805    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1806
1807    /**
1808     * Indicates whether the scrollbars are opaque.
1809     *
1810     * @hide
1811     */
1812    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1813
1814    /**
1815     * Indicates whether the view is opaque.
1816     *
1817     * @hide
1818     */
1819    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1820
1821    /**
1822     * Indicates a prepressed state;
1823     * the short time between ACTION_DOWN and recognizing
1824     * a 'real' press. Prepressed is used to recognize quick taps
1825     * even when they are shorter than ViewConfiguration.getTapTimeout().
1826     *
1827     * @hide
1828     */
1829    private static final int PFLAG_PREPRESSED          = 0x02000000;
1830
1831    /**
1832     * Indicates whether the view is temporarily detached.
1833     *
1834     * @hide
1835     */
1836    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1837
1838    /**
1839     * Indicates that we should awaken scroll bars once attached
1840     *
1841     * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged
1842     * during window attachment and it is no longer needed. Feel free to repurpose it.
1843     *
1844     * @hide
1845     */
1846    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1847
1848    /**
1849     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1850     * @hide
1851     */
1852    private static final int PFLAG_HOVERED             = 0x10000000;
1853
1854    /**
1855     * no longer needed, should be reused
1856     */
1857    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1858
1859    /** {@hide} */
1860    static final int PFLAG_ACTIVATED                   = 0x40000000;
1861
1862    /**
1863     * Indicates that this view was specifically invalidated, not just dirtied because some
1864     * child view was invalidated. The flag is used to determine when we need to recreate
1865     * a view's display list (as opposed to just returning a reference to its existing
1866     * display list).
1867     *
1868     * @hide
1869     */
1870    static final int PFLAG_INVALIDATED                 = 0x80000000;
1871
1872    /**
1873     * Masks for mPrivateFlags2, as generated by dumpFlags():
1874     *
1875     * |-------|-------|-------|-------|
1876     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1877     *                                1  PFLAG2_DRAG_HOVERED
1878     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1879     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1880     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1881     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1882     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1883     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1884     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1885     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1886     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1887     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1888     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1889     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1890     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1891     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1892     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1893     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1894     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1895     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1896     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1897     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1898     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1899     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1900     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1901     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1902     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1903     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1904     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1905     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1906     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1907     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1908     *    1                              PFLAG2_PADDING_RESOLVED
1909     *   1                               PFLAG2_DRAWABLE_RESOLVED
1910     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1911     * |-------|-------|-------|-------|
1912     */
1913
1914    /**
1915     * Indicates that this view has reported that it can accept the current drag's content.
1916     * Cleared when the drag operation concludes.
1917     * @hide
1918     */
1919    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1920
1921    /**
1922     * Indicates that this view is currently directly under the drag location in a
1923     * drag-and-drop operation involving content that it can accept.  Cleared when
1924     * the drag exits the view, or when the drag operation concludes.
1925     * @hide
1926     */
1927    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1928
1929    /** @hide */
1930    @IntDef({
1931        LAYOUT_DIRECTION_LTR,
1932        LAYOUT_DIRECTION_RTL,
1933        LAYOUT_DIRECTION_INHERIT,
1934        LAYOUT_DIRECTION_LOCALE
1935    })
1936    @Retention(RetentionPolicy.SOURCE)
1937    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1938    public @interface LayoutDir {}
1939
1940    /** @hide */
1941    @IntDef({
1942        LAYOUT_DIRECTION_LTR,
1943        LAYOUT_DIRECTION_RTL
1944    })
1945    @Retention(RetentionPolicy.SOURCE)
1946    public @interface ResolvedLayoutDir {}
1947
1948    /**
1949     * A flag to indicate that the layout direction of this view has not been defined yet.
1950     * @hide
1951     */
1952    public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED;
1953
1954    /**
1955     * Horizontal layout direction of this view is from Left to Right.
1956     * Use with {@link #setLayoutDirection}.
1957     */
1958    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1959
1960    /**
1961     * Horizontal layout direction of this view is from Right to Left.
1962     * Use with {@link #setLayoutDirection}.
1963     */
1964    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1965
1966    /**
1967     * Horizontal layout direction of this view is inherited from its parent.
1968     * Use with {@link #setLayoutDirection}.
1969     */
1970    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1971
1972    /**
1973     * Horizontal layout direction of this view is from deduced from the default language
1974     * script for the locale. Use with {@link #setLayoutDirection}.
1975     */
1976    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1977
1978    /**
1979     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1980     * @hide
1981     */
1982    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1983
1984    /**
1985     * Mask for use with private flags indicating bits used for horizontal layout direction.
1986     * @hide
1987     */
1988    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1989
1990    /**
1991     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1992     * right-to-left direction.
1993     * @hide
1994     */
1995    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1996
1997    /**
1998     * Indicates whether the view horizontal layout direction has been resolved.
1999     * @hide
2000     */
2001    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2002
2003    /**
2004     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
2005     * @hide
2006     */
2007    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
2008            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
2009
2010    /*
2011     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
2012     * flag value.
2013     * @hide
2014     */
2015    private static final int[] LAYOUT_DIRECTION_FLAGS = {
2016            LAYOUT_DIRECTION_LTR,
2017            LAYOUT_DIRECTION_RTL,
2018            LAYOUT_DIRECTION_INHERIT,
2019            LAYOUT_DIRECTION_LOCALE
2020    };
2021
2022    /**
2023     * Default horizontal layout direction.
2024     */
2025    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
2026
2027    /**
2028     * Default horizontal layout direction.
2029     * @hide
2030     */
2031    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
2032
2033    /**
2034     * Text direction is inherited through {@link ViewGroup}
2035     */
2036    public static final int TEXT_DIRECTION_INHERIT = 0;
2037
2038    /**
2039     * Text direction is using "first strong algorithm". The first strong directional character
2040     * determines the paragraph direction. If there is no strong directional character, the
2041     * paragraph direction is the view's resolved layout direction.
2042     */
2043    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2044
2045    /**
2046     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2047     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2048     * If there are neither, the paragraph direction is the view's resolved layout direction.
2049     */
2050    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2051
2052    /**
2053     * Text direction is forced to LTR.
2054     */
2055    public static final int TEXT_DIRECTION_LTR = 3;
2056
2057    /**
2058     * Text direction is forced to RTL.
2059     */
2060    public static final int TEXT_DIRECTION_RTL = 4;
2061
2062    /**
2063     * Text direction is coming from the system Locale.
2064     */
2065    public static final int TEXT_DIRECTION_LOCALE = 5;
2066
2067    /**
2068     * Text direction is using "first strong algorithm". The first strong directional character
2069     * determines the paragraph direction. If there is no strong directional character, the
2070     * paragraph direction is LTR.
2071     */
2072    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
2073
2074    /**
2075     * Text direction is using "first strong algorithm". The first strong directional character
2076     * determines the paragraph direction. If there is no strong directional character, the
2077     * paragraph direction is RTL.
2078     */
2079    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2080
2081    /**
2082     * Default text direction is inherited
2083     */
2084    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2085
2086    /**
2087     * Default resolved text direction
2088     * @hide
2089     */
2090    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2091
2092    /**
2093     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2094     * @hide
2095     */
2096    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2097
2098    /**
2099     * Mask for use with private flags indicating bits used for text direction.
2100     * @hide
2101     */
2102    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2103            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2104
2105    /**
2106     * Array of text direction flags for mapping attribute "textDirection" to correct
2107     * flag value.
2108     * @hide
2109     */
2110    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2111            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2112            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2113            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2114            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2115            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2116            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2117            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2118            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2119    };
2120
2121    /**
2122     * Indicates whether the view text direction has been resolved.
2123     * @hide
2124     */
2125    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2126            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2127
2128    /**
2129     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2130     * @hide
2131     */
2132    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2133
2134    /**
2135     * Mask for use with private flags indicating bits used for resolved text direction.
2136     * @hide
2137     */
2138    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2139            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2140
2141    /**
2142     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2143     * @hide
2144     */
2145    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2146            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2147
2148    /** @hide */
2149    @IntDef({
2150        TEXT_ALIGNMENT_INHERIT,
2151        TEXT_ALIGNMENT_GRAVITY,
2152        TEXT_ALIGNMENT_CENTER,
2153        TEXT_ALIGNMENT_TEXT_START,
2154        TEXT_ALIGNMENT_TEXT_END,
2155        TEXT_ALIGNMENT_VIEW_START,
2156        TEXT_ALIGNMENT_VIEW_END
2157    })
2158    @Retention(RetentionPolicy.SOURCE)
2159    public @interface TextAlignment {}
2160
2161    /**
2162     * Default text alignment. The text alignment of this View is inherited from its parent.
2163     * Use with {@link #setTextAlignment(int)}
2164     */
2165    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2166
2167    /**
2168     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2169     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2170     *
2171     * Use with {@link #setTextAlignment(int)}
2172     */
2173    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2174
2175    /**
2176     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2177     *
2178     * Use with {@link #setTextAlignment(int)}
2179     */
2180    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2181
2182    /**
2183     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2184     *
2185     * Use with {@link #setTextAlignment(int)}
2186     */
2187    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2188
2189    /**
2190     * Center the paragraph, e.g. ALIGN_CENTER.
2191     *
2192     * Use with {@link #setTextAlignment(int)}
2193     */
2194    public static final int TEXT_ALIGNMENT_CENTER = 4;
2195
2196    /**
2197     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2198     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2199     *
2200     * Use with {@link #setTextAlignment(int)}
2201     */
2202    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2203
2204    /**
2205     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2206     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2207     *
2208     * Use with {@link #setTextAlignment(int)}
2209     */
2210    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2211
2212    /**
2213     * Default text alignment is inherited
2214     */
2215    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2216
2217    /**
2218     * Default resolved text alignment
2219     * @hide
2220     */
2221    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2222
2223    /**
2224      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2225      * @hide
2226      */
2227    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2228
2229    /**
2230      * Mask for use with private flags indicating bits used for text alignment.
2231      * @hide
2232      */
2233    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2234
2235    /**
2236     * Array of text direction flags for mapping attribute "textAlignment" to correct
2237     * flag value.
2238     * @hide
2239     */
2240    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2241            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2242            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2243            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2244            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2245            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2246            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2247            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2248    };
2249
2250    /**
2251     * Indicates whether the view text alignment has been resolved.
2252     * @hide
2253     */
2254    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2255
2256    /**
2257     * Bit shift to get the resolved text alignment.
2258     * @hide
2259     */
2260    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2261
2262    /**
2263     * Mask for use with private flags indicating bits used for text alignment.
2264     * @hide
2265     */
2266    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2267            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2268
2269    /**
2270     * Indicates whether if the view text alignment has been resolved to gravity
2271     */
2272    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2273            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2274
2275    // Accessiblity constants for mPrivateFlags2
2276
2277    /**
2278     * Shift for the bits in {@link #mPrivateFlags2} related to the
2279     * "importantForAccessibility" attribute.
2280     */
2281    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2282
2283    /**
2284     * Automatically determine whether a view is important for accessibility.
2285     */
2286    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2287
2288    /**
2289     * The view is important for accessibility.
2290     */
2291    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2292
2293    /**
2294     * The view is not important for accessibility.
2295     */
2296    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2297
2298    /**
2299     * The view is not important for accessibility, nor are any of its
2300     * descendant views.
2301     */
2302    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2303
2304    /**
2305     * The default whether the view is important for accessibility.
2306     */
2307    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2308
2309    /**
2310     * Mask for obtainig the bits which specify how to determine
2311     * whether a view is important for accessibility.
2312     */
2313    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2314        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2315        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2316        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2317
2318    /**
2319     * Shift for the bits in {@link #mPrivateFlags2} related to the
2320     * "accessibilityLiveRegion" attribute.
2321     */
2322    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2323
2324    /**
2325     * Live region mode specifying that accessibility services should not
2326     * automatically announce changes to this view. This is the default live
2327     * region mode for most views.
2328     * <p>
2329     * Use with {@link #setAccessibilityLiveRegion(int)}.
2330     */
2331    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2332
2333    /**
2334     * Live region mode specifying that accessibility services should announce
2335     * changes to this view.
2336     * <p>
2337     * Use with {@link #setAccessibilityLiveRegion(int)}.
2338     */
2339    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2340
2341    /**
2342     * Live region mode specifying that accessibility services should interrupt
2343     * ongoing speech to immediately announce changes to this view.
2344     * <p>
2345     * Use with {@link #setAccessibilityLiveRegion(int)}.
2346     */
2347    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2348
2349    /**
2350     * The default whether the view is important for accessibility.
2351     */
2352    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2353
2354    /**
2355     * Mask for obtaining the bits which specify a view's accessibility live
2356     * region mode.
2357     */
2358    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2359            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2360            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2361
2362    /**
2363     * Flag indicating whether a view has accessibility focus.
2364     */
2365    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2366
2367    /**
2368     * Flag whether the accessibility state of the subtree rooted at this view changed.
2369     */
2370    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2371
2372    /**
2373     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2374     * is used to check whether later changes to the view's transform should invalidate the
2375     * view to force the quickReject test to run again.
2376     */
2377    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2378
2379    /**
2380     * Flag indicating that start/end padding has been resolved into left/right padding
2381     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2382     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2383     * during measurement. In some special cases this is required such as when an adapter-based
2384     * view measures prospective children without attaching them to a window.
2385     */
2386    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2387
2388    /**
2389     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2390     */
2391    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2392
2393    /**
2394     * Indicates that the view is tracking some sort of transient state
2395     * that the app should not need to be aware of, but that the framework
2396     * should take special care to preserve.
2397     */
2398    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2399
2400    /**
2401     * Group of bits indicating that RTL properties resolution is done.
2402     */
2403    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2404            PFLAG2_TEXT_DIRECTION_RESOLVED |
2405            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2406            PFLAG2_PADDING_RESOLVED |
2407            PFLAG2_DRAWABLE_RESOLVED;
2408
2409    // There are a couple of flags left in mPrivateFlags2
2410
2411    /* End of masks for mPrivateFlags2 */
2412
2413    /**
2414     * Masks for mPrivateFlags3, as generated by dumpFlags():
2415     *
2416     * |-------|-------|-------|-------|
2417     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2418     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2419     *                               1   PFLAG3_IS_LAID_OUT
2420     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2421     *                             1     PFLAG3_CALLED_SUPER
2422     *                            1      PFLAG3_APPLYING_INSETS
2423     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2424     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2425     *                         1         PFLAG3_SCROLL_INDICATOR_TOP
2426     *                        1          PFLAG3_SCROLL_INDICATOR_BOTTOM
2427     *                       1           PFLAG3_SCROLL_INDICATOR_LEFT
2428     *                      1            PFLAG3_SCROLL_INDICATOR_RIGHT
2429     *                     1             PFLAG3_SCROLL_INDICATOR_START
2430     *                    1              PFLAG3_SCROLL_INDICATOR_END
2431     *                   1               PFLAG3_ASSIST_BLOCKED
2432     *                  1                PFLAG3_POINTER_ICON_NULL
2433     *                 1                 PFLAG3_POINTER_ICON_VALUE_START
2434     *           11111111                PFLAG3_POINTER_ICON_MASK
2435     *          1                        PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE
2436     *         1                         PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED
2437     *        1                          PFLAG3_TEMPORARY_DETACH
2438     * |-------|-------|-------|-------|
2439     */
2440
2441    /**
2442     * Flag indicating that view has a transform animation set on it. This is used to track whether
2443     * an animation is cleared between successive frames, in order to tell the associated
2444     * DisplayList to clear its animation matrix.
2445     */
2446    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2447
2448    /**
2449     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2450     * animation is cleared between successive frames, in order to tell the associated
2451     * DisplayList to restore its alpha value.
2452     */
2453    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2454
2455    /**
2456     * Flag indicating that the view has been through at least one layout since it
2457     * was last attached to a window.
2458     */
2459    static final int PFLAG3_IS_LAID_OUT = 0x4;
2460
2461    /**
2462     * Flag indicating that a call to measure() was skipped and should be done
2463     * instead when layout() is invoked.
2464     */
2465    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2466
2467    /**
2468     * Flag indicating that an overridden method correctly called down to
2469     * the superclass implementation as required by the API spec.
2470     */
2471    static final int PFLAG3_CALLED_SUPER = 0x10;
2472
2473    /**
2474     * Flag indicating that we're in the process of applying window insets.
2475     */
2476    static final int PFLAG3_APPLYING_INSETS = 0x20;
2477
2478    /**
2479     * Flag indicating that we're in the process of fitting system windows using the old method.
2480     */
2481    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2482
2483    /**
2484     * Flag indicating that nested scrolling is enabled for this view.
2485     * The view will optionally cooperate with views up its parent chain to allow for
2486     * integrated nested scrolling along the same axis.
2487     */
2488    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2489
2490    /**
2491     * Flag indicating that the bottom scroll indicator should be displayed
2492     * when this view can scroll up.
2493     */
2494    static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100;
2495
2496    /**
2497     * Flag indicating that the bottom scroll indicator should be displayed
2498     * when this view can scroll down.
2499     */
2500    static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200;
2501
2502    /**
2503     * Flag indicating that the left scroll indicator should be displayed
2504     * when this view can scroll left.
2505     */
2506    static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400;
2507
2508    /**
2509     * Flag indicating that the right scroll indicator should be displayed
2510     * when this view can scroll right.
2511     */
2512    static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800;
2513
2514    /**
2515     * Flag indicating that the start scroll indicator should be displayed
2516     * when this view can scroll in the start direction.
2517     */
2518    static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000;
2519
2520    /**
2521     * Flag indicating that the end scroll indicator should be displayed
2522     * when this view can scroll in the end direction.
2523     */
2524    static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000;
2525
2526    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2527
2528    static final int SCROLL_INDICATORS_NONE = 0x0000;
2529
2530    /**
2531     * Mask for use with setFlags indicating bits used for indicating which
2532     * scroll indicators are enabled.
2533     */
2534    static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP
2535            | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT
2536            | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START
2537            | PFLAG3_SCROLL_INDICATOR_END;
2538
2539    /**
2540     * Left-shift required to translate between public scroll indicator flags
2541     * and internal PFLAGS3 flags. When used as a right-shift, translates
2542     * PFLAGS3 flags to public flags.
2543     */
2544    static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8;
2545
2546    /** @hide */
2547    @Retention(RetentionPolicy.SOURCE)
2548    @IntDef(flag = true,
2549            value = {
2550                    SCROLL_INDICATOR_TOP,
2551                    SCROLL_INDICATOR_BOTTOM,
2552                    SCROLL_INDICATOR_LEFT,
2553                    SCROLL_INDICATOR_RIGHT,
2554                    SCROLL_INDICATOR_START,
2555                    SCROLL_INDICATOR_END,
2556            })
2557    public @interface ScrollIndicators {}
2558
2559    /**
2560     * Scroll indicator direction for the top edge of the view.
2561     *
2562     * @see #setScrollIndicators(int)
2563     * @see #setScrollIndicators(int, int)
2564     * @see #getScrollIndicators()
2565     */
2566    public static final int SCROLL_INDICATOR_TOP =
2567            PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2568
2569    /**
2570     * Scroll indicator direction for the bottom edge of the view.
2571     *
2572     * @see #setScrollIndicators(int)
2573     * @see #setScrollIndicators(int, int)
2574     * @see #getScrollIndicators()
2575     */
2576    public static final int SCROLL_INDICATOR_BOTTOM =
2577            PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2578
2579    /**
2580     * Scroll indicator direction for the left edge of the view.
2581     *
2582     * @see #setScrollIndicators(int)
2583     * @see #setScrollIndicators(int, int)
2584     * @see #getScrollIndicators()
2585     */
2586    public static final int SCROLL_INDICATOR_LEFT =
2587            PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2588
2589    /**
2590     * Scroll indicator direction for the right edge of the view.
2591     *
2592     * @see #setScrollIndicators(int)
2593     * @see #setScrollIndicators(int, int)
2594     * @see #getScrollIndicators()
2595     */
2596    public static final int SCROLL_INDICATOR_RIGHT =
2597            PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2598
2599    /**
2600     * Scroll indicator direction for the starting edge of the view.
2601     * <p>
2602     * Resolved according to the view's layout direction, see
2603     * {@link #getLayoutDirection()} for more information.
2604     *
2605     * @see #setScrollIndicators(int)
2606     * @see #setScrollIndicators(int, int)
2607     * @see #getScrollIndicators()
2608     */
2609    public static final int SCROLL_INDICATOR_START =
2610            PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2611
2612    /**
2613     * Scroll indicator direction for the ending edge of the view.
2614     * <p>
2615     * Resolved according to the view's layout direction, see
2616     * {@link #getLayoutDirection()} for more information.
2617     *
2618     * @see #setScrollIndicators(int)
2619     * @see #setScrollIndicators(int, int)
2620     * @see #getScrollIndicators()
2621     */
2622    public static final int SCROLL_INDICATOR_END =
2623            PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
2624
2625    /**
2626     * <p>Indicates that we are allowing {@link ViewStructure} to traverse
2627     * into this view.<p>
2628     */
2629    static final int PFLAG3_ASSIST_BLOCKED = 0x4000;
2630
2631    /**
2632     * The mask for use with private flags indicating bits used for pointer icon shapes.
2633     */
2634    static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000;
2635
2636    /**
2637     * Left-shift used for pointer icon shape values in private flags.
2638     */
2639    static final int PFLAG3_POINTER_ICON_LSHIFT = 15;
2640
2641    /**
2642     * Value indicating no specific pointer icons.
2643     */
2644    private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT;
2645
2646    /**
2647     * Value indicating {@link PointerIcon.TYPE_NULL}.
2648     */
2649    private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT;
2650
2651    /**
2652     * The base value for other pointer icon shapes.
2653     */
2654    private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT;
2655
2656    /**
2657     * Whether this view has rendered elements that overlap (see {@link
2658     * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and
2659     * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when
2660     * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is
2661     * determined by whatever {@link #hasOverlappingRendering()} returns.
2662     */
2663    private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000;
2664
2665    /**
2666     * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value
2667     * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid.
2668     */
2669    private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000;
2670
2671    /**
2672     * Flag indicating that the view is temporarily detached from the parent view.
2673     *
2674     * @see #onStartTemporaryDetach()
2675     * @see #onFinishTemporaryDetach()
2676     */
2677    static final int PFLAG3_TEMPORARY_DETACH = 0x2000000;
2678
2679    /* End of masks for mPrivateFlags3 */
2680
2681    /**
2682     * Always allow a user to over-scroll this view, provided it is a
2683     * view that can scroll.
2684     *
2685     * @see #getOverScrollMode()
2686     * @see #setOverScrollMode(int)
2687     */
2688    public static final int OVER_SCROLL_ALWAYS = 0;
2689
2690    /**
2691     * Allow a user to over-scroll this view only if the content is large
2692     * enough to meaningfully scroll, provided it is a view that can scroll.
2693     *
2694     * @see #getOverScrollMode()
2695     * @see #setOverScrollMode(int)
2696     */
2697    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2698
2699    /**
2700     * Never allow a user to over-scroll this view.
2701     *
2702     * @see #getOverScrollMode()
2703     * @see #setOverScrollMode(int)
2704     */
2705    public static final int OVER_SCROLL_NEVER = 2;
2706
2707    /**
2708     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2709     * requested the system UI (status bar) to be visible (the default).
2710     *
2711     * @see #setSystemUiVisibility(int)
2712     */
2713    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2714
2715    /**
2716     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2717     * system UI to enter an unobtrusive "low profile" mode.
2718     *
2719     * <p>This is for use in games, book readers, video players, or any other
2720     * "immersive" application where the usual system chrome is deemed too distracting.
2721     *
2722     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2723     *
2724     * @see #setSystemUiVisibility(int)
2725     */
2726    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2727
2728    /**
2729     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2730     * system navigation be temporarily hidden.
2731     *
2732     * <p>This is an even less obtrusive state than that called for by
2733     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2734     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2735     * those to disappear. This is useful (in conjunction with the
2736     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2737     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2738     * window flags) for displaying content using every last pixel on the display.
2739     *
2740     * <p>There is a limitation: because navigation controls are so important, the least user
2741     * interaction will cause them to reappear immediately.  When this happens, both
2742     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2743     * so that both elements reappear at the same time.
2744     *
2745     * @see #setSystemUiVisibility(int)
2746     */
2747    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2748
2749    /**
2750     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2751     * into the normal fullscreen mode so that its content can take over the screen
2752     * while still allowing the user to interact with the application.
2753     *
2754     * <p>This has the same visual effect as
2755     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2756     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2757     * meaning that non-critical screen decorations (such as the status bar) will be
2758     * hidden while the user is in the View's window, focusing the experience on
2759     * that content.  Unlike the window flag, if you are using ActionBar in
2760     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2761     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2762     * hide the action bar.
2763     *
2764     * <p>This approach to going fullscreen is best used over the window flag when
2765     * it is a transient state -- that is, the application does this at certain
2766     * points in its user interaction where it wants to allow the user to focus
2767     * on content, but not as a continuous state.  For situations where the application
2768     * would like to simply stay full screen the entire time (such as a game that
2769     * wants to take over the screen), the
2770     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2771     * is usually a better approach.  The state set here will be removed by the system
2772     * in various situations (such as the user moving to another application) like
2773     * the other system UI states.
2774     *
2775     * <p>When using this flag, the application should provide some easy facility
2776     * for the user to go out of it.  A common example would be in an e-book
2777     * reader, where tapping on the screen brings back whatever screen and UI
2778     * decorations that had been hidden while the user was immersed in reading
2779     * the book.
2780     *
2781     * @see #setSystemUiVisibility(int)
2782     */
2783    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2784
2785    /**
2786     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2787     * flags, we would like a stable view of the content insets given to
2788     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2789     * will always represent the worst case that the application can expect
2790     * as a continuous state.  In the stock Android UI this is the space for
2791     * the system bar, nav bar, and status bar, but not more transient elements
2792     * such as an input method.
2793     *
2794     * The stable layout your UI sees is based on the system UI modes you can
2795     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2796     * then you will get a stable layout for changes of the
2797     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2798     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2799     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2800     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2801     * with a stable layout.  (Note that you should avoid using
2802     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2803     *
2804     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2805     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2806     * then a hidden status bar will be considered a "stable" state for purposes
2807     * here.  This allows your UI to continually hide the status bar, while still
2808     * using the system UI flags to hide the action bar while still retaining
2809     * a stable layout.  Note that changing the window fullscreen flag will never
2810     * provide a stable layout for a clean transition.
2811     *
2812     * <p>If you are using ActionBar in
2813     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2814     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2815     * insets it adds to those given to the application.
2816     */
2817    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2818
2819    /**
2820     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2821     * to be laid out as if it has requested
2822     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2823     * allows it to avoid artifacts when switching in and out of that mode, at
2824     * the expense that some of its user interface may be covered by screen
2825     * decorations when they are shown.  You can perform layout of your inner
2826     * UI elements to account for the navigation system UI through the
2827     * {@link #fitSystemWindows(Rect)} method.
2828     */
2829    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2830
2831    /**
2832     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2833     * to be laid out as if it has requested
2834     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2835     * allows it to avoid artifacts when switching in and out of that mode, at
2836     * the expense that some of its user interface may be covered by screen
2837     * decorations when they are shown.  You can perform layout of your inner
2838     * UI elements to account for non-fullscreen system UI through the
2839     * {@link #fitSystemWindows(Rect)} method.
2840     */
2841    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2842
2843    /**
2844     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2845     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2846     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2847     * user interaction.
2848     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2849     * has an effect when used in combination with that flag.</p>
2850     */
2851    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2852
2853    /**
2854     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2855     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2856     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2857     * experience while also hiding the system bars.  If this flag is not set,
2858     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2859     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2860     * if the user swipes from the top of the screen.
2861     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2862     * system gestures, such as swiping from the top of the screen.  These transient system bars
2863     * will overlay app’s content, may have some degree of transparency, and will automatically
2864     * hide after a short timeout.
2865     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2866     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2867     * with one or both of those flags.</p>
2868     */
2869    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2870
2871    /**
2872     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2873     * is compatible with light status bar backgrounds.
2874     *
2875     * <p>For this to take effect, the window must request
2876     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2877     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2878     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2879     *         FLAG_TRANSLUCENT_STATUS}.
2880     *
2881     * @see android.R.attr#windowLightStatusBar
2882     */
2883    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2884
2885    /**
2886     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2887     */
2888    @Deprecated
2889    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2890
2891    /**
2892     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2893     */
2894    @Deprecated
2895    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2896
2897    /**
2898     * @hide
2899     *
2900     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2901     * out of the public fields to keep the undefined bits out of the developer's way.
2902     *
2903     * Flag to make the status bar not expandable.  Unless you also
2904     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2905     */
2906    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
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 hide notification icons and scrolling ticker text.
2915     */
2916    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
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 disable incoming notification alerts.  This will not block
2925     * icons, but it will block sound, vibrating and other visual or aural notifications.
2926     */
2927    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2928
2929    /**
2930     * @hide
2931     *
2932     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2933     * out of the public fields to keep the undefined bits out of the developer's way.
2934     *
2935     * Flag to hide only the scrolling ticker.  Note that
2936     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2937     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2938     */
2939    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2940
2941    /**
2942     * @hide
2943     *
2944     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2945     * out of the public fields to keep the undefined bits out of the developer's way.
2946     *
2947     * Flag to hide the center system info area.
2948     */
2949    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2950
2951    /**
2952     * @hide
2953     *
2954     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2955     * out of the public fields to keep the undefined bits out of the developer's way.
2956     *
2957     * Flag to hide only the home button.  Don't use this
2958     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2959     */
2960    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2961
2962    /**
2963     * @hide
2964     *
2965     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2966     * out of the public fields to keep the undefined bits out of the developer's way.
2967     *
2968     * Flag to hide only the back button. Don't use this
2969     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2970     */
2971    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2972
2973    /**
2974     * @hide
2975     *
2976     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2977     * out of the public fields to keep the undefined bits out of the developer's way.
2978     *
2979     * Flag to hide only the clock.  You might use this if your activity has
2980     * its own clock making the status bar's clock redundant.
2981     */
2982    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2983
2984    /**
2985     * @hide
2986     *
2987     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2988     * out of the public fields to keep the undefined bits out of the developer's way.
2989     *
2990     * Flag to hide only the recent apps button. Don't use this
2991     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2992     */
2993    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2994
2995    /**
2996     * @hide
2997     *
2998     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2999     * out of the public fields to keep the undefined bits out of the developer's way.
3000     *
3001     * Flag to disable the global search gesture. Don't use this
3002     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
3003     */
3004    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
3005
3006    /**
3007     * @hide
3008     *
3009     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3010     * out of the public fields to keep the undefined bits out of the developer's way.
3011     *
3012     * Flag to specify that the status bar is displayed in transient mode.
3013     */
3014    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
3015
3016    /**
3017     * @hide
3018     *
3019     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3020     * out of the public fields to keep the undefined bits out of the developer's way.
3021     *
3022     * Flag to specify that the navigation bar is displayed in transient mode.
3023     */
3024    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
3025
3026    /**
3027     * @hide
3028     *
3029     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3030     * out of the public fields to keep the undefined bits out of the developer's way.
3031     *
3032     * Flag to specify that the hidden status bar would like to be shown.
3033     */
3034    public static final int STATUS_BAR_UNHIDE = 0x10000000;
3035
3036    /**
3037     * @hide
3038     *
3039     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3040     * out of the public fields to keep the undefined bits out of the developer's way.
3041     *
3042     * Flag to specify that the hidden navigation bar would like to be shown.
3043     */
3044    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
3045
3046    /**
3047     * @hide
3048     *
3049     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3050     * out of the public fields to keep the undefined bits out of the developer's way.
3051     *
3052     * Flag to specify that the status bar is displayed in translucent mode.
3053     */
3054    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
3055
3056    /**
3057     * @hide
3058     *
3059     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
3060     * out of the public fields to keep the undefined bits out of the developer's way.
3061     *
3062     * Flag to specify that the navigation bar is displayed in translucent mode.
3063     */
3064    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
3065
3066    /**
3067     * @hide
3068     *
3069     * Whether Recents is visible or not.
3070     */
3071    public static final int RECENT_APPS_VISIBLE = 0x00004000;
3072
3073    /**
3074     * @hide
3075     *
3076     * Whether the TV's picture-in-picture is visible or not.
3077     */
3078    public static final int TV_PICTURE_IN_PICTURE_VISIBLE = 0x00010000;
3079
3080    /**
3081     * @hide
3082     *
3083     * Makes navigation bar transparent (but not the status bar).
3084     */
3085    public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000;
3086
3087    /**
3088     * @hide
3089     *
3090     * Makes status bar transparent (but not the navigation bar).
3091     */
3092    public static final int STATUS_BAR_TRANSPARENT = 0x0000008;
3093
3094    /**
3095     * @hide
3096     *
3097     * Makes both status bar and navigation bar transparent.
3098     */
3099    public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT
3100            | STATUS_BAR_TRANSPARENT;
3101
3102    /**
3103     * @hide
3104     */
3105    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7;
3106
3107    /**
3108     * These are the system UI flags that can be cleared by events outside
3109     * of an application.  Currently this is just the ability to tap on the
3110     * screen while hiding the navigation bar to have it return.
3111     * @hide
3112     */
3113    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
3114            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
3115            | SYSTEM_UI_FLAG_FULLSCREEN;
3116
3117    /**
3118     * Flags that can impact the layout in relation to system UI.
3119     */
3120    public static final int SYSTEM_UI_LAYOUT_FLAGS =
3121            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
3122            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
3123
3124    /** @hide */
3125    @IntDef(flag = true,
3126            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
3127    @Retention(RetentionPolicy.SOURCE)
3128    public @interface FindViewFlags {}
3129
3130    /**
3131     * Find views that render the specified text.
3132     *
3133     * @see #findViewsWithText(ArrayList, CharSequence, int)
3134     */
3135    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
3136
3137    /**
3138     * Find find views that contain the specified content description.
3139     *
3140     * @see #findViewsWithText(ArrayList, CharSequence, int)
3141     */
3142    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
3143
3144    /**
3145     * Find views that contain {@link AccessibilityNodeProvider}. Such
3146     * a View is a root of virtual view hierarchy and may contain the searched
3147     * text. If this flag is set Views with providers are automatically
3148     * added and it is a responsibility of the client to call the APIs of
3149     * the provider to determine whether the virtual tree rooted at this View
3150     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
3151     * representing the virtual views with this text.
3152     *
3153     * @see #findViewsWithText(ArrayList, CharSequence, int)
3154     *
3155     * @hide
3156     */
3157    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
3158
3159    /**
3160     * The undefined cursor position.
3161     *
3162     * @hide
3163     */
3164    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
3165
3166    /**
3167     * Indicates that the screen has changed state and is now off.
3168     *
3169     * @see #onScreenStateChanged(int)
3170     */
3171    public static final int SCREEN_STATE_OFF = 0x0;
3172
3173    /**
3174     * Indicates that the screen has changed state and is now on.
3175     *
3176     * @see #onScreenStateChanged(int)
3177     */
3178    public static final int SCREEN_STATE_ON = 0x1;
3179
3180    /**
3181     * Indicates no axis of view scrolling.
3182     */
3183    public static final int SCROLL_AXIS_NONE = 0;
3184
3185    /**
3186     * Indicates scrolling along the horizontal axis.
3187     */
3188    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
3189
3190    /**
3191     * Indicates scrolling along the vertical axis.
3192     */
3193    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
3194
3195    /**
3196     * Controls the over-scroll mode for this view.
3197     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
3198     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
3199     * and {@link #OVER_SCROLL_NEVER}.
3200     */
3201    private int mOverScrollMode;
3202
3203    /**
3204     * The parent this view is attached to.
3205     * {@hide}
3206     *
3207     * @see #getParent()
3208     */
3209    protected ViewParent mParent;
3210
3211    /**
3212     * {@hide}
3213     */
3214    AttachInfo mAttachInfo;
3215
3216    /**
3217     * {@hide}
3218     */
3219    @ViewDebug.ExportedProperty(flagMapping = {
3220        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
3221                name = "FORCE_LAYOUT"),
3222        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
3223                name = "LAYOUT_REQUIRED"),
3224        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
3225            name = "DRAWING_CACHE_INVALID", outputIf = false),
3226        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
3227        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
3228        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
3229        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
3230    }, formatToHexString = true)
3231    int mPrivateFlags;
3232    int mPrivateFlags2;
3233    int mPrivateFlags3;
3234
3235    /**
3236     * This view's request for the visibility of the status bar.
3237     * @hide
3238     */
3239    @ViewDebug.ExportedProperty(flagMapping = {
3240        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
3241                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
3242                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
3243        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3244                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
3245                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
3246        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
3247                                equals = SYSTEM_UI_FLAG_VISIBLE,
3248                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
3249    }, formatToHexString = true)
3250    int mSystemUiVisibility;
3251
3252    /**
3253     * Reference count for transient state.
3254     * @see #setHasTransientState(boolean)
3255     */
3256    int mTransientStateCount = 0;
3257
3258    /**
3259     * Count of how many windows this view has been attached to.
3260     */
3261    int mWindowAttachCount;
3262
3263    /**
3264     * The layout parameters associated with this view and used by the parent
3265     * {@link android.view.ViewGroup} to determine how this view should be
3266     * laid out.
3267     * {@hide}
3268     */
3269    protected ViewGroup.LayoutParams mLayoutParams;
3270
3271    /**
3272     * The view flags hold various views states.
3273     * {@hide}
3274     */
3275    @ViewDebug.ExportedProperty(formatToHexString = true)
3276    int mViewFlags;
3277
3278    static class TransformationInfo {
3279        /**
3280         * The transform matrix for the View. This transform is calculated internally
3281         * based on the translation, rotation, and scale properties.
3282         *
3283         * Do *not* use this variable directly; instead call getMatrix(), which will
3284         * load the value from the View's RenderNode.
3285         */
3286        private final Matrix mMatrix = new Matrix();
3287
3288        /**
3289         * The inverse transform matrix for the View. This transform is calculated
3290         * internally based on the translation, rotation, and scale properties.
3291         *
3292         * Do *not* use this variable directly; instead call getInverseMatrix(),
3293         * which will load the value from the View's RenderNode.
3294         */
3295        private Matrix mInverseMatrix;
3296
3297        /**
3298         * The opacity of the View. This is a value from 0 to 1, where 0 means
3299         * completely transparent and 1 means completely opaque.
3300         */
3301        @ViewDebug.ExportedProperty
3302        float mAlpha = 1f;
3303
3304        /**
3305         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3306         * property only used by transitions, which is composited with the other alpha
3307         * values to calculate the final visual alpha value.
3308         */
3309        float mTransitionAlpha = 1f;
3310    }
3311
3312    TransformationInfo mTransformationInfo;
3313
3314    /**
3315     * Current clip bounds. to which all drawing of this view are constrained.
3316     */
3317    Rect mClipBounds = null;
3318
3319    private boolean mLastIsOpaque;
3320
3321    /**
3322     * The distance in pixels from the left edge of this view's parent
3323     * to the left edge of this view.
3324     * {@hide}
3325     */
3326    @ViewDebug.ExportedProperty(category = "layout")
3327    protected int mLeft;
3328    /**
3329     * The distance in pixels from the left edge of this view's parent
3330     * to the right edge of this view.
3331     * {@hide}
3332     */
3333    @ViewDebug.ExportedProperty(category = "layout")
3334    protected int mRight;
3335    /**
3336     * The distance in pixels from the top edge of this view's parent
3337     * to the top edge of this view.
3338     * {@hide}
3339     */
3340    @ViewDebug.ExportedProperty(category = "layout")
3341    protected int mTop;
3342    /**
3343     * The distance in pixels from the top edge of this view's parent
3344     * to the bottom edge of this view.
3345     * {@hide}
3346     */
3347    @ViewDebug.ExportedProperty(category = "layout")
3348    protected int mBottom;
3349
3350    /**
3351     * The offset, in pixels, by which the content of this view is scrolled
3352     * horizontally.
3353     * {@hide}
3354     */
3355    @ViewDebug.ExportedProperty(category = "scrolling")
3356    protected int mScrollX;
3357    /**
3358     * The offset, in pixels, by which the content of this view is scrolled
3359     * vertically.
3360     * {@hide}
3361     */
3362    @ViewDebug.ExportedProperty(category = "scrolling")
3363    protected int mScrollY;
3364
3365    /**
3366     * The left padding in pixels, that is the distance in pixels between the
3367     * left edge of this view and the left edge of its content.
3368     * {@hide}
3369     */
3370    @ViewDebug.ExportedProperty(category = "padding")
3371    protected int mPaddingLeft = 0;
3372    /**
3373     * The right padding in pixels, that is the distance in pixels between the
3374     * right edge of this view and the right edge of its content.
3375     * {@hide}
3376     */
3377    @ViewDebug.ExportedProperty(category = "padding")
3378    protected int mPaddingRight = 0;
3379    /**
3380     * The top padding in pixels, that is the distance in pixels between the
3381     * top edge of this view and the top edge of its content.
3382     * {@hide}
3383     */
3384    @ViewDebug.ExportedProperty(category = "padding")
3385    protected int mPaddingTop;
3386    /**
3387     * The bottom padding in pixels, that is the distance in pixels between the
3388     * bottom edge of this view and the bottom edge of its content.
3389     * {@hide}
3390     */
3391    @ViewDebug.ExportedProperty(category = "padding")
3392    protected int mPaddingBottom;
3393
3394    /**
3395     * The layout insets in pixels, that is the distance in pixels between the
3396     * visible edges of this view its bounds.
3397     */
3398    private Insets mLayoutInsets;
3399
3400    /**
3401     * Briefly describes the view and is primarily used for accessibility support.
3402     */
3403    private CharSequence mContentDescription;
3404
3405    /**
3406     * Specifies the id of a view for which this view serves as a label for
3407     * accessibility purposes.
3408     */
3409    private int mLabelForId = View.NO_ID;
3410
3411    /**
3412     * Predicate for matching labeled view id with its label for
3413     * accessibility purposes.
3414     */
3415    private MatchLabelForPredicate mMatchLabelForPredicate;
3416
3417    /**
3418     * Specifies a view before which this one is visited in accessibility traversal.
3419     */
3420    private int mAccessibilityTraversalBeforeId = NO_ID;
3421
3422    /**
3423     * Specifies a view after which this one is visited in accessibility traversal.
3424     */
3425    private int mAccessibilityTraversalAfterId = NO_ID;
3426
3427    /**
3428     * Predicate for matching a view by its id.
3429     */
3430    private MatchIdPredicate mMatchIdPredicate;
3431
3432    /**
3433     * Cache the paddingRight set by the user to append to the scrollbar's size.
3434     *
3435     * @hide
3436     */
3437    @ViewDebug.ExportedProperty(category = "padding")
3438    protected int mUserPaddingRight;
3439
3440    /**
3441     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3442     *
3443     * @hide
3444     */
3445    @ViewDebug.ExportedProperty(category = "padding")
3446    protected int mUserPaddingBottom;
3447
3448    /**
3449     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3450     *
3451     * @hide
3452     */
3453    @ViewDebug.ExportedProperty(category = "padding")
3454    protected int mUserPaddingLeft;
3455
3456    /**
3457     * Cache the paddingStart set by the user to append to the scrollbar's size.
3458     *
3459     */
3460    @ViewDebug.ExportedProperty(category = "padding")
3461    int mUserPaddingStart;
3462
3463    /**
3464     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3465     *
3466     */
3467    @ViewDebug.ExportedProperty(category = "padding")
3468    int mUserPaddingEnd;
3469
3470    /**
3471     * Cache initial left padding.
3472     *
3473     * @hide
3474     */
3475    int mUserPaddingLeftInitial;
3476
3477    /**
3478     * Cache initial right padding.
3479     *
3480     * @hide
3481     */
3482    int mUserPaddingRightInitial;
3483
3484    /**
3485     * Default undefined padding
3486     */
3487    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3488
3489    /**
3490     * Cache if a left padding has been defined
3491     */
3492    private boolean mLeftPaddingDefined = false;
3493
3494    /**
3495     * Cache if a right padding has been defined
3496     */
3497    private boolean mRightPaddingDefined = false;
3498
3499    /**
3500     * @hide
3501     */
3502    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3503    /**
3504     * @hide
3505     */
3506    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3507
3508    private LongSparseLongArray mMeasureCache;
3509
3510    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3511    private Drawable mBackground;
3512    private TintInfo mBackgroundTint;
3513
3514    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3515    private ForegroundInfo mForegroundInfo;
3516
3517    private Drawable mScrollIndicatorDrawable;
3518
3519    /**
3520     * RenderNode used for backgrounds.
3521     * <p>
3522     * When non-null and valid, this is expected to contain an up-to-date copy
3523     * of the background drawable. It is cleared on temporary detach, and reset
3524     * on cleanup.
3525     */
3526    private RenderNode mBackgroundRenderNode;
3527
3528    private int mBackgroundResource;
3529    private boolean mBackgroundSizeChanged;
3530
3531    private String mTransitionName;
3532
3533    static class TintInfo {
3534        ColorStateList mTintList;
3535        PorterDuff.Mode mTintMode;
3536        boolean mHasTintMode;
3537        boolean mHasTintList;
3538    }
3539
3540    private static class ForegroundInfo {
3541        private Drawable mDrawable;
3542        private TintInfo mTintInfo;
3543        private int mGravity = Gravity.FILL;
3544        private boolean mInsidePadding = true;
3545        private boolean mBoundsChanged = true;
3546        private final Rect mSelfBounds = new Rect();
3547        private final Rect mOverlayBounds = new Rect();
3548    }
3549
3550    static class ListenerInfo {
3551        /**
3552         * Listener used to dispatch focus change events.
3553         * This field should be made private, so it is hidden from the SDK.
3554         * {@hide}
3555         */
3556        protected OnFocusChangeListener mOnFocusChangeListener;
3557
3558        /**
3559         * Listeners for layout change events.
3560         */
3561        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3562
3563        protected OnScrollChangeListener mOnScrollChangeListener;
3564
3565        /**
3566         * Listeners for attach events.
3567         */
3568        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3569
3570        /**
3571         * Listener used to dispatch click events.
3572         * This field should be made private, so it is hidden from the SDK.
3573         * {@hide}
3574         */
3575        public OnClickListener mOnClickListener;
3576
3577        /**
3578         * Listener used to dispatch long click events.
3579         * This field should be made private, so it is hidden from the SDK.
3580         * {@hide}
3581         */
3582        protected OnLongClickListener mOnLongClickListener;
3583
3584        /**
3585         * Listener used to dispatch context click events. This field should be made private, so it
3586         * is hidden from the SDK.
3587         * {@hide}
3588         */
3589        protected OnContextClickListener mOnContextClickListener;
3590
3591        /**
3592         * Listener used to build the context menu.
3593         * This field should be made private, so it is hidden from the SDK.
3594         * {@hide}
3595         */
3596        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3597
3598        private OnKeyListener mOnKeyListener;
3599
3600        private OnTouchListener mOnTouchListener;
3601
3602        private OnHoverListener mOnHoverListener;
3603
3604        private OnGenericMotionListener mOnGenericMotionListener;
3605
3606        private OnDragListener mOnDragListener;
3607
3608        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3609
3610        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3611    }
3612
3613    ListenerInfo mListenerInfo;
3614
3615    // Temporary values used to hold (x,y) coordinates when delegating from the
3616    // two-arg performLongClick() method to the legacy no-arg version.
3617    private float mLongClickX = Float.NaN;
3618    private float mLongClickY = Float.NaN;
3619
3620    /**
3621     * The application environment this view lives in.
3622     * This field should be made private, so it is hidden from the SDK.
3623     * {@hide}
3624     */
3625    @ViewDebug.ExportedProperty(deepExport = true)
3626    protected Context mContext;
3627
3628    private final Resources mResources;
3629
3630    private ScrollabilityCache mScrollCache;
3631
3632    private int[] mDrawableState = null;
3633
3634    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3635
3636    /**
3637     * Animator that automatically runs based on state changes.
3638     */
3639    private StateListAnimator mStateListAnimator;
3640
3641    /**
3642     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3643     * the user may specify which view to go to next.
3644     */
3645    private int mNextFocusLeftId = View.NO_ID;
3646
3647    /**
3648     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3649     * the user may specify which view to go to next.
3650     */
3651    private int mNextFocusRightId = View.NO_ID;
3652
3653    /**
3654     * When this view has focus and the next focus is {@link #FOCUS_UP},
3655     * the user may specify which view to go to next.
3656     */
3657    private int mNextFocusUpId = View.NO_ID;
3658
3659    /**
3660     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3661     * the user may specify which view to go to next.
3662     */
3663    private int mNextFocusDownId = View.NO_ID;
3664
3665    /**
3666     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3667     * the user may specify which view to go to next.
3668     */
3669    int mNextFocusForwardId = View.NO_ID;
3670
3671    private CheckForLongPress mPendingCheckForLongPress;
3672    private CheckForTap mPendingCheckForTap = null;
3673    private PerformClick mPerformClick;
3674    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3675
3676    private UnsetPressedState mUnsetPressedState;
3677
3678    /**
3679     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3680     * up event while a long press is invoked as soon as the long press duration is reached, so
3681     * a long press could be performed before the tap is checked, in which case the tap's action
3682     * should not be invoked.
3683     */
3684    private boolean mHasPerformedLongPress;
3685
3686    /**
3687     * Whether a context click button is currently pressed down. This is true when the stylus is
3688     * touching the screen and the primary button has been pressed, or if a mouse's right button is
3689     * pressed. This is false once the button is released or if the stylus has been lifted.
3690     */
3691    private boolean mInContextButtonPress;
3692
3693    /**
3694     * Whether the next up event should be ignored for the purposes of gesture recognition. This is
3695     * true after a stylus button press has occured, when the next up event should not be recognized
3696     * as a tap.
3697     */
3698    private boolean mIgnoreNextUpEvent;
3699
3700    /**
3701     * The minimum height of the view. We'll try our best to have the height
3702     * of this view to at least this amount.
3703     */
3704    @ViewDebug.ExportedProperty(category = "measurement")
3705    private int mMinHeight;
3706
3707    /**
3708     * The minimum width of the view. We'll try our best to have the width
3709     * of this view to at least this amount.
3710     */
3711    @ViewDebug.ExportedProperty(category = "measurement")
3712    private int mMinWidth;
3713
3714    /**
3715     * The delegate to handle touch events that are physically in this view
3716     * but should be handled by another view.
3717     */
3718    private TouchDelegate mTouchDelegate = null;
3719
3720    /**
3721     * Solid color to use as a background when creating the drawing cache. Enables
3722     * the cache to use 16 bit bitmaps instead of 32 bit.
3723     */
3724    private int mDrawingCacheBackgroundColor = 0;
3725
3726    /**
3727     * Special tree observer used when mAttachInfo is null.
3728     */
3729    private ViewTreeObserver mFloatingTreeObserver;
3730
3731    /**
3732     * Cache the touch slop from the context that created the view.
3733     */
3734    private int mTouchSlop;
3735
3736    /**
3737     * Object that handles automatic animation of view properties.
3738     */
3739    private ViewPropertyAnimator mAnimator = null;
3740
3741    /**
3742     * List of registered FrameMetricsObservers.
3743     */
3744    private ArrayList<FrameMetricsObserver> mFrameMetricsObservers;
3745
3746    /**
3747     * Flag indicating that a drag can cross window boundaries.  When
3748     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3749     * with this flag set, all visible applications with targetSdkVersion >=
3750     * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate
3751     * in the drag operation and receive the dragged content.
3752     *
3753     * If this is the only flag set, then the drag recipient will only have access to text data
3754     * and intents contained in the {@link ClipData} object. Access to URIs contained in the
3755     * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags.
3756     */
3757    public static final int DRAG_FLAG_GLOBAL = 1 << 8;  // 256
3758
3759    /**
3760     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3761     * request read access to the content URI(s) contained in the {@link ClipData} object.
3762     * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
3763     */
3764    public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION;
3765
3766    /**
3767     * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to
3768     * request write access to the content URI(s) contained in the {@link ClipData} object.
3769     * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3770     */
3771    public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
3772
3773    /**
3774     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3775     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device
3776     * reboots until explicitly revoked with
3777     * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}.
3778     * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3779     */
3780    public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION =
3781            Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;
3782
3783    /**
3784     * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link
3785     * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix
3786     * match against the original granted URI.
3787     * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
3788     */
3789    public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION =
3790            Intent.FLAG_GRANT_PREFIX_URI_PERMISSION;
3791
3792    /**
3793     * Flag indicating that the drag shadow will be opaque.  When
3794     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called
3795     * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent.
3796     */
3797    public static final int DRAG_FLAG_OPAQUE = 1 << 9;
3798
3799    /**
3800     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3801     */
3802    private float mVerticalScrollFactor;
3803
3804    /**
3805     * Position of the vertical scroll bar.
3806     */
3807    private int mVerticalScrollbarPosition;
3808
3809    /**
3810     * Position the scroll bar at the default position as determined by the system.
3811     */
3812    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3813
3814    /**
3815     * Position the scroll bar along the left edge.
3816     */
3817    public static final int SCROLLBAR_POSITION_LEFT = 1;
3818
3819    /**
3820     * Position the scroll bar along the right edge.
3821     */
3822    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3823
3824    /**
3825     * Indicates that the view does not have a layer.
3826     *
3827     * @see #getLayerType()
3828     * @see #setLayerType(int, android.graphics.Paint)
3829     * @see #LAYER_TYPE_SOFTWARE
3830     * @see #LAYER_TYPE_HARDWARE
3831     */
3832    public static final int LAYER_TYPE_NONE = 0;
3833
3834    /**
3835     * <p>Indicates that the view has a software layer. A software layer is backed
3836     * by a bitmap and causes the view to be rendered using Android's software
3837     * rendering pipeline, even if hardware acceleration is enabled.</p>
3838     *
3839     * <p>Software layers have various usages:</p>
3840     * <p>When the application is not using hardware acceleration, a software layer
3841     * is useful to apply a specific color filter and/or blending mode and/or
3842     * translucency to a view and all its children.</p>
3843     * <p>When the application is using hardware acceleration, a software layer
3844     * is useful to render drawing primitives not supported by the hardware
3845     * accelerated pipeline. It can also be used to cache a complex view tree
3846     * into a texture and reduce the complexity of drawing operations. For instance,
3847     * when animating a complex view tree with a translation, a software layer can
3848     * be used to render the view tree only once.</p>
3849     * <p>Software layers should be avoided when the affected view tree updates
3850     * often. Every update will require to re-render the software layer, which can
3851     * potentially be slow (particularly when hardware acceleration is turned on
3852     * since the layer will have to be uploaded into a hardware texture after every
3853     * update.)</p>
3854     *
3855     * @see #getLayerType()
3856     * @see #setLayerType(int, android.graphics.Paint)
3857     * @see #LAYER_TYPE_NONE
3858     * @see #LAYER_TYPE_HARDWARE
3859     */
3860    public static final int LAYER_TYPE_SOFTWARE = 1;
3861
3862    /**
3863     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3864     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3865     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3866     * rendering pipeline, but only if hardware acceleration is turned on for the
3867     * view hierarchy. When hardware acceleration is turned off, hardware layers
3868     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3869     *
3870     * <p>A hardware layer is useful to apply a specific color filter and/or
3871     * blending mode and/or translucency to a view and all its children.</p>
3872     * <p>A hardware layer can be used to cache a complex view tree into a
3873     * texture and reduce the complexity of drawing operations. For instance,
3874     * when animating a complex view tree with a translation, a hardware layer can
3875     * be used to render the view tree only once.</p>
3876     * <p>A hardware layer can also be used to increase the rendering quality when
3877     * rotation transformations are applied on a view. It can also be used to
3878     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3879     *
3880     * @see #getLayerType()
3881     * @see #setLayerType(int, android.graphics.Paint)
3882     * @see #LAYER_TYPE_NONE
3883     * @see #LAYER_TYPE_SOFTWARE
3884     */
3885    public static final int LAYER_TYPE_HARDWARE = 2;
3886
3887    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3888            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3889            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3890            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3891    })
3892    int mLayerType = LAYER_TYPE_NONE;
3893    Paint mLayerPaint;
3894
3895    /**
3896     * Set to true when drawing cache is enabled and cannot be created.
3897     *
3898     * @hide
3899     */
3900    public boolean mCachingFailed;
3901    private Bitmap mDrawingCache;
3902    private Bitmap mUnscaledDrawingCache;
3903
3904    /**
3905     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3906     * <p>
3907     * When non-null and valid, this is expected to contain an up-to-date copy
3908     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3909     * cleanup.
3910     */
3911    final RenderNode mRenderNode;
3912
3913    /**
3914     * Set to true when the view is sending hover accessibility events because it
3915     * is the innermost hovered view.
3916     */
3917    private boolean mSendingHoverAccessibilityEvents;
3918
3919    /**
3920     * Delegate for injecting accessibility functionality.
3921     */
3922    AccessibilityDelegate mAccessibilityDelegate;
3923
3924    /**
3925     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3926     * and add/remove objects to/from the overlay directly through the Overlay methods.
3927     */
3928    ViewOverlay mOverlay;
3929
3930    /**
3931     * The currently active parent view for receiving delegated nested scrolling events.
3932     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3933     * by {@link #stopNestedScroll()} at the same point where we clear
3934     * requestDisallowInterceptTouchEvent.
3935     */
3936    private ViewParent mNestedScrollingParent;
3937
3938    /**
3939     * Consistency verifier for debugging purposes.
3940     * @hide
3941     */
3942    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3943            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3944                    new InputEventConsistencyVerifier(this, 0) : null;
3945
3946    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3947
3948    private int[] mTempNestedScrollConsumed;
3949
3950    /**
3951     * An overlay is going to draw this View instead of being drawn as part of this
3952     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3953     * when this view is invalidated.
3954     */
3955    GhostView mGhostView;
3956
3957    /**
3958     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3959     * @hide
3960     */
3961    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3962    public String[] mAttributes;
3963
3964    /**
3965     * Maps a Resource id to its name.
3966     */
3967    private static SparseArray<String> mAttributeMap;
3968
3969    /**
3970     * Queue of pending runnables. Used to postpone calls to post() until this
3971     * view is attached and has a handler.
3972     */
3973    private HandlerActionQueue mRunQueue;
3974
3975    /**
3976     * The pointer icon when the mouse hovers on this view. The default is null.
3977     */
3978    private PointerIcon mPointerIcon;
3979
3980    /**
3981     * @hide
3982     */
3983    String mStartActivityRequestWho;
3984
3985    /**
3986     * Simple constructor to use when creating a view from code.
3987     *
3988     * @param context The Context the view is running in, through which it can
3989     *        access the current theme, resources, etc.
3990     */
3991    public View(Context context) {
3992        mContext = context;
3993        mResources = context != null ? context.getResources() : null;
3994        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3995        // Set some flags defaults
3996        mPrivateFlags2 =
3997                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3998                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3999                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
4000                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
4001                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
4002                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
4003        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
4004        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
4005        mUserPaddingStart = UNDEFINED_PADDING;
4006        mUserPaddingEnd = UNDEFINED_PADDING;
4007        mRenderNode = RenderNode.create(getClass().getName(), this);
4008
4009        if (!sCompatibilityDone && context != null) {
4010            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4011
4012            // Older apps may need this compatibility hack for measurement.
4013            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
4014
4015            // Older apps expect onMeasure() to always be called on a layout pass, regardless
4016            // of whether a layout was requested on that View.
4017            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
4018
4019            Canvas.sCompatibilityRestore = targetSdkVersion < M;
4020
4021            // In M and newer, our widgets can pass a "hint" value in the size
4022            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
4023            // know what the expected parent size is going to be, so e.g. list items can size
4024            // themselves at 1/3 the size of their container. It breaks older apps though,
4025            // specifically apps that use some popular open source libraries.
4026            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;
4027
4028            // Old versions of the platform would give different results from
4029            // LinearLayout measurement passes using EXACTLY and non-EXACTLY
4030            // modes, so we always need to run an additional EXACTLY pass.
4031            sAlwaysRemeasureExactly = targetSdkVersion <= M;
4032
4033            // Prior to N, layout params could change without requiring a
4034            // subsequent call to setLayoutParams() and they would usually
4035            // work. Partial layout breaks this assumption.
4036            sLayoutParamsAlwaysChanged = targetSdkVersion <= M;
4037
4038            // Prior to N, TextureView would silently ignore calls to setBackground/setForeground.
4039            // On N+, we throw, but that breaks compatibility with apps that use these methods.
4040            sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M;
4041
4042            sCompatibilityDone = true;
4043        }
4044    }
4045
4046    /**
4047     * Constructor that is called when inflating a view from XML. This is called
4048     * when a view is being constructed from an XML file, supplying attributes
4049     * that were specified in the XML file. This version uses a default style of
4050     * 0, so the only attribute values applied are those in the Context's Theme
4051     * and the given AttributeSet.
4052     *
4053     * <p>
4054     * The method onFinishInflate() will be called after all children have been
4055     * added.
4056     *
4057     * @param context The Context the view is running in, through which it can
4058     *        access the current theme, resources, etc.
4059     * @param attrs The attributes of the XML tag that is inflating the view.
4060     * @see #View(Context, AttributeSet, int)
4061     */
4062    public View(Context context, @Nullable AttributeSet attrs) {
4063        this(context, attrs, 0);
4064    }
4065
4066    /**
4067     * Perform inflation from XML and apply a class-specific base style from a
4068     * theme attribute. This constructor of View allows subclasses to use their
4069     * own base style when they are inflating. For example, a Button class's
4070     * constructor would call this version of the super class constructor and
4071     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
4072     * allows the theme's button style to modify all of the base view attributes
4073     * (in particular its background) as well as the Button class's attributes.
4074     *
4075     * @param context The Context the view is running in, through which it can
4076     *        access the current theme, resources, etc.
4077     * @param attrs The attributes of the XML tag that is inflating the view.
4078     * @param defStyleAttr An attribute in the current theme that contains a
4079     *        reference to a style resource that supplies default values for
4080     *        the view. Can be 0 to not look for defaults.
4081     * @see #View(Context, AttributeSet)
4082     */
4083    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
4084        this(context, attrs, defStyleAttr, 0);
4085    }
4086
4087    /**
4088     * Perform inflation from XML and apply a class-specific base style from a
4089     * theme attribute or style resource. This constructor of View allows
4090     * subclasses to use their own base style when they are inflating.
4091     * <p>
4092     * When determining the final value of a particular attribute, there are
4093     * four inputs that come into play:
4094     * <ol>
4095     * <li>Any attribute values in the given AttributeSet.
4096     * <li>The style resource specified in the AttributeSet (named "style").
4097     * <li>The default style specified by <var>defStyleAttr</var>.
4098     * <li>The default style specified by <var>defStyleRes</var>.
4099     * <li>The base values in this theme.
4100     * </ol>
4101     * <p>
4102     * Each of these inputs is considered in-order, with the first listed taking
4103     * precedence over the following ones. In other words, if in the
4104     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
4105     * , then the button's text will <em>always</em> be black, regardless of
4106     * what is specified in any of the styles.
4107     *
4108     * @param context The Context the view is running in, through which it can
4109     *        access the current theme, resources, etc.
4110     * @param attrs The attributes of the XML tag that is inflating the view.
4111     * @param defStyleAttr An attribute in the current theme that contains a
4112     *        reference to a style resource that supplies default values for
4113     *        the view. Can be 0 to not look for defaults.
4114     * @param defStyleRes A resource identifier of a style resource that
4115     *        supplies default values for the view, used only if
4116     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
4117     *        to not look for defaults.
4118     * @see #View(Context, AttributeSet, int)
4119     */
4120    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
4121        this(context);
4122
4123        final TypedArray a = context.obtainStyledAttributes(
4124                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
4125
4126        if (mDebugViewAttributes) {
4127            saveAttributeData(attrs, a);
4128        }
4129
4130        Drawable background = null;
4131
4132        int leftPadding = -1;
4133        int topPadding = -1;
4134        int rightPadding = -1;
4135        int bottomPadding = -1;
4136        int startPadding = UNDEFINED_PADDING;
4137        int endPadding = UNDEFINED_PADDING;
4138
4139        int padding = -1;
4140
4141        int viewFlagValues = 0;
4142        int viewFlagMasks = 0;
4143
4144        boolean setScrollContainer = false;
4145
4146        int x = 0;
4147        int y = 0;
4148
4149        float tx = 0;
4150        float ty = 0;
4151        float tz = 0;
4152        float elevation = 0;
4153        float rotation = 0;
4154        float rotationX = 0;
4155        float rotationY = 0;
4156        float sx = 1f;
4157        float sy = 1f;
4158        boolean transformSet = false;
4159
4160        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
4161        int overScrollMode = mOverScrollMode;
4162        boolean initializeScrollbars = false;
4163        boolean initializeScrollIndicators = false;
4164
4165        boolean startPaddingDefined = false;
4166        boolean endPaddingDefined = false;
4167        boolean leftPaddingDefined = false;
4168        boolean rightPaddingDefined = false;
4169
4170        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
4171
4172        final int N = a.getIndexCount();
4173        for (int i = 0; i < N; i++) {
4174            int attr = a.getIndex(i);
4175            switch (attr) {
4176                case com.android.internal.R.styleable.View_background:
4177                    background = a.getDrawable(attr);
4178                    break;
4179                case com.android.internal.R.styleable.View_padding:
4180                    padding = a.getDimensionPixelSize(attr, -1);
4181                    mUserPaddingLeftInitial = padding;
4182                    mUserPaddingRightInitial = padding;
4183                    leftPaddingDefined = true;
4184                    rightPaddingDefined = true;
4185                    break;
4186                 case com.android.internal.R.styleable.View_paddingLeft:
4187                    leftPadding = a.getDimensionPixelSize(attr, -1);
4188                    mUserPaddingLeftInitial = leftPadding;
4189                    leftPaddingDefined = true;
4190                    break;
4191                case com.android.internal.R.styleable.View_paddingTop:
4192                    topPadding = a.getDimensionPixelSize(attr, -1);
4193                    break;
4194                case com.android.internal.R.styleable.View_paddingRight:
4195                    rightPadding = a.getDimensionPixelSize(attr, -1);
4196                    mUserPaddingRightInitial = rightPadding;
4197                    rightPaddingDefined = true;
4198                    break;
4199                case com.android.internal.R.styleable.View_paddingBottom:
4200                    bottomPadding = a.getDimensionPixelSize(attr, -1);
4201                    break;
4202                case com.android.internal.R.styleable.View_paddingStart:
4203                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4204                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
4205                    break;
4206                case com.android.internal.R.styleable.View_paddingEnd:
4207                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
4208                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
4209                    break;
4210                case com.android.internal.R.styleable.View_scrollX:
4211                    x = a.getDimensionPixelOffset(attr, 0);
4212                    break;
4213                case com.android.internal.R.styleable.View_scrollY:
4214                    y = a.getDimensionPixelOffset(attr, 0);
4215                    break;
4216                case com.android.internal.R.styleable.View_alpha:
4217                    setAlpha(a.getFloat(attr, 1f));
4218                    break;
4219                case com.android.internal.R.styleable.View_transformPivotX:
4220                    setPivotX(a.getDimensionPixelOffset(attr, 0));
4221                    break;
4222                case com.android.internal.R.styleable.View_transformPivotY:
4223                    setPivotY(a.getDimensionPixelOffset(attr, 0));
4224                    break;
4225                case com.android.internal.R.styleable.View_translationX:
4226                    tx = a.getDimensionPixelOffset(attr, 0);
4227                    transformSet = true;
4228                    break;
4229                case com.android.internal.R.styleable.View_translationY:
4230                    ty = a.getDimensionPixelOffset(attr, 0);
4231                    transformSet = true;
4232                    break;
4233                case com.android.internal.R.styleable.View_translationZ:
4234                    tz = a.getDimensionPixelOffset(attr, 0);
4235                    transformSet = true;
4236                    break;
4237                case com.android.internal.R.styleable.View_elevation:
4238                    elevation = a.getDimensionPixelOffset(attr, 0);
4239                    transformSet = true;
4240                    break;
4241                case com.android.internal.R.styleable.View_rotation:
4242                    rotation = a.getFloat(attr, 0);
4243                    transformSet = true;
4244                    break;
4245                case com.android.internal.R.styleable.View_rotationX:
4246                    rotationX = a.getFloat(attr, 0);
4247                    transformSet = true;
4248                    break;
4249                case com.android.internal.R.styleable.View_rotationY:
4250                    rotationY = a.getFloat(attr, 0);
4251                    transformSet = true;
4252                    break;
4253                case com.android.internal.R.styleable.View_scaleX:
4254                    sx = a.getFloat(attr, 1f);
4255                    transformSet = true;
4256                    break;
4257                case com.android.internal.R.styleable.View_scaleY:
4258                    sy = a.getFloat(attr, 1f);
4259                    transformSet = true;
4260                    break;
4261                case com.android.internal.R.styleable.View_id:
4262                    mID = a.getResourceId(attr, NO_ID);
4263                    break;
4264                case com.android.internal.R.styleable.View_tag:
4265                    mTag = a.getText(attr);
4266                    break;
4267                case com.android.internal.R.styleable.View_fitsSystemWindows:
4268                    if (a.getBoolean(attr, false)) {
4269                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
4270                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
4271                    }
4272                    break;
4273                case com.android.internal.R.styleable.View_focusable:
4274                    if (a.getBoolean(attr, false)) {
4275                        viewFlagValues |= FOCUSABLE;
4276                        viewFlagMasks |= FOCUSABLE_MASK;
4277                    }
4278                    break;
4279                case com.android.internal.R.styleable.View_focusableInTouchMode:
4280                    if (a.getBoolean(attr, false)) {
4281                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
4282                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
4283                    }
4284                    break;
4285                case com.android.internal.R.styleable.View_clickable:
4286                    if (a.getBoolean(attr, false)) {
4287                        viewFlagValues |= CLICKABLE;
4288                        viewFlagMasks |= CLICKABLE;
4289                    }
4290                    break;
4291                case com.android.internal.R.styleable.View_longClickable:
4292                    if (a.getBoolean(attr, false)) {
4293                        viewFlagValues |= LONG_CLICKABLE;
4294                        viewFlagMasks |= LONG_CLICKABLE;
4295                    }
4296                    break;
4297                case com.android.internal.R.styleable.View_contextClickable:
4298                    if (a.getBoolean(attr, false)) {
4299                        viewFlagValues |= CONTEXT_CLICKABLE;
4300                        viewFlagMasks |= CONTEXT_CLICKABLE;
4301                    }
4302                    break;
4303                case com.android.internal.R.styleable.View_saveEnabled:
4304                    if (!a.getBoolean(attr, true)) {
4305                        viewFlagValues |= SAVE_DISABLED;
4306                        viewFlagMasks |= SAVE_DISABLED_MASK;
4307                    }
4308                    break;
4309                case com.android.internal.R.styleable.View_duplicateParentState:
4310                    if (a.getBoolean(attr, false)) {
4311                        viewFlagValues |= DUPLICATE_PARENT_STATE;
4312                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
4313                    }
4314                    break;
4315                case com.android.internal.R.styleable.View_visibility:
4316                    final int visibility = a.getInt(attr, 0);
4317                    if (visibility != 0) {
4318                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
4319                        viewFlagMasks |= VISIBILITY_MASK;
4320                    }
4321                    break;
4322                case com.android.internal.R.styleable.View_layoutDirection:
4323                    // Clear any layout direction flags (included resolved bits) already set
4324                    mPrivateFlags2 &=
4325                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
4326                    // Set the layout direction flags depending on the value of the attribute
4327                    final int layoutDirection = a.getInt(attr, -1);
4328                    final int value = (layoutDirection != -1) ?
4329                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
4330                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
4331                    break;
4332                case com.android.internal.R.styleable.View_drawingCacheQuality:
4333                    final int cacheQuality = a.getInt(attr, 0);
4334                    if (cacheQuality != 0) {
4335                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
4336                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
4337                    }
4338                    break;
4339                case com.android.internal.R.styleable.View_contentDescription:
4340                    setContentDescription(a.getString(attr));
4341                    break;
4342                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
4343                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
4344                    break;
4345                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
4346                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
4347                    break;
4348                case com.android.internal.R.styleable.View_labelFor:
4349                    setLabelFor(a.getResourceId(attr, NO_ID));
4350                    break;
4351                case com.android.internal.R.styleable.View_soundEffectsEnabled:
4352                    if (!a.getBoolean(attr, true)) {
4353                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
4354                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
4355                    }
4356                    break;
4357                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
4358                    if (!a.getBoolean(attr, true)) {
4359                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
4360                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
4361                    }
4362                    break;
4363                case R.styleable.View_scrollbars:
4364                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
4365                    if (scrollbars != SCROLLBARS_NONE) {
4366                        viewFlagValues |= scrollbars;
4367                        viewFlagMasks |= SCROLLBARS_MASK;
4368                        initializeScrollbars = true;
4369                    }
4370                    break;
4371                //noinspection deprecation
4372                case R.styleable.View_fadingEdge:
4373                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
4374                        // Ignore the attribute starting with ICS
4375                        break;
4376                    }
4377                    // With builds < ICS, fall through and apply fading edges
4378                case R.styleable.View_requiresFadingEdge:
4379                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
4380                    if (fadingEdge != FADING_EDGE_NONE) {
4381                        viewFlagValues |= fadingEdge;
4382                        viewFlagMasks |= FADING_EDGE_MASK;
4383                        initializeFadingEdgeInternal(a);
4384                    }
4385                    break;
4386                case R.styleable.View_scrollbarStyle:
4387                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4388                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4389                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4390                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4391                    }
4392                    break;
4393                case R.styleable.View_isScrollContainer:
4394                    setScrollContainer = true;
4395                    if (a.getBoolean(attr, false)) {
4396                        setScrollContainer(true);
4397                    }
4398                    break;
4399                case com.android.internal.R.styleable.View_keepScreenOn:
4400                    if (a.getBoolean(attr, false)) {
4401                        viewFlagValues |= KEEP_SCREEN_ON;
4402                        viewFlagMasks |= KEEP_SCREEN_ON;
4403                    }
4404                    break;
4405                case R.styleable.View_filterTouchesWhenObscured:
4406                    if (a.getBoolean(attr, false)) {
4407                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4408                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4409                    }
4410                    break;
4411                case R.styleable.View_nextFocusLeft:
4412                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4413                    break;
4414                case R.styleable.View_nextFocusRight:
4415                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4416                    break;
4417                case R.styleable.View_nextFocusUp:
4418                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4419                    break;
4420                case R.styleable.View_nextFocusDown:
4421                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4422                    break;
4423                case R.styleable.View_nextFocusForward:
4424                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4425                    break;
4426                case R.styleable.View_minWidth:
4427                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4428                    break;
4429                case R.styleable.View_minHeight:
4430                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4431                    break;
4432                case R.styleable.View_onClick:
4433                    if (context.isRestricted()) {
4434                        throw new IllegalStateException("The android:onClick attribute cannot "
4435                                + "be used within a restricted context");
4436                    }
4437
4438                    final String handlerName = a.getString(attr);
4439                    if (handlerName != null) {
4440                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4441                    }
4442                    break;
4443                case R.styleable.View_overScrollMode:
4444                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4445                    break;
4446                case R.styleable.View_verticalScrollbarPosition:
4447                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4448                    break;
4449                case R.styleable.View_layerType:
4450                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4451                    break;
4452                case R.styleable.View_textDirection:
4453                    // Clear any text direction flag already set
4454                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4455                    // Set the text direction flags depending on the value of the attribute
4456                    final int textDirection = a.getInt(attr, -1);
4457                    if (textDirection != -1) {
4458                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4459                    }
4460                    break;
4461                case R.styleable.View_textAlignment:
4462                    // Clear any text alignment flag already set
4463                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4464                    // Set the text alignment flag depending on the value of the attribute
4465                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4466                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4467                    break;
4468                case R.styleable.View_importantForAccessibility:
4469                    setImportantForAccessibility(a.getInt(attr,
4470                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4471                    break;
4472                case R.styleable.View_accessibilityLiveRegion:
4473                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4474                    break;
4475                case R.styleable.View_transitionName:
4476                    setTransitionName(a.getString(attr));
4477                    break;
4478                case R.styleable.View_nestedScrollingEnabled:
4479                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4480                    break;
4481                case R.styleable.View_stateListAnimator:
4482                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4483                            a.getResourceId(attr, 0)));
4484                    break;
4485                case R.styleable.View_backgroundTint:
4486                    // This will get applied later during setBackground().
4487                    if (mBackgroundTint == null) {
4488                        mBackgroundTint = new TintInfo();
4489                    }
4490                    mBackgroundTint.mTintList = a.getColorStateList(
4491                            R.styleable.View_backgroundTint);
4492                    mBackgroundTint.mHasTintList = true;
4493                    break;
4494                case R.styleable.View_backgroundTintMode:
4495                    // This will get applied later during setBackground().
4496                    if (mBackgroundTint == null) {
4497                        mBackgroundTint = new TintInfo();
4498                    }
4499                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4500                            R.styleable.View_backgroundTintMode, -1), null);
4501                    mBackgroundTint.mHasTintMode = true;
4502                    break;
4503                case R.styleable.View_outlineProvider:
4504                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4505                            PROVIDER_BACKGROUND));
4506                    break;
4507                case R.styleable.View_foreground:
4508                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4509                        setForeground(a.getDrawable(attr));
4510                    }
4511                    break;
4512                case R.styleable.View_foregroundGravity:
4513                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4514                        setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4515                    }
4516                    break;
4517                case R.styleable.View_foregroundTintMode:
4518                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4519                        setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4520                    }
4521                    break;
4522                case R.styleable.View_foregroundTint:
4523                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4524                        setForegroundTintList(a.getColorStateList(attr));
4525                    }
4526                    break;
4527                case R.styleable.View_foregroundInsidePadding:
4528                    if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) {
4529                        if (mForegroundInfo == null) {
4530                            mForegroundInfo = new ForegroundInfo();
4531                        }
4532                        mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4533                                mForegroundInfo.mInsidePadding);
4534                    }
4535                    break;
4536                case R.styleable.View_scrollIndicators:
4537                    final int scrollIndicators =
4538                            (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT)
4539                                    & SCROLL_INDICATORS_PFLAG3_MASK;
4540                    if (scrollIndicators != 0) {
4541                        mPrivateFlags3 |= scrollIndicators;
4542                        initializeScrollIndicators = true;
4543                    }
4544                    break;
4545                case R.styleable.View_pointerIcon:
4546                    final int resourceId = a.getResourceId(attr, 0);
4547                    if (resourceId != 0) {
4548                        setPointerIcon(PointerIcon.load(
4549                                context.getResources(), resourceId));
4550                    } else {
4551                        final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED);
4552                        if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) {
4553                            setPointerIcon(PointerIcon.getSystemIcon(context, pointerType));
4554                        }
4555                    }
4556                    break;
4557                case R.styleable.View_forceHasOverlappingRendering:
4558                    if (a.peekValue(attr) != null) {
4559                        forceHasOverlappingRendering(a.getBoolean(attr, true));
4560                    }
4561                    break;
4562
4563            }
4564        }
4565
4566        setOverScrollMode(overScrollMode);
4567
4568        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4569        // the resolved layout direction). Those cached values will be used later during padding
4570        // resolution.
4571        mUserPaddingStart = startPadding;
4572        mUserPaddingEnd = endPadding;
4573
4574        if (background != null) {
4575            setBackground(background);
4576        }
4577
4578        // setBackground above will record that padding is currently provided by the background.
4579        // If we have padding specified via xml, record that here instead and use it.
4580        mLeftPaddingDefined = leftPaddingDefined;
4581        mRightPaddingDefined = rightPaddingDefined;
4582
4583        if (padding >= 0) {
4584            leftPadding = padding;
4585            topPadding = padding;
4586            rightPadding = padding;
4587            bottomPadding = padding;
4588            mUserPaddingLeftInitial = padding;
4589            mUserPaddingRightInitial = padding;
4590        }
4591
4592        if (isRtlCompatibilityMode()) {
4593            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4594            // left / right padding are used if defined (meaning here nothing to do). If they are not
4595            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4596            // start / end and resolve them as left / right (layout direction is not taken into account).
4597            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4598            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4599            // defined.
4600            if (!mLeftPaddingDefined && startPaddingDefined) {
4601                leftPadding = startPadding;
4602            }
4603            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4604            if (!mRightPaddingDefined && endPaddingDefined) {
4605                rightPadding = endPadding;
4606            }
4607            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4608        } else {
4609            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4610            // values defined. Otherwise, left /right values are used.
4611            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4612            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4613            // defined.
4614            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4615
4616            if (mLeftPaddingDefined && !hasRelativePadding) {
4617                mUserPaddingLeftInitial = leftPadding;
4618            }
4619            if (mRightPaddingDefined && !hasRelativePadding) {
4620                mUserPaddingRightInitial = rightPadding;
4621            }
4622        }
4623
4624        internalSetPadding(
4625                mUserPaddingLeftInitial,
4626                topPadding >= 0 ? topPadding : mPaddingTop,
4627                mUserPaddingRightInitial,
4628                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4629
4630        if (viewFlagMasks != 0) {
4631            setFlags(viewFlagValues, viewFlagMasks);
4632        }
4633
4634        if (initializeScrollbars) {
4635            initializeScrollbarsInternal(a);
4636        }
4637
4638        if (initializeScrollIndicators) {
4639            initializeScrollIndicatorsInternal();
4640        }
4641
4642        a.recycle();
4643
4644        // Needs to be called after mViewFlags is set
4645        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4646            recomputePadding();
4647        }
4648
4649        if (x != 0 || y != 0) {
4650            scrollTo(x, y);
4651        }
4652
4653        if (transformSet) {
4654            setTranslationX(tx);
4655            setTranslationY(ty);
4656            setTranslationZ(tz);
4657            setElevation(elevation);
4658            setRotation(rotation);
4659            setRotationX(rotationX);
4660            setRotationY(rotationY);
4661            setScaleX(sx);
4662            setScaleY(sy);
4663        }
4664
4665        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4666            setScrollContainer(true);
4667        }
4668
4669        computeOpaqueFlags();
4670    }
4671
4672    /**
4673     * An implementation of OnClickListener that attempts to lazily load a
4674     * named click handling method from a parent or ancestor context.
4675     */
4676    private static class DeclaredOnClickListener implements OnClickListener {
4677        private final View mHostView;
4678        private final String mMethodName;
4679
4680        private Method mResolvedMethod;
4681        private Context mResolvedContext;
4682
4683        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4684            mHostView = hostView;
4685            mMethodName = methodName;
4686        }
4687
4688        @Override
4689        public void onClick(@NonNull View v) {
4690            if (mResolvedMethod == null) {
4691                resolveMethod(mHostView.getContext(), mMethodName);
4692            }
4693
4694            try {
4695                mResolvedMethod.invoke(mResolvedContext, v);
4696            } catch (IllegalAccessException e) {
4697                throw new IllegalStateException(
4698                        "Could not execute non-public method for android:onClick", e);
4699            } catch (InvocationTargetException e) {
4700                throw new IllegalStateException(
4701                        "Could not execute method for android:onClick", e);
4702            }
4703        }
4704
4705        @NonNull
4706        private void resolveMethod(@Nullable Context context, @NonNull String name) {
4707            while (context != null) {
4708                try {
4709                    if (!context.isRestricted()) {
4710                        final Method method = context.getClass().getMethod(mMethodName, View.class);
4711                        if (method != null) {
4712                            mResolvedMethod = method;
4713                            mResolvedContext = context;
4714                            return;
4715                        }
4716                    }
4717                } catch (NoSuchMethodException e) {
4718                    // Failed to find method, keep searching up the hierarchy.
4719                }
4720
4721                if (context instanceof ContextWrapper) {
4722                    context = ((ContextWrapper) context).getBaseContext();
4723                } else {
4724                    // Can't search up the hierarchy, null out and fail.
4725                    context = null;
4726                }
4727            }
4728
4729            final int id = mHostView.getId();
4730            final String idText = id == NO_ID ? "" : " with id '"
4731                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4732            throw new IllegalStateException("Could not find method " + mMethodName
4733                    + "(View) in a parent or ancestor Context for android:onClick "
4734                    + "attribute defined on view " + mHostView.getClass() + idText);
4735        }
4736    }
4737
4738    /**
4739     * Non-public constructor for use in testing
4740     */
4741    View() {
4742        mResources = null;
4743        mRenderNode = RenderNode.create(getClass().getName(), this);
4744    }
4745
4746    private static SparseArray<String> getAttributeMap() {
4747        if (mAttributeMap == null) {
4748            mAttributeMap = new SparseArray<>();
4749        }
4750        return mAttributeMap;
4751    }
4752
4753    private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) {
4754        final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount();
4755        final int indexCount = t.getIndexCount();
4756        final String[] attributes = new String[(attrsCount + indexCount) * 2];
4757
4758        int i = 0;
4759
4760        // Store raw XML attributes.
4761        for (int j = 0; j < attrsCount; ++j) {
4762            attributes[i] = attrs.getAttributeName(j);
4763            attributes[i + 1] = attrs.getAttributeValue(j);
4764            i += 2;
4765        }
4766
4767        // Store resolved styleable attributes.
4768        final Resources res = t.getResources();
4769        final SparseArray<String> attributeMap = getAttributeMap();
4770        for (int j = 0; j < indexCount; ++j) {
4771            final int index = t.getIndex(j);
4772            if (!t.hasValueOrEmpty(index)) {
4773                // Value is undefined. Skip it.
4774                continue;
4775            }
4776
4777            final int resourceId = t.getResourceId(index, 0);
4778            if (resourceId == 0) {
4779                // Value is not a reference. Skip it.
4780                continue;
4781            }
4782
4783            String resourceName = attributeMap.get(resourceId);
4784            if (resourceName == null) {
4785                try {
4786                    resourceName = res.getResourceName(resourceId);
4787                } catch (Resources.NotFoundException e) {
4788                    resourceName = "0x" + Integer.toHexString(resourceId);
4789                }
4790                attributeMap.put(resourceId, resourceName);
4791            }
4792
4793            attributes[i] = resourceName;
4794            attributes[i + 1] = t.getString(index);
4795            i += 2;
4796        }
4797
4798        // Trim to fit contents.
4799        final String[] trimmed = new String[i];
4800        System.arraycopy(attributes, 0, trimmed, 0, i);
4801        mAttributes = trimmed;
4802    }
4803
4804    public String toString() {
4805        StringBuilder out = new StringBuilder(128);
4806        out.append(getClass().getName());
4807        out.append('{');
4808        out.append(Integer.toHexString(System.identityHashCode(this)));
4809        out.append(' ');
4810        switch (mViewFlags&VISIBILITY_MASK) {
4811            case VISIBLE: out.append('V'); break;
4812            case INVISIBLE: out.append('I'); break;
4813            case GONE: out.append('G'); break;
4814            default: out.append('.'); break;
4815        }
4816        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4817        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4818        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4819        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4820        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4821        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4822        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4823        out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.');
4824        out.append(' ');
4825        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4826        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4827        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4828        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4829            out.append('p');
4830        } else {
4831            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4832        }
4833        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4834        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4835        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4836        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4837        out.append(' ');
4838        out.append(mLeft);
4839        out.append(',');
4840        out.append(mTop);
4841        out.append('-');
4842        out.append(mRight);
4843        out.append(',');
4844        out.append(mBottom);
4845        final int id = getId();
4846        if (id != NO_ID) {
4847            out.append(" #");
4848            out.append(Integer.toHexString(id));
4849            final Resources r = mResources;
4850            if (id > 0 && Resources.resourceHasPackage(id) && r != null) {
4851                try {
4852                    String pkgname;
4853                    switch (id&0xff000000) {
4854                        case 0x7f000000:
4855                            pkgname="app";
4856                            break;
4857                        case 0x01000000:
4858                            pkgname="android";
4859                            break;
4860                        default:
4861                            pkgname = r.getResourcePackageName(id);
4862                            break;
4863                    }
4864                    String typename = r.getResourceTypeName(id);
4865                    String entryname = r.getResourceEntryName(id);
4866                    out.append(" ");
4867                    out.append(pkgname);
4868                    out.append(":");
4869                    out.append(typename);
4870                    out.append("/");
4871                    out.append(entryname);
4872                } catch (Resources.NotFoundException e) {
4873                }
4874            }
4875        }
4876        out.append("}");
4877        return out.toString();
4878    }
4879
4880    /**
4881     * <p>
4882     * Initializes the fading edges from a given set of styled attributes. This
4883     * method should be called by subclasses that need fading edges and when an
4884     * instance of these subclasses is created programmatically rather than
4885     * being inflated from XML. This method is automatically called when the XML
4886     * is inflated.
4887     * </p>
4888     *
4889     * @param a the styled attributes set to initialize the fading edges from
4890     *
4891     * @removed
4892     */
4893    protected void initializeFadingEdge(TypedArray a) {
4894        // This method probably shouldn't have been included in the SDK to begin with.
4895        // It relies on 'a' having been initialized using an attribute filter array that is
4896        // not publicly available to the SDK. The old method has been renamed
4897        // to initializeFadingEdgeInternal and hidden for framework use only;
4898        // this one initializes using defaults to make it safe to call for apps.
4899
4900        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4901
4902        initializeFadingEdgeInternal(arr);
4903
4904        arr.recycle();
4905    }
4906
4907    /**
4908     * <p>
4909     * Initializes the fading edges from a given set of styled attributes. This
4910     * method should be called by subclasses that need fading edges and when an
4911     * instance of these subclasses is created programmatically rather than
4912     * being inflated from XML. This method is automatically called when the XML
4913     * is inflated.
4914     * </p>
4915     *
4916     * @param a the styled attributes set to initialize the fading edges from
4917     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4918     */
4919    protected void initializeFadingEdgeInternal(TypedArray a) {
4920        initScrollCache();
4921
4922        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4923                R.styleable.View_fadingEdgeLength,
4924                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4925    }
4926
4927    /**
4928     * Returns the size of the vertical faded edges used to indicate that more
4929     * content in this view is visible.
4930     *
4931     * @return The size in pixels of the vertical faded edge or 0 if vertical
4932     *         faded edges are not enabled for this view.
4933     * @attr ref android.R.styleable#View_fadingEdgeLength
4934     */
4935    public int getVerticalFadingEdgeLength() {
4936        if (isVerticalFadingEdgeEnabled()) {
4937            ScrollabilityCache cache = mScrollCache;
4938            if (cache != null) {
4939                return cache.fadingEdgeLength;
4940            }
4941        }
4942        return 0;
4943    }
4944
4945    /**
4946     * Set the size of the faded edge used to indicate that more content in this
4947     * view is available.  Will not change whether the fading edge is enabled; use
4948     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4949     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4950     * for the vertical or horizontal fading edges.
4951     *
4952     * @param length The size in pixels of the faded edge used to indicate that more
4953     *        content in this view is visible.
4954     */
4955    public void setFadingEdgeLength(int length) {
4956        initScrollCache();
4957        mScrollCache.fadingEdgeLength = length;
4958    }
4959
4960    /**
4961     * Returns the size of the horizontal faded edges used to indicate that more
4962     * content in this view is visible.
4963     *
4964     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4965     *         faded edges are not enabled for this view.
4966     * @attr ref android.R.styleable#View_fadingEdgeLength
4967     */
4968    public int getHorizontalFadingEdgeLength() {
4969        if (isHorizontalFadingEdgeEnabled()) {
4970            ScrollabilityCache cache = mScrollCache;
4971            if (cache != null) {
4972                return cache.fadingEdgeLength;
4973            }
4974        }
4975        return 0;
4976    }
4977
4978    /**
4979     * Returns the width of the vertical scrollbar.
4980     *
4981     * @return The width in pixels of the vertical scrollbar or 0 if there
4982     *         is no vertical scrollbar.
4983     */
4984    public int getVerticalScrollbarWidth() {
4985        ScrollabilityCache cache = mScrollCache;
4986        if (cache != null) {
4987            ScrollBarDrawable scrollBar = cache.scrollBar;
4988            if (scrollBar != null) {
4989                int size = scrollBar.getSize(true);
4990                if (size <= 0) {
4991                    size = cache.scrollBarSize;
4992                }
4993                return size;
4994            }
4995            return 0;
4996        }
4997        return 0;
4998    }
4999
5000    /**
5001     * Returns the height of the horizontal scrollbar.
5002     *
5003     * @return The height in pixels of the horizontal scrollbar or 0 if
5004     *         there is no horizontal scrollbar.
5005     */
5006    protected int getHorizontalScrollbarHeight() {
5007        ScrollabilityCache cache = mScrollCache;
5008        if (cache != null) {
5009            ScrollBarDrawable scrollBar = cache.scrollBar;
5010            if (scrollBar != null) {
5011                int size = scrollBar.getSize(false);
5012                if (size <= 0) {
5013                    size = cache.scrollBarSize;
5014                }
5015                return size;
5016            }
5017            return 0;
5018        }
5019        return 0;
5020    }
5021
5022    /**
5023     * <p>
5024     * Initializes the scrollbars from a given set of styled attributes. This
5025     * method should be called by subclasses that need scrollbars and when an
5026     * instance of these subclasses is created programmatically rather than
5027     * being inflated from XML. This method is automatically called when the XML
5028     * is inflated.
5029     * </p>
5030     *
5031     * @param a the styled attributes set to initialize the scrollbars from
5032     *
5033     * @removed
5034     */
5035    protected void initializeScrollbars(TypedArray a) {
5036        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
5037        // using the View filter array which is not available to the SDK. As such, internal
5038        // framework usage now uses initializeScrollbarsInternal and we grab a default
5039        // TypedArray with the right filter instead here.
5040        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
5041
5042        initializeScrollbarsInternal(arr);
5043
5044        // We ignored the method parameter. Recycle the one we actually did use.
5045        arr.recycle();
5046    }
5047
5048    /**
5049     * <p>
5050     * Initializes the scrollbars from a given set of styled attributes. This
5051     * method should be called by subclasses that need scrollbars and when an
5052     * instance of these subclasses is created programmatically rather than
5053     * being inflated from XML. This method is automatically called when the XML
5054     * is inflated.
5055     * </p>
5056     *
5057     * @param a the styled attributes set to initialize the scrollbars from
5058     * @hide
5059     */
5060    protected void initializeScrollbarsInternal(TypedArray a) {
5061        initScrollCache();
5062
5063        final ScrollabilityCache scrollabilityCache = mScrollCache;
5064
5065        if (scrollabilityCache.scrollBar == null) {
5066            scrollabilityCache.scrollBar = new ScrollBarDrawable();
5067            scrollabilityCache.scrollBar.setState(getDrawableState());
5068            scrollabilityCache.scrollBar.setCallback(this);
5069        }
5070
5071        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
5072
5073        if (!fadeScrollbars) {
5074            scrollabilityCache.state = ScrollabilityCache.ON;
5075        }
5076        scrollabilityCache.fadeScrollBars = fadeScrollbars;
5077
5078
5079        scrollabilityCache.scrollBarFadeDuration = a.getInt(
5080                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
5081                        .getScrollBarFadeDuration());
5082        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
5083                R.styleable.View_scrollbarDefaultDelayBeforeFade,
5084                ViewConfiguration.getScrollDefaultDelay());
5085
5086
5087        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
5088                com.android.internal.R.styleable.View_scrollbarSize,
5089                ViewConfiguration.get(mContext).getScaledScrollBarSize());
5090
5091        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
5092        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
5093
5094        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
5095        if (thumb != null) {
5096            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
5097        }
5098
5099        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
5100                false);
5101        if (alwaysDraw) {
5102            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
5103        }
5104
5105        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
5106        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
5107
5108        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
5109        if (thumb != null) {
5110            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
5111        }
5112
5113        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
5114                false);
5115        if (alwaysDraw) {
5116            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
5117        }
5118
5119        // Apply layout direction to the new Drawables if needed
5120        final int layoutDirection = getLayoutDirection();
5121        if (track != null) {
5122            track.setLayoutDirection(layoutDirection);
5123        }
5124        if (thumb != null) {
5125            thumb.setLayoutDirection(layoutDirection);
5126        }
5127
5128        // Re-apply user/background padding so that scrollbar(s) get added
5129        resolvePadding();
5130    }
5131
5132    private void initializeScrollIndicatorsInternal() {
5133        // Some day maybe we'll break this into top/left/start/etc. and let the
5134        // client control it. Until then, you can have any scroll indicator you
5135        // want as long as it's a 1dp foreground-colored rectangle.
5136        if (mScrollIndicatorDrawable == null) {
5137            mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material);
5138        }
5139    }
5140
5141    /**
5142     * <p>
5143     * Initalizes the scrollability cache if necessary.
5144     * </p>
5145     */
5146    private void initScrollCache() {
5147        if (mScrollCache == null) {
5148            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
5149        }
5150    }
5151
5152    private ScrollabilityCache getScrollCache() {
5153        initScrollCache();
5154        return mScrollCache;
5155    }
5156
5157    /**
5158     * Set the position of the vertical scroll bar. Should be one of
5159     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
5160     * {@link #SCROLLBAR_POSITION_RIGHT}.
5161     *
5162     * @param position Where the vertical scroll bar should be positioned.
5163     */
5164    public void setVerticalScrollbarPosition(int position) {
5165        if (mVerticalScrollbarPosition != position) {
5166            mVerticalScrollbarPosition = position;
5167            computeOpaqueFlags();
5168            resolvePadding();
5169        }
5170    }
5171
5172    /**
5173     * @return The position where the vertical scroll bar will show, if applicable.
5174     * @see #setVerticalScrollbarPosition(int)
5175     */
5176    public int getVerticalScrollbarPosition() {
5177        return mVerticalScrollbarPosition;
5178    }
5179
5180    boolean isOnScrollbar(float x, float y) {
5181        if (mScrollCache == null) {
5182            return false;
5183        }
5184        x += getScrollX();
5185        y += getScrollY();
5186        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5187            final Rect bounds = mScrollCache.mScrollBarBounds;
5188            getVerticalScrollBarBounds(bounds);
5189            if (bounds.contains((int)x, (int)y)) {
5190                return true;
5191            }
5192        }
5193        if (isHorizontalScrollBarEnabled()) {
5194            final Rect bounds = mScrollCache.mScrollBarBounds;
5195            getHorizontalScrollBarBounds(bounds);
5196            if (bounds.contains((int)x, (int)y)) {
5197                return true;
5198            }
5199        }
5200        return false;
5201    }
5202
5203    boolean isOnScrollbarThumb(float x, float y) {
5204        return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y);
5205    }
5206
5207    private boolean isOnVerticalScrollbarThumb(float x, float y) {
5208        if (mScrollCache == null) {
5209            return false;
5210        }
5211        if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) {
5212            x += getScrollX();
5213            y += getScrollY();
5214            final Rect bounds = mScrollCache.mScrollBarBounds;
5215            getVerticalScrollBarBounds(bounds);
5216            final int range = computeVerticalScrollRange();
5217            final int offset = computeVerticalScrollOffset();
5218            final int extent = computeVerticalScrollExtent();
5219            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(),
5220                    extent, range);
5221            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength,
5222                    extent, range, offset);
5223            final int thumbTop = bounds.top + thumbOffset;
5224            if (x >= bounds.left && x <= bounds.right && y >= thumbTop
5225                    && y <= thumbTop + thumbLength) {
5226                return true;
5227            }
5228        }
5229        return false;
5230    }
5231
5232    private boolean isOnHorizontalScrollbarThumb(float x, float y) {
5233        if (mScrollCache == null) {
5234            return false;
5235        }
5236        if (isHorizontalScrollBarEnabled()) {
5237            x += getScrollX();
5238            y += getScrollY();
5239            final Rect bounds = mScrollCache.mScrollBarBounds;
5240            getHorizontalScrollBarBounds(bounds);
5241            final int range = computeHorizontalScrollRange();
5242            final int offset = computeHorizontalScrollOffset();
5243            final int extent = computeHorizontalScrollExtent();
5244            final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(),
5245                    extent, range);
5246            final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength,
5247                    extent, range, offset);
5248            final int thumbLeft = bounds.left + thumbOffset;
5249            if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top
5250                    && y <= bounds.bottom) {
5251                return true;
5252            }
5253        }
5254        return false;
5255    }
5256
5257    boolean isDraggingScrollBar() {
5258        return mScrollCache != null
5259                && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING;
5260    }
5261
5262    /**
5263     * Sets the state of all scroll indicators.
5264     * <p>
5265     * See {@link #setScrollIndicators(int, int)} for usage information.
5266     *
5267     * @param indicators a bitmask of indicators that should be enabled, or
5268     *                   {@code 0} to disable all indicators
5269     * @see #setScrollIndicators(int, int)
5270     * @see #getScrollIndicators()
5271     * @attr ref android.R.styleable#View_scrollIndicators
5272     */
5273    public void setScrollIndicators(@ScrollIndicators int indicators) {
5274        setScrollIndicators(indicators,
5275                SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT);
5276    }
5277
5278    /**
5279     * Sets the state of the scroll indicators specified by the mask. To change
5280     * all scroll indicators at once, see {@link #setScrollIndicators(int)}.
5281     * <p>
5282     * When a scroll indicator is enabled, it will be displayed if the view
5283     * can scroll in the direction of the indicator.
5284     * <p>
5285     * Multiple indicator types may be enabled or disabled by passing the
5286     * logical OR of the desired types. If multiple types are specified, they
5287     * will all be set to the same enabled state.
5288     * <p>
5289     * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators
5290     *
5291     * @param indicators the indicator direction, or the logical OR of multiple
5292     *             indicator directions. One or more of:
5293     *             <ul>
5294     *               <li>{@link #SCROLL_INDICATOR_TOP}</li>
5295     *               <li>{@link #SCROLL_INDICATOR_BOTTOM}</li>
5296     *               <li>{@link #SCROLL_INDICATOR_LEFT}</li>
5297     *               <li>{@link #SCROLL_INDICATOR_RIGHT}</li>
5298     *               <li>{@link #SCROLL_INDICATOR_START}</li>
5299     *               <li>{@link #SCROLL_INDICATOR_END}</li>
5300     *             </ul>
5301     * @see #setScrollIndicators(int)
5302     * @see #getScrollIndicators()
5303     * @attr ref android.R.styleable#View_scrollIndicators
5304     */
5305    public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) {
5306        // Shift and sanitize mask.
5307        mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5308        mask &= SCROLL_INDICATORS_PFLAG3_MASK;
5309
5310        // Shift and mask indicators.
5311        indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5312        indicators &= mask;
5313
5314        // Merge with non-masked flags.
5315        final int updatedFlags = indicators | (mPrivateFlags3 & ~mask);
5316
5317        if (mPrivateFlags3 != updatedFlags) {
5318            mPrivateFlags3 = updatedFlags;
5319
5320            if (indicators != 0) {
5321                initializeScrollIndicatorsInternal();
5322            }
5323            invalidate();
5324        }
5325    }
5326
5327    /**
5328     * Returns a bitmask representing the enabled scroll indicators.
5329     * <p>
5330     * For example, if the top and left scroll indicators are enabled and all
5331     * other indicators are disabled, the return value will be
5332     * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}.
5333     * <p>
5334     * To check whether the bottom scroll indicator is enabled, use the value
5335     * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}.
5336     *
5337     * @return a bitmask representing the enabled scroll indicators
5338     */
5339    @ScrollIndicators
5340    public int getScrollIndicators() {
5341        return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK)
5342                >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT;
5343    }
5344
5345    ListenerInfo getListenerInfo() {
5346        if (mListenerInfo != null) {
5347            return mListenerInfo;
5348        }
5349        mListenerInfo = new ListenerInfo();
5350        return mListenerInfo;
5351    }
5352
5353    /**
5354     * Register a callback to be invoked when the scroll X or Y positions of
5355     * this view change.
5356     * <p>
5357     * <b>Note:</b> Some views handle scrolling independently from View and may
5358     * have their own separate listeners for scroll-type events. For example,
5359     * {@link android.widget.ListView ListView} allows clients to register an
5360     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
5361     * to listen for changes in list scroll position.
5362     *
5363     * @param l The listener to notify when the scroll X or Y position changes.
5364     * @see android.view.View#getScrollX()
5365     * @see android.view.View#getScrollY()
5366     */
5367    public void setOnScrollChangeListener(OnScrollChangeListener l) {
5368        getListenerInfo().mOnScrollChangeListener = l;
5369    }
5370
5371    /**
5372     * Register a callback to be invoked when focus of this view changed.
5373     *
5374     * @param l The callback that will run.
5375     */
5376    public void setOnFocusChangeListener(OnFocusChangeListener l) {
5377        getListenerInfo().mOnFocusChangeListener = l;
5378    }
5379
5380    /**
5381     * Add a listener that will be called when the bounds of the view change due to
5382     * layout processing.
5383     *
5384     * @param listener The listener that will be called when layout bounds change.
5385     */
5386    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
5387        ListenerInfo li = getListenerInfo();
5388        if (li.mOnLayoutChangeListeners == null) {
5389            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
5390        }
5391        if (!li.mOnLayoutChangeListeners.contains(listener)) {
5392            li.mOnLayoutChangeListeners.add(listener);
5393        }
5394    }
5395
5396    /**
5397     * Remove a listener for layout changes.
5398     *
5399     * @param listener The listener for layout bounds change.
5400     */
5401    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
5402        ListenerInfo li = mListenerInfo;
5403        if (li == null || li.mOnLayoutChangeListeners == null) {
5404            return;
5405        }
5406        li.mOnLayoutChangeListeners.remove(listener);
5407    }
5408
5409    /**
5410     * Add a listener for attach state changes.
5411     *
5412     * This listener will be called whenever this view is attached or detached
5413     * from a window. Remove the listener using
5414     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
5415     *
5416     * @param listener Listener to attach
5417     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
5418     */
5419    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5420        ListenerInfo li = getListenerInfo();
5421        if (li.mOnAttachStateChangeListeners == null) {
5422            li.mOnAttachStateChangeListeners
5423                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
5424        }
5425        li.mOnAttachStateChangeListeners.add(listener);
5426    }
5427
5428    /**
5429     * Remove a listener for attach state changes. The listener will receive no further
5430     * notification of window attach/detach events.
5431     *
5432     * @param listener Listener to remove
5433     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
5434     */
5435    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
5436        ListenerInfo li = mListenerInfo;
5437        if (li == null || li.mOnAttachStateChangeListeners == null) {
5438            return;
5439        }
5440        li.mOnAttachStateChangeListeners.remove(listener);
5441    }
5442
5443    /**
5444     * Returns the focus-change callback registered for this view.
5445     *
5446     * @return The callback, or null if one is not registered.
5447     */
5448    public OnFocusChangeListener getOnFocusChangeListener() {
5449        ListenerInfo li = mListenerInfo;
5450        return li != null ? li.mOnFocusChangeListener : null;
5451    }
5452
5453    /**
5454     * Register a callback to be invoked when this view is clicked. If this view is not
5455     * clickable, it becomes clickable.
5456     *
5457     * @param l The callback that will run
5458     *
5459     * @see #setClickable(boolean)
5460     */
5461    public void setOnClickListener(@Nullable OnClickListener l) {
5462        if (!isClickable()) {
5463            setClickable(true);
5464        }
5465        getListenerInfo().mOnClickListener = l;
5466    }
5467
5468    /**
5469     * Return whether this view has an attached OnClickListener.  Returns
5470     * true if there is a listener, false if there is none.
5471     */
5472    public boolean hasOnClickListeners() {
5473        ListenerInfo li = mListenerInfo;
5474        return (li != null && li.mOnClickListener != null);
5475    }
5476
5477    /**
5478     * Register a callback to be invoked when this view is clicked and held. If this view is not
5479     * long clickable, it becomes long clickable.
5480     *
5481     * @param l The callback that will run
5482     *
5483     * @see #setLongClickable(boolean)
5484     */
5485    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
5486        if (!isLongClickable()) {
5487            setLongClickable(true);
5488        }
5489        getListenerInfo().mOnLongClickListener = l;
5490    }
5491
5492    /**
5493     * Register a callback to be invoked when this view is context clicked. If the view is not
5494     * context clickable, it becomes context clickable.
5495     *
5496     * @param l The callback that will run
5497     * @see #setContextClickable(boolean)
5498     */
5499    public void setOnContextClickListener(@Nullable OnContextClickListener l) {
5500        if (!isContextClickable()) {
5501            setContextClickable(true);
5502        }
5503        getListenerInfo().mOnContextClickListener = l;
5504    }
5505
5506    /**
5507     * Register a callback to be invoked when the context menu for this view is
5508     * being built. If this view is not long clickable, it becomes long clickable.
5509     *
5510     * @param l The callback that will run
5511     *
5512     */
5513    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
5514        if (!isLongClickable()) {
5515            setLongClickable(true);
5516        }
5517        getListenerInfo().mOnCreateContextMenuListener = l;
5518    }
5519
5520    /**
5521     * Set an observer to collect stats for each frame rendered for this view.
5522     *
5523     * @hide
5524     */
5525    public void addFrameMetricsListener(Window window,
5526            Window.OnFrameMetricsAvailableListener listener,
5527            Handler handler) {
5528        if (mAttachInfo != null) {
5529            if (mAttachInfo.mThreadedRenderer != null) {
5530                if (mFrameMetricsObservers == null) {
5531                    mFrameMetricsObservers = new ArrayList<>();
5532                }
5533
5534                FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5535                        handler.getLooper(), listener);
5536                mFrameMetricsObservers.add(fmo);
5537                mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo);
5538            } else {
5539                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5540            }
5541        } else {
5542            if (mFrameMetricsObservers == null) {
5543                mFrameMetricsObservers = new ArrayList<>();
5544            }
5545
5546            FrameMetricsObserver fmo = new FrameMetricsObserver(window,
5547                    handler.getLooper(), listener);
5548            mFrameMetricsObservers.add(fmo);
5549        }
5550    }
5551
5552    /**
5553     * Remove observer configured to collect frame stats for this view.
5554     *
5555     * @hide
5556     */
5557    public void removeFrameMetricsListener(
5558            Window.OnFrameMetricsAvailableListener listener) {
5559        ThreadedRenderer renderer = getThreadedRenderer();
5560        FrameMetricsObserver fmo = findFrameMetricsObserver(listener);
5561        if (fmo == null) {
5562            throw new IllegalArgumentException(
5563                    "attempt to remove OnFrameMetricsAvailableListener that was never added");
5564        }
5565
5566        if (mFrameMetricsObservers != null) {
5567            mFrameMetricsObservers.remove(fmo);
5568            if (renderer != null) {
5569                renderer.removeFrameMetricsObserver(fmo);
5570            }
5571        }
5572    }
5573
5574    private void registerPendingFrameMetricsObservers() {
5575        if (mFrameMetricsObservers != null) {
5576            ThreadedRenderer renderer = getThreadedRenderer();
5577            if (renderer != null) {
5578                for (FrameMetricsObserver fmo : mFrameMetricsObservers) {
5579                    renderer.addFrameMetricsObserver(fmo);
5580                }
5581            } else {
5582                Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats");
5583            }
5584        }
5585    }
5586
5587    private FrameMetricsObserver findFrameMetricsObserver(
5588            Window.OnFrameMetricsAvailableListener listener) {
5589        for (int i = 0; i < mFrameMetricsObservers.size(); i++) {
5590            FrameMetricsObserver observer = mFrameMetricsObservers.get(i);
5591            if (observer.mListener == listener) {
5592                return observer;
5593            }
5594        }
5595
5596        return null;
5597    }
5598
5599    /**
5600     * Call this view's OnClickListener, if it is defined.  Performs all normal
5601     * actions associated with clicking: reporting accessibility event, playing
5602     * a sound, etc.
5603     *
5604     * @return True there was an assigned OnClickListener that was called, false
5605     *         otherwise is returned.
5606     */
5607    public boolean performClick() {
5608        final boolean result;
5609        final ListenerInfo li = mListenerInfo;
5610        if (li != null && li.mOnClickListener != null) {
5611            playSoundEffect(SoundEffectConstants.CLICK);
5612            li.mOnClickListener.onClick(this);
5613            result = true;
5614        } else {
5615            result = false;
5616        }
5617
5618        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
5619        return result;
5620    }
5621
5622    /**
5623     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
5624     * this only calls the listener, and does not do any associated clicking
5625     * actions like reporting an accessibility event.
5626     *
5627     * @return True there was an assigned OnClickListener that was called, false
5628     *         otherwise is returned.
5629     */
5630    public boolean callOnClick() {
5631        ListenerInfo li = mListenerInfo;
5632        if (li != null && li.mOnClickListener != null) {
5633            li.mOnClickListener.onClick(this);
5634            return true;
5635        }
5636        return false;
5637    }
5638
5639    /**
5640     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5641     * context menu if the OnLongClickListener did not consume the event.
5642     *
5643     * @return {@code true} if one of the above receivers consumed the event,
5644     *         {@code false} otherwise
5645     */
5646    public boolean performLongClick() {
5647        return performLongClickInternal(mLongClickX, mLongClickY);
5648    }
5649
5650    /**
5651     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5652     * context menu if the OnLongClickListener did not consume the event,
5653     * anchoring it to an (x,y) coordinate.
5654     *
5655     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5656     *          to disable anchoring
5657     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5658     *          to disable anchoring
5659     * @return {@code true} if one of the above receivers consumed the event,
5660     *         {@code false} otherwise
5661     */
5662    public boolean performLongClick(float x, float y) {
5663        mLongClickX = x;
5664        mLongClickY = y;
5665        final boolean handled = performLongClick();
5666        mLongClickX = Float.NaN;
5667        mLongClickY = Float.NaN;
5668        return handled;
5669    }
5670
5671    /**
5672     * Calls this view's OnLongClickListener, if it is defined. Invokes the
5673     * context menu if the OnLongClickListener did not consume the event,
5674     * optionally anchoring it to an (x,y) coordinate.
5675     *
5676     * @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
5677     *          to disable anchoring
5678     * @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
5679     *          to disable anchoring
5680     * @return {@code true} if one of the above receivers consumed the event,
5681     *         {@code false} otherwise
5682     */
5683    private boolean performLongClickInternal(float x, float y) {
5684        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
5685
5686        boolean handled = false;
5687        final ListenerInfo li = mListenerInfo;
5688        if (li != null && li.mOnLongClickListener != null) {
5689            handled = li.mOnLongClickListener.onLongClick(View.this);
5690        }
5691        if (!handled) {
5692            final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
5693            handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
5694        }
5695        if (handled) {
5696            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
5697        }
5698        return handled;
5699    }
5700
5701    /**
5702     * Call this view's OnContextClickListener, if it is defined.
5703     *
5704     * @param x the x coordinate of the context click
5705     * @param y the y coordinate of the context click
5706     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5707     *         otherwise.
5708     */
5709    public boolean performContextClick(float x, float y) {
5710        return performContextClick();
5711    }
5712
5713    /**
5714     * Call this view's OnContextClickListener, if it is defined.
5715     *
5716     * @return True if there was an assigned OnContextClickListener that consumed the event, false
5717     *         otherwise.
5718     */
5719    public boolean performContextClick() {
5720        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED);
5721
5722        boolean handled = false;
5723        ListenerInfo li = mListenerInfo;
5724        if (li != null && li.mOnContextClickListener != null) {
5725            handled = li.mOnContextClickListener.onContextClick(View.this);
5726        }
5727        if (handled) {
5728            performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK);
5729        }
5730        return handled;
5731    }
5732
5733    /**
5734     * Performs button-related actions during a touch down event.
5735     *
5736     * @param event The event.
5737     * @return True if the down was consumed.
5738     *
5739     * @hide
5740     */
5741    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5742        if (event.isFromSource(InputDevice.SOURCE_MOUSE) &&
5743            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5744            showContextMenu(event.getX(), event.getY());
5745            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5746            return true;
5747        }
5748        return false;
5749    }
5750
5751    /**
5752     * Shows the context menu for this view.
5753     *
5754     * @return {@code true} if the context menu was shown, {@code false}
5755     *         otherwise
5756     * @see #showContextMenu(float, float)
5757     */
5758    public boolean showContextMenu() {
5759        return getParent().showContextMenuForChild(this);
5760    }
5761
5762    /**
5763     * Shows the context menu for this view anchored to the specified
5764     * view-relative coordinate.
5765     *
5766     * @param x the X coordinate in pixels relative to the view to which the
5767     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5768     * @param y the Y coordinate in pixels relative to the view to which the
5769     *          menu should be anchored, or {@link Float#NaN} to disable anchoring
5770     * @return {@code true} if the context menu was shown, {@code false}
5771     *         otherwise
5772     */
5773    public boolean showContextMenu(float x, float y) {
5774        return getParent().showContextMenuForChild(this, x, y);
5775    }
5776
5777    /**
5778     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5779     *
5780     * @param callback Callback that will control the lifecycle of the action mode
5781     * @return The new action mode if it is started, null otherwise
5782     *
5783     * @see ActionMode
5784     * @see #startActionMode(android.view.ActionMode.Callback, int)
5785     */
5786    public ActionMode startActionMode(ActionMode.Callback callback) {
5787        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5788    }
5789
5790    /**
5791     * Start an action mode with the given type.
5792     *
5793     * @param callback Callback that will control the lifecycle of the action mode
5794     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5795     * @return The new action mode if it is started, null otherwise
5796     *
5797     * @see ActionMode
5798     */
5799    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5800        ViewParent parent = getParent();
5801        if (parent == null) return null;
5802        try {
5803            return parent.startActionModeForChild(this, callback, type);
5804        } catch (AbstractMethodError ame) {
5805            // Older implementations of custom views might not implement this.
5806            return parent.startActionModeForChild(this, callback);
5807        }
5808    }
5809
5810    /**
5811     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5812     * Context, creating a unique View identifier to retrieve the result.
5813     *
5814     * @param intent The Intent to be started.
5815     * @param requestCode The request code to use.
5816     * @hide
5817     */
5818    public void startActivityForResult(Intent intent, int requestCode) {
5819        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5820        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5821    }
5822
5823    /**
5824     * If this View corresponds to the calling who, dispatches the activity result.
5825     * @param who The identifier for the targeted View to receive the result.
5826     * @param requestCode The integer request code originally supplied to
5827     *                    startActivityForResult(), allowing you to identify who this
5828     *                    result came from.
5829     * @param resultCode The integer result code returned by the child activity
5830     *                   through its setResult().
5831     * @param data An Intent, which can return result data to the caller
5832     *               (various data can be attached to Intent "extras").
5833     * @return {@code true} if the activity result was dispatched.
5834     * @hide
5835     */
5836    public boolean dispatchActivityResult(
5837            String who, int requestCode, int resultCode, Intent data) {
5838        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5839            onActivityResult(requestCode, resultCode, data);
5840            mStartActivityRequestWho = null;
5841            return true;
5842        }
5843        return false;
5844    }
5845
5846    /**
5847     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5848     *
5849     * @param requestCode The integer request code originally supplied to
5850     *                    startActivityForResult(), allowing you to identify who this
5851     *                    result came from.
5852     * @param resultCode The integer result code returned by the child activity
5853     *                   through its setResult().
5854     * @param data An Intent, which can return result data to the caller
5855     *               (various data can be attached to Intent "extras").
5856     * @hide
5857     */
5858    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5859        // Do nothing.
5860    }
5861
5862    /**
5863     * Register a callback to be invoked when a hardware key is pressed in this view.
5864     * Key presses in software input methods will generally not trigger the methods of
5865     * this listener.
5866     * @param l the key listener to attach to this view
5867     */
5868    public void setOnKeyListener(OnKeyListener l) {
5869        getListenerInfo().mOnKeyListener = l;
5870    }
5871
5872    /**
5873     * Register a callback to be invoked when a touch event is sent to this view.
5874     * @param l the touch listener to attach to this view
5875     */
5876    public void setOnTouchListener(OnTouchListener l) {
5877        getListenerInfo().mOnTouchListener = l;
5878    }
5879
5880    /**
5881     * Register a callback to be invoked when a generic motion event is sent to this view.
5882     * @param l the generic motion listener to attach to this view
5883     */
5884    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5885        getListenerInfo().mOnGenericMotionListener = l;
5886    }
5887
5888    /**
5889     * Register a callback to be invoked when a hover event is sent to this view.
5890     * @param l the hover listener to attach to this view
5891     */
5892    public void setOnHoverListener(OnHoverListener l) {
5893        getListenerInfo().mOnHoverListener = l;
5894    }
5895
5896    /**
5897     * Register a drag event listener callback object for this View. The parameter is
5898     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5899     * View, the system calls the
5900     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5901     * @param l An implementation of {@link android.view.View.OnDragListener}.
5902     */
5903    public void setOnDragListener(OnDragListener l) {
5904        getListenerInfo().mOnDragListener = l;
5905    }
5906
5907    /**
5908     * Give this view focus. This will cause
5909     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5910     *
5911     * Note: this does not check whether this {@link View} should get focus, it just
5912     * gives it focus no matter what.  It should only be called internally by framework
5913     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5914     *
5915     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5916     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5917     *        focus moved when requestFocus() is called. It may not always
5918     *        apply, in which case use the default View.FOCUS_DOWN.
5919     * @param previouslyFocusedRect The rectangle of the view that had focus
5920     *        prior in this View's coordinate system.
5921     */
5922    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5923        if (DBG) {
5924            System.out.println(this + " requestFocus()");
5925        }
5926
5927        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5928            mPrivateFlags |= PFLAG_FOCUSED;
5929
5930            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5931
5932            if (mParent != null) {
5933                mParent.requestChildFocus(this, this);
5934            }
5935
5936            if (mAttachInfo != null) {
5937                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5938            }
5939
5940            onFocusChanged(true, direction, previouslyFocusedRect);
5941            refreshDrawableState();
5942        }
5943    }
5944
5945    /**
5946     * Populates <code>outRect</code> with the hotspot bounds. By default,
5947     * the hotspot bounds are identical to the screen bounds.
5948     *
5949     * @param outRect rect to populate with hotspot bounds
5950     * @hide Only for internal use by views and widgets.
5951     */
5952    public void getHotspotBounds(Rect outRect) {
5953        final Drawable background = getBackground();
5954        if (background != null) {
5955            background.getHotspotBounds(outRect);
5956        } else {
5957            getBoundsOnScreen(outRect);
5958        }
5959    }
5960
5961    /**
5962     * Request that a rectangle of this view be visible on the screen,
5963     * scrolling if necessary just enough.
5964     *
5965     * <p>A View should call this if it maintains some notion of which part
5966     * of its content is interesting.  For example, a text editing view
5967     * should call this when its cursor moves.
5968     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5969     * It should not be affected by which part of the View is currently visible or its scroll
5970     * position.
5971     *
5972     * @param rectangle The rectangle in the View's content coordinate space
5973     * @return Whether any parent scrolled.
5974     */
5975    public boolean requestRectangleOnScreen(Rect rectangle) {
5976        return requestRectangleOnScreen(rectangle, false);
5977    }
5978
5979    /**
5980     * Request that a rectangle of this view be visible on the screen,
5981     * scrolling if necessary just enough.
5982     *
5983     * <p>A View should call this if it maintains some notion of which part
5984     * of its content is interesting.  For example, a text editing view
5985     * should call this when its cursor moves.
5986     * <p>The Rectangle passed into this method should be in the View's content coordinate space.
5987     * It should not be affected by which part of the View is currently visible or its scroll
5988     * position.
5989     * <p>When <code>immediate</code> is set to true, scrolling will not be
5990     * animated.
5991     *
5992     * @param rectangle The rectangle in the View's content coordinate space
5993     * @param immediate True to forbid animated scrolling, false otherwise
5994     * @return Whether any parent scrolled.
5995     */
5996    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5997        if (mParent == null) {
5998            return false;
5999        }
6000
6001        View child = this;
6002
6003        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
6004        position.set(rectangle);
6005
6006        ViewParent parent = mParent;
6007        boolean scrolled = false;
6008        while (parent != null) {
6009            rectangle.set((int) position.left, (int) position.top,
6010                    (int) position.right, (int) position.bottom);
6011
6012            scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate);
6013
6014            if (!(parent instanceof View)) {
6015                break;
6016            }
6017
6018            // move it from child's content coordinate space to parent's content coordinate space
6019            position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY());
6020
6021            child = (View) parent;
6022            parent = child.getParent();
6023        }
6024
6025        return scrolled;
6026    }
6027
6028    /**
6029     * Called when this view wants to give up focus. If focus is cleared
6030     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
6031     * <p>
6032     * <strong>Note:</strong> When a View clears focus the framework is trying
6033     * to give focus to the first focusable View from the top. Hence, if this
6034     * View is the first from the top that can take focus, then all callbacks
6035     * related to clearing focus will be invoked after which the framework will
6036     * give focus to this view.
6037     * </p>
6038     */
6039    public void clearFocus() {
6040        if (DBG) {
6041            System.out.println(this + " clearFocus()");
6042        }
6043
6044        clearFocusInternal(null, true, true);
6045    }
6046
6047    /**
6048     * Clears focus from the view, optionally propagating the change up through
6049     * the parent hierarchy and requesting that the root view place new focus.
6050     *
6051     * @param propagate whether to propagate the change up through the parent
6052     *            hierarchy
6053     * @param refocus when propagate is true, specifies whether to request the
6054     *            root view place new focus
6055     */
6056    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
6057        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
6058            mPrivateFlags &= ~PFLAG_FOCUSED;
6059
6060            if (propagate && mParent != null) {
6061                mParent.clearChildFocus(this);
6062            }
6063
6064            onFocusChanged(false, 0, null);
6065            refreshDrawableState();
6066
6067            if (propagate && (!refocus || !rootViewRequestFocus())) {
6068                notifyGlobalFocusCleared(this);
6069            }
6070        }
6071    }
6072
6073    void notifyGlobalFocusCleared(View oldFocus) {
6074        if (oldFocus != null && mAttachInfo != null) {
6075            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
6076        }
6077    }
6078
6079    boolean rootViewRequestFocus() {
6080        final View root = getRootView();
6081        return root != null && root.requestFocus();
6082    }
6083
6084    /**
6085     * Called internally by the view system when a new view is getting focus.
6086     * This is what clears the old focus.
6087     * <p>
6088     * <b>NOTE:</b> The parent view's focused child must be updated manually
6089     * after calling this method. Otherwise, the view hierarchy may be left in
6090     * an inconstent state.
6091     */
6092    void unFocus(View focused) {
6093        if (DBG) {
6094            System.out.println(this + " unFocus()");
6095        }
6096
6097        clearFocusInternal(focused, false, false);
6098    }
6099
6100    /**
6101     * Returns true if this view has focus itself, or is the ancestor of the
6102     * view that has focus.
6103     *
6104     * @return True if this view has or contains focus, false otherwise.
6105     */
6106    @ViewDebug.ExportedProperty(category = "focus")
6107    public boolean hasFocus() {
6108        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6109    }
6110
6111    /**
6112     * Returns true if this view is focusable or if it contains a reachable View
6113     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
6114     * is a View whose parents do not block descendants focus.
6115     *
6116     * Only {@link #VISIBLE} views are considered focusable.
6117     *
6118     * @return True if the view is focusable or if the view contains a focusable
6119     *         View, false otherwise.
6120     *
6121     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
6122     * @see ViewGroup#getTouchscreenBlocksFocus()
6123     */
6124    public boolean hasFocusable() {
6125        if (!isFocusableInTouchMode()) {
6126            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
6127                final ViewGroup g = (ViewGroup) p;
6128                if (g.shouldBlockFocusForTouchscreen()) {
6129                    return false;
6130                }
6131            }
6132        }
6133        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
6134    }
6135
6136    /**
6137     * Called by the view system when the focus state of this view changes.
6138     * When the focus change event is caused by directional navigation, direction
6139     * and previouslyFocusedRect provide insight into where the focus is coming from.
6140     * When overriding, be sure to call up through to the super class so that
6141     * the standard focus handling will occur.
6142     *
6143     * @param gainFocus True if the View has focus; false otherwise.
6144     * @param direction The direction focus has moved when requestFocus()
6145     *                  is called to give this view focus. Values are
6146     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
6147     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
6148     *                  It may not always apply, in which case use the default.
6149     * @param previouslyFocusedRect The rectangle, in this view's coordinate
6150     *        system, of the previously focused view.  If applicable, this will be
6151     *        passed in as finer grained information about where the focus is coming
6152     *        from (in addition to direction).  Will be <code>null</code> otherwise.
6153     */
6154    @CallSuper
6155    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
6156            @Nullable Rect previouslyFocusedRect) {
6157        if (gainFocus) {
6158            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
6159        } else {
6160            notifyViewAccessibilityStateChangedIfNeeded(
6161                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6162        }
6163
6164        InputMethodManager imm = InputMethodManager.peekInstance();
6165        if (!gainFocus) {
6166            if (isPressed()) {
6167                setPressed(false);
6168            }
6169            if (imm != null && mAttachInfo != null
6170                    && mAttachInfo.mHasWindowFocus) {
6171                imm.focusOut(this);
6172            }
6173            onFocusLost();
6174        } else if (imm != null && mAttachInfo != null
6175                && mAttachInfo.mHasWindowFocus) {
6176            imm.focusIn(this);
6177        }
6178
6179        invalidate(true);
6180        ListenerInfo li = mListenerInfo;
6181        if (li != null && li.mOnFocusChangeListener != null) {
6182            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
6183        }
6184
6185        if (mAttachInfo != null) {
6186            mAttachInfo.mKeyDispatchState.reset(this);
6187        }
6188    }
6189
6190    /**
6191     * Sends an accessibility event of the given type. If accessibility is
6192     * not enabled this method has no effect. The default implementation calls
6193     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
6194     * to populate information about the event source (this View), then calls
6195     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
6196     * populate the text content of the event source including its descendants,
6197     * and last calls
6198     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
6199     * on its parent to request sending of the event to interested parties.
6200     * <p>
6201     * If an {@link AccessibilityDelegate} has been specified via calling
6202     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6203     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
6204     * responsible for handling this call.
6205     * </p>
6206     *
6207     * @param eventType The type of the event to send, as defined by several types from
6208     * {@link android.view.accessibility.AccessibilityEvent}, such as
6209     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
6210     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
6211     *
6212     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6213     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6214     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
6215     * @see AccessibilityDelegate
6216     */
6217    public void sendAccessibilityEvent(int eventType) {
6218        if (mAccessibilityDelegate != null) {
6219            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
6220        } else {
6221            sendAccessibilityEventInternal(eventType);
6222        }
6223    }
6224
6225    /**
6226     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
6227     * {@link AccessibilityEvent} to make an announcement which is related to some
6228     * sort of a context change for which none of the events representing UI transitions
6229     * is a good fit. For example, announcing a new page in a book. If accessibility
6230     * is not enabled this method does nothing.
6231     *
6232     * @param text The announcement text.
6233     */
6234    public void announceForAccessibility(CharSequence text) {
6235        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
6236            AccessibilityEvent event = AccessibilityEvent.obtain(
6237                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
6238            onInitializeAccessibilityEvent(event);
6239            event.getText().add(text);
6240            event.setContentDescription(null);
6241            mParent.requestSendAccessibilityEvent(this, event);
6242        }
6243    }
6244
6245    /**
6246     * @see #sendAccessibilityEvent(int)
6247     *
6248     * Note: Called from the default {@link AccessibilityDelegate}.
6249     *
6250     * @hide
6251     */
6252    public void sendAccessibilityEventInternal(int eventType) {
6253        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6254            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
6255        }
6256    }
6257
6258    /**
6259     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
6260     * takes as an argument an empty {@link AccessibilityEvent} and does not
6261     * perform a check whether accessibility is enabled.
6262     * <p>
6263     * If an {@link AccessibilityDelegate} has been specified via calling
6264     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6265     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
6266     * is responsible for handling this call.
6267     * </p>
6268     *
6269     * @param event The event to send.
6270     *
6271     * @see #sendAccessibilityEvent(int)
6272     */
6273    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
6274        if (mAccessibilityDelegate != null) {
6275            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
6276        } else {
6277            sendAccessibilityEventUncheckedInternal(event);
6278        }
6279    }
6280
6281    /**
6282     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
6283     *
6284     * Note: Called from the default {@link AccessibilityDelegate}.
6285     *
6286     * @hide
6287     */
6288    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
6289        if (!isShown()) {
6290            return;
6291        }
6292        onInitializeAccessibilityEvent(event);
6293        // Only a subset of accessibility events populates text content.
6294        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
6295            dispatchPopulateAccessibilityEvent(event);
6296        }
6297        // In the beginning we called #isShown(), so we know that getParent() is not null.
6298        getParent().requestSendAccessibilityEvent(this, event);
6299    }
6300
6301    /**
6302     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
6303     * to its children for adding their text content to the event. Note that the
6304     * event text is populated in a separate dispatch path since we add to the
6305     * event not only the text of the source but also the text of all its descendants.
6306     * A typical implementation will call
6307     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
6308     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6309     * on each child. Override this method if custom population of the event text
6310     * content is required.
6311     * <p>
6312     * If an {@link AccessibilityDelegate} has been specified via calling
6313     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6314     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
6315     * is responsible for handling this call.
6316     * </p>
6317     * <p>
6318     * <em>Note:</em> Accessibility events of certain types are not dispatched for
6319     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
6320     * </p>
6321     *
6322     * @param event The event.
6323     *
6324     * @return True if the event population was completed.
6325     */
6326    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
6327        if (mAccessibilityDelegate != null) {
6328            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
6329        } else {
6330            return dispatchPopulateAccessibilityEventInternal(event);
6331        }
6332    }
6333
6334    /**
6335     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6336     *
6337     * Note: Called from the default {@link AccessibilityDelegate}.
6338     *
6339     * @hide
6340     */
6341    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6342        onPopulateAccessibilityEvent(event);
6343        return false;
6344    }
6345
6346    /**
6347     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
6348     * giving a chance to this View to populate the accessibility event with its
6349     * text content. While this method is free to modify event
6350     * attributes other than text content, doing so should normally be performed in
6351     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
6352     * <p>
6353     * Example: Adding formatted date string to an accessibility event in addition
6354     *          to the text added by the super implementation:
6355     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6356     *     super.onPopulateAccessibilityEvent(event);
6357     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
6358     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
6359     *         mCurrentDate.getTimeInMillis(), flags);
6360     *     event.getText().add(selectedDateUtterance);
6361     * }</pre>
6362     * <p>
6363     * If an {@link AccessibilityDelegate} has been specified via calling
6364     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6365     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
6366     * is responsible for handling this call.
6367     * </p>
6368     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6369     * information to the event, in case the default implementation has basic information to add.
6370     * </p>
6371     *
6372     * @param event The accessibility event which to populate.
6373     *
6374     * @see #sendAccessibilityEvent(int)
6375     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6376     */
6377    @CallSuper
6378    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
6379        if (mAccessibilityDelegate != null) {
6380            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
6381        } else {
6382            onPopulateAccessibilityEventInternal(event);
6383        }
6384    }
6385
6386    /**
6387     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
6388     *
6389     * Note: Called from the default {@link AccessibilityDelegate}.
6390     *
6391     * @hide
6392     */
6393    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
6394    }
6395
6396    /**
6397     * Initializes an {@link AccessibilityEvent} with information about
6398     * this View which is the event source. In other words, the source of
6399     * an accessibility event is the view whose state change triggered firing
6400     * the event.
6401     * <p>
6402     * Example: Setting the password property of an event in addition
6403     *          to properties set by the super implementation:
6404     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6405     *     super.onInitializeAccessibilityEvent(event);
6406     *     event.setPassword(true);
6407     * }</pre>
6408     * <p>
6409     * If an {@link AccessibilityDelegate} has been specified via calling
6410     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6411     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
6412     * is responsible for handling this call.
6413     * </p>
6414     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
6415     * information to the event, in case the default implementation has basic information to add.
6416     * </p>
6417     * @param event The event to initialize.
6418     *
6419     * @see #sendAccessibilityEvent(int)
6420     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
6421     */
6422    @CallSuper
6423    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
6424        if (mAccessibilityDelegate != null) {
6425            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
6426        } else {
6427            onInitializeAccessibilityEventInternal(event);
6428        }
6429    }
6430
6431    /**
6432     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
6433     *
6434     * Note: Called from the default {@link AccessibilityDelegate}.
6435     *
6436     * @hide
6437     */
6438    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
6439        event.setSource(this);
6440        event.setClassName(getAccessibilityClassName());
6441        event.setPackageName(getContext().getPackageName());
6442        event.setEnabled(isEnabled());
6443        event.setContentDescription(mContentDescription);
6444
6445        switch (event.getEventType()) {
6446            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
6447                ArrayList<View> focusablesTempList = (mAttachInfo != null)
6448                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
6449                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
6450                event.setItemCount(focusablesTempList.size());
6451                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
6452                if (mAttachInfo != null) {
6453                    focusablesTempList.clear();
6454                }
6455            } break;
6456            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
6457                CharSequence text = getIterableTextForAccessibility();
6458                if (text != null && text.length() > 0) {
6459                    event.setFromIndex(getAccessibilitySelectionStart());
6460                    event.setToIndex(getAccessibilitySelectionEnd());
6461                    event.setItemCount(text.length());
6462                }
6463            } break;
6464        }
6465    }
6466
6467    /**
6468     * Returns an {@link AccessibilityNodeInfo} representing this view from the
6469     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
6470     * This method is responsible for obtaining an accessibility node info from a
6471     * pool of reusable instances and calling
6472     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
6473     * initialize the former.
6474     * <p>
6475     * Note: The client is responsible for recycling the obtained instance by calling
6476     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
6477     * </p>
6478     *
6479     * @return A populated {@link AccessibilityNodeInfo}.
6480     *
6481     * @see AccessibilityNodeInfo
6482     */
6483    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
6484        if (mAccessibilityDelegate != null) {
6485            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
6486        } else {
6487            return createAccessibilityNodeInfoInternal();
6488        }
6489    }
6490
6491    /**
6492     * @see #createAccessibilityNodeInfo()
6493     *
6494     * @hide
6495     */
6496    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
6497        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6498        if (provider != null) {
6499            return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID);
6500        } else {
6501            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
6502            onInitializeAccessibilityNodeInfo(info);
6503            return info;
6504        }
6505    }
6506
6507    /**
6508     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
6509     * The base implementation sets:
6510     * <ul>
6511     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
6512     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
6513     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
6514     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
6515     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
6516     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
6517     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
6518     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
6519     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
6520     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
6521     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
6522     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
6523     *   <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li>
6524     * </ul>
6525     * <p>
6526     * Subclasses should override this method, call the super implementation,
6527     * and set additional attributes.
6528     * </p>
6529     * <p>
6530     * If an {@link AccessibilityDelegate} has been specified via calling
6531     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6532     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
6533     * is responsible for handling this call.
6534     * </p>
6535     *
6536     * @param info The instance to initialize.
6537     */
6538    @CallSuper
6539    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
6540        if (mAccessibilityDelegate != null) {
6541            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
6542        } else {
6543            onInitializeAccessibilityNodeInfoInternal(info);
6544        }
6545    }
6546
6547    /**
6548     * Gets the location of this view in screen coordinates.
6549     *
6550     * @param outRect The output location
6551     * @hide
6552     */
6553    public void getBoundsOnScreen(Rect outRect) {
6554        getBoundsOnScreen(outRect, false);
6555    }
6556
6557    /**
6558     * Gets the location of this view in screen coordinates.
6559     *
6560     * @param outRect The output location
6561     * @param clipToParent Whether to clip child bounds to the parent ones.
6562     * @hide
6563     */
6564    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
6565        if (mAttachInfo == null) {
6566            return;
6567        }
6568
6569        RectF position = mAttachInfo.mTmpTransformRect;
6570        position.set(0, 0, mRight - mLeft, mBottom - mTop);
6571
6572        if (!hasIdentityMatrix()) {
6573            getMatrix().mapRect(position);
6574        }
6575
6576        position.offset(mLeft, mTop);
6577
6578        ViewParent parent = mParent;
6579        while (parent instanceof View) {
6580            View parentView = (View) parent;
6581
6582            position.offset(-parentView.mScrollX, -parentView.mScrollY);
6583
6584            if (clipToParent) {
6585                position.left = Math.max(position.left, 0);
6586                position.top = Math.max(position.top, 0);
6587                position.right = Math.min(position.right, parentView.getWidth());
6588                position.bottom = Math.min(position.bottom, parentView.getHeight());
6589            }
6590
6591            if (!parentView.hasIdentityMatrix()) {
6592                parentView.getMatrix().mapRect(position);
6593            }
6594
6595            position.offset(parentView.mLeft, parentView.mTop);
6596
6597            parent = parentView.mParent;
6598        }
6599
6600        if (parent instanceof ViewRootImpl) {
6601            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
6602            position.offset(0, -viewRootImpl.mCurScrollY);
6603        }
6604
6605        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6606
6607        outRect.set(Math.round(position.left), Math.round(position.top),
6608                Math.round(position.right), Math.round(position.bottom));
6609    }
6610
6611    /**
6612     * Return the class name of this object to be used for accessibility purposes.
6613     * Subclasses should only override this if they are implementing something that
6614     * should be seen as a completely new class of view when used by accessibility,
6615     * unrelated to the class it is deriving from.  This is used to fill in
6616     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
6617     */
6618    public CharSequence getAccessibilityClassName() {
6619        return View.class.getName();
6620    }
6621
6622    /**
6623     * Called when assist structure is being retrieved from a view as part of
6624     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
6625     * @param structure Fill in with structured view data.  The default implementation
6626     * fills in all data that can be inferred from the view itself.
6627     */
6628    public void onProvideStructure(ViewStructure structure) {
6629        final int id = mID;
6630        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
6631                && (id&0x0000ffff) != 0) {
6632            String pkg, type, entry;
6633            try {
6634                final Resources res = getResources();
6635                entry = res.getResourceEntryName(id);
6636                type = res.getResourceTypeName(id);
6637                pkg = res.getResourcePackageName(id);
6638            } catch (Resources.NotFoundException e) {
6639                entry = type = pkg = null;
6640            }
6641            structure.setId(id, pkg, type, entry);
6642        } else {
6643            structure.setId(id, null, null, null);
6644        }
6645        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
6646        if (!hasIdentityMatrix()) {
6647            structure.setTransformation(getMatrix());
6648        }
6649        structure.setElevation(getZ());
6650        structure.setVisibility(getVisibility());
6651        structure.setEnabled(isEnabled());
6652        if (isClickable()) {
6653            structure.setClickable(true);
6654        }
6655        if (isFocusable()) {
6656            structure.setFocusable(true);
6657        }
6658        if (isFocused()) {
6659            structure.setFocused(true);
6660        }
6661        if (isAccessibilityFocused()) {
6662            structure.setAccessibilityFocused(true);
6663        }
6664        if (isSelected()) {
6665            structure.setSelected(true);
6666        }
6667        if (isActivated()) {
6668            structure.setActivated(true);
6669        }
6670        if (isLongClickable()) {
6671            structure.setLongClickable(true);
6672        }
6673        if (this instanceof Checkable) {
6674            structure.setCheckable(true);
6675            if (((Checkable)this).isChecked()) {
6676                structure.setChecked(true);
6677            }
6678        }
6679        if (isContextClickable()) {
6680            structure.setContextClickable(true);
6681        }
6682        structure.setClassName(getAccessibilityClassName().toString());
6683        structure.setContentDescription(getContentDescription());
6684    }
6685
6686    /**
6687     * Called when assist structure is being retrieved from a view as part of
6688     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
6689     * generate additional virtual structure under this view.  The defaullt implementation
6690     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
6691     * view's virtual accessibility nodes, if any.  You can override this for a more
6692     * optimal implementation providing this data.
6693     */
6694    public void onProvideVirtualStructure(ViewStructure structure) {
6695        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
6696        if (provider != null) {
6697            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
6698            structure.setChildCount(1);
6699            ViewStructure root = structure.newChild(0);
6700            populateVirtualStructure(root, provider, info);
6701            info.recycle();
6702        }
6703    }
6704
6705    private void populateVirtualStructure(ViewStructure structure,
6706            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
6707        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
6708                null, null, null);
6709        Rect rect = structure.getTempRect();
6710        info.getBoundsInParent(rect);
6711        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
6712        structure.setVisibility(VISIBLE);
6713        structure.setEnabled(info.isEnabled());
6714        if (info.isClickable()) {
6715            structure.setClickable(true);
6716        }
6717        if (info.isFocusable()) {
6718            structure.setFocusable(true);
6719        }
6720        if (info.isFocused()) {
6721            structure.setFocused(true);
6722        }
6723        if (info.isAccessibilityFocused()) {
6724            structure.setAccessibilityFocused(true);
6725        }
6726        if (info.isSelected()) {
6727            structure.setSelected(true);
6728        }
6729        if (info.isLongClickable()) {
6730            structure.setLongClickable(true);
6731        }
6732        if (info.isCheckable()) {
6733            structure.setCheckable(true);
6734            if (info.isChecked()) {
6735                structure.setChecked(true);
6736            }
6737        }
6738        if (info.isContextClickable()) {
6739            structure.setContextClickable(true);
6740        }
6741        CharSequence cname = info.getClassName();
6742        structure.setClassName(cname != null ? cname.toString() : null);
6743        structure.setContentDescription(info.getContentDescription());
6744        if (info.getText() != null || info.getError() != null) {
6745            structure.setText(info.getText(), info.getTextSelectionStart(),
6746                    info.getTextSelectionEnd());
6747        }
6748        final int NCHILDREN = info.getChildCount();
6749        if (NCHILDREN > 0) {
6750            structure.setChildCount(NCHILDREN);
6751            for (int i=0; i<NCHILDREN; i++) {
6752                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6753                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6754                ViewStructure child = structure.newChild(i);
6755                populateVirtualStructure(child, provider, cinfo);
6756                cinfo.recycle();
6757            }
6758        }
6759    }
6760
6761    /**
6762     * Dispatch creation of {@link ViewStructure} down the hierarchy.  The default
6763     * implementation calls {@link #onProvideStructure} and
6764     * {@link #onProvideVirtualStructure}.
6765     */
6766    public void dispatchProvideStructure(ViewStructure structure) {
6767        if (!isAssistBlocked()) {
6768            onProvideStructure(structure);
6769            onProvideVirtualStructure(structure);
6770        } else {
6771            structure.setClassName(getAccessibilityClassName().toString());
6772            structure.setAssistBlocked(true);
6773        }
6774    }
6775
6776    /**
6777     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6778     *
6779     * Note: Called from the default {@link AccessibilityDelegate}.
6780     *
6781     * @hide
6782     */
6783    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6784        if (mAttachInfo == null) {
6785            return;
6786        }
6787
6788        Rect bounds = mAttachInfo.mTmpInvalRect;
6789
6790        getDrawingRect(bounds);
6791        info.setBoundsInParent(bounds);
6792
6793        getBoundsOnScreen(bounds, true);
6794        info.setBoundsInScreen(bounds);
6795
6796        ViewParent parent = getParentForAccessibility();
6797        if (parent instanceof View) {
6798            info.setParent((View) parent);
6799        }
6800
6801        if (mID != View.NO_ID) {
6802            View rootView = getRootView();
6803            if (rootView == null) {
6804                rootView = this;
6805            }
6806
6807            View label = rootView.findLabelForView(this, mID);
6808            if (label != null) {
6809                info.setLabeledBy(label);
6810            }
6811
6812            if ((mAttachInfo.mAccessibilityFetchFlags
6813                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6814                    && Resources.resourceHasPackage(mID)) {
6815                try {
6816                    String viewId = getResources().getResourceName(mID);
6817                    info.setViewIdResourceName(viewId);
6818                } catch (Resources.NotFoundException nfe) {
6819                    /* ignore */
6820                }
6821            }
6822        }
6823
6824        if (mLabelForId != View.NO_ID) {
6825            View rootView = getRootView();
6826            if (rootView == null) {
6827                rootView = this;
6828            }
6829            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6830            if (labeled != null) {
6831                info.setLabelFor(labeled);
6832            }
6833        }
6834
6835        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6836            View rootView = getRootView();
6837            if (rootView == null) {
6838                rootView = this;
6839            }
6840            View next = rootView.findViewInsideOutShouldExist(this,
6841                    mAccessibilityTraversalBeforeId);
6842            if (next != null && next.includeForAccessibility()) {
6843                info.setTraversalBefore(next);
6844            }
6845        }
6846
6847        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6848            View rootView = getRootView();
6849            if (rootView == null) {
6850                rootView = this;
6851            }
6852            View next = rootView.findViewInsideOutShouldExist(this,
6853                    mAccessibilityTraversalAfterId);
6854            if (next != null && next.includeForAccessibility()) {
6855                info.setTraversalAfter(next);
6856            }
6857        }
6858
6859        info.setVisibleToUser(isVisibleToUser());
6860
6861        if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags
6862                & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) {
6863            info.setImportantForAccessibility(isImportantForAccessibility());
6864        } else {
6865            info.setImportantForAccessibility(true);
6866        }
6867
6868        info.setPackageName(mContext.getPackageName());
6869        info.setClassName(getAccessibilityClassName());
6870        info.setContentDescription(getContentDescription());
6871
6872        info.setEnabled(isEnabled());
6873        info.setClickable(isClickable());
6874        info.setFocusable(isFocusable());
6875        info.setFocused(isFocused());
6876        info.setAccessibilityFocused(isAccessibilityFocused());
6877        info.setSelected(isSelected());
6878        info.setLongClickable(isLongClickable());
6879        info.setContextClickable(isContextClickable());
6880        info.setLiveRegion(getAccessibilityLiveRegion());
6881
6882        // TODO: These make sense only if we are in an AdapterView but all
6883        // views can be selected. Maybe from accessibility perspective
6884        // we should report as selectable view in an AdapterView.
6885        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6886        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6887
6888        if (isFocusable()) {
6889            if (isFocused()) {
6890                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6891            } else {
6892                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6893            }
6894        }
6895
6896        if (!isAccessibilityFocused()) {
6897            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6898        } else {
6899            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6900        }
6901
6902        if (isClickable() && isEnabled()) {
6903            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6904        }
6905
6906        if (isLongClickable() && isEnabled()) {
6907            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6908        }
6909
6910        if (isContextClickable() && isEnabled()) {
6911            info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK);
6912        }
6913
6914        CharSequence text = getIterableTextForAccessibility();
6915        if (text != null && text.length() > 0) {
6916            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6917
6918            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6919            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6920            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6921            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6922                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6923                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6924        }
6925
6926        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6927        populateAccessibilityNodeInfoDrawingOrderInParent(info);
6928    }
6929
6930    /**
6931     * Determine the order in which this view will be drawn relative to its siblings for a11y
6932     *
6933     * @param info The info whose drawing order should be populated
6934     */
6935    private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) {
6936        /*
6937         * If the view's bounds haven't been set yet, layout has not completed. In that situation,
6938         * drawing order may not be well-defined, and some Views with custom drawing order may
6939         * not be initialized sufficiently to respond properly getChildDrawingOrder.
6940         */
6941        if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) {
6942            info.setDrawingOrder(0);
6943            return;
6944        }
6945        int drawingOrderInParent = 1;
6946        // Iterate up the hierarchy if parents are not important for a11y
6947        View viewAtDrawingLevel = this;
6948        final ViewParent parent = getParentForAccessibility();
6949        while (viewAtDrawingLevel != parent) {
6950            final ViewParent currentParent = viewAtDrawingLevel.getParent();
6951            if (!(currentParent instanceof ViewGroup)) {
6952                // Should only happen for the Decor
6953                drawingOrderInParent = 0;
6954                break;
6955            } else {
6956                final ViewGroup parentGroup = (ViewGroup) currentParent;
6957                final int childCount = parentGroup.getChildCount();
6958                if (childCount > 1) {
6959                    List<View> preorderedList = parentGroup.buildOrderedChildList();
6960                    if (preorderedList != null) {
6961                        final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel);
6962                        for (int i = 0; i < childDrawIndex; i++) {
6963                            drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i));
6964                        }
6965                    } else {
6966                        final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel);
6967                        final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled();
6968                        final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup
6969                                .getChildDrawingOrder(childCount, childIndex) : childIndex;
6970                        final int numChildrenToIterate = customOrder ? childCount : childDrawIndex;
6971                        if (childDrawIndex != 0) {
6972                            for (int i = 0; i < numChildrenToIterate; i++) {
6973                                final int otherDrawIndex = (customOrder ?
6974                                        parentGroup.getChildDrawingOrder(childCount, i) : i);
6975                                if (otherDrawIndex < childDrawIndex) {
6976                                    drawingOrderInParent +=
6977                                            numViewsForAccessibility(parentGroup.getChildAt(i));
6978                                }
6979                            }
6980                        }
6981                    }
6982                }
6983            }
6984            viewAtDrawingLevel = (View) currentParent;
6985        }
6986        info.setDrawingOrder(drawingOrderInParent);
6987    }
6988
6989    private static int numViewsForAccessibility(View view) {
6990        if (view != null) {
6991            if (view.includeForAccessibility()) {
6992                return 1;
6993            } else if (view instanceof ViewGroup) {
6994                return ((ViewGroup) view).getNumChildrenForAccessibility();
6995            }
6996        }
6997        return 0;
6998    }
6999
7000    private View findLabelForView(View view, int labeledId) {
7001        if (mMatchLabelForPredicate == null) {
7002            mMatchLabelForPredicate = new MatchLabelForPredicate();
7003        }
7004        mMatchLabelForPredicate.mLabeledId = labeledId;
7005        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
7006    }
7007
7008    /**
7009     * Computes whether this view is visible to the user. Such a view is
7010     * attached, visible, all its predecessors are visible, it is not clipped
7011     * entirely by its predecessors, and has an alpha greater than zero.
7012     *
7013     * @return Whether the view is visible on the screen.
7014     *
7015     * @hide
7016     */
7017    protected boolean isVisibleToUser() {
7018        return isVisibleToUser(null);
7019    }
7020
7021    /**
7022     * Computes whether the given portion of this view is visible to the user.
7023     * Such a view is attached, visible, all its predecessors are visible,
7024     * has an alpha greater than zero, and the specified portion is not
7025     * clipped entirely by its predecessors.
7026     *
7027     * @param boundInView the portion of the view to test; coordinates should be relative; may be
7028     *                    <code>null</code>, and the entire view will be tested in this case.
7029     *                    When <code>true</code> is returned by the function, the actual visible
7030     *                    region will be stored in this parameter; that is, if boundInView is fully
7031     *                    contained within the view, no modification will be made, otherwise regions
7032     *                    outside of the visible area of the view will be clipped.
7033     *
7034     * @return Whether the specified portion of the view is visible on the screen.
7035     *
7036     * @hide
7037     */
7038    protected boolean isVisibleToUser(Rect boundInView) {
7039        if (mAttachInfo != null) {
7040            // Attached to invisible window means this view is not visible.
7041            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
7042                return false;
7043            }
7044            // An invisible predecessor or one with alpha zero means
7045            // that this view is not visible to the user.
7046            Object current = this;
7047            while (current instanceof View) {
7048                View view = (View) current;
7049                // We have attach info so this view is attached and there is no
7050                // need to check whether we reach to ViewRootImpl on the way up.
7051                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
7052                        view.getVisibility() != VISIBLE) {
7053                    return false;
7054                }
7055                current = view.mParent;
7056            }
7057            // Check if the view is entirely covered by its predecessors.
7058            Rect visibleRect = mAttachInfo.mTmpInvalRect;
7059            Point offset = mAttachInfo.mPoint;
7060            if (!getGlobalVisibleRect(visibleRect, offset)) {
7061                return false;
7062            }
7063            // Check if the visible portion intersects the rectangle of interest.
7064            if (boundInView != null) {
7065                visibleRect.offset(-offset.x, -offset.y);
7066                return boundInView.intersect(visibleRect);
7067            }
7068            return true;
7069        }
7070        return false;
7071    }
7072
7073    /**
7074     * Returns the delegate for implementing accessibility support via
7075     * composition. For more details see {@link AccessibilityDelegate}.
7076     *
7077     * @return The delegate, or null if none set.
7078     *
7079     * @hide
7080     */
7081    public AccessibilityDelegate getAccessibilityDelegate() {
7082        return mAccessibilityDelegate;
7083    }
7084
7085    /**
7086     * Sets a delegate for implementing accessibility support via composition
7087     * (as opposed to inheritance). For more details, see
7088     * {@link AccessibilityDelegate}.
7089     * <p>
7090     * <strong>Note:</strong> On platform versions prior to
7091     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
7092     * views in the {@code android.widget.*} package are called <i>before</i>
7093     * host methods. This prevents certain properties such as class name from
7094     * being modified by overriding
7095     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
7096     * as any changes will be overwritten by the host class.
7097     * <p>
7098     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
7099     * methods are called <i>after</i> host methods, which all properties to be
7100     * modified without being overwritten by the host class.
7101     *
7102     * @param delegate the object to which accessibility method calls should be
7103     *                 delegated
7104     * @see AccessibilityDelegate
7105     */
7106    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
7107        mAccessibilityDelegate = delegate;
7108    }
7109
7110    /**
7111     * Gets the provider for managing a virtual view hierarchy rooted at this View
7112     * and reported to {@link android.accessibilityservice.AccessibilityService}s
7113     * that explore the window content.
7114     * <p>
7115     * If this method returns an instance, this instance is responsible for managing
7116     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
7117     * View including the one representing the View itself. Similarly the returned
7118     * instance is responsible for performing accessibility actions on any virtual
7119     * view or the root view itself.
7120     * </p>
7121     * <p>
7122     * If an {@link AccessibilityDelegate} has been specified via calling
7123     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7124     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
7125     * is responsible for handling this call.
7126     * </p>
7127     *
7128     * @return The provider.
7129     *
7130     * @see AccessibilityNodeProvider
7131     */
7132    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
7133        if (mAccessibilityDelegate != null) {
7134            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
7135        } else {
7136            return null;
7137        }
7138    }
7139
7140    /**
7141     * Gets the unique identifier of this view on the screen for accessibility purposes.
7142     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
7143     *
7144     * @return The view accessibility id.
7145     *
7146     * @hide
7147     */
7148    public int getAccessibilityViewId() {
7149        if (mAccessibilityViewId == NO_ID) {
7150            mAccessibilityViewId = sNextAccessibilityViewId++;
7151        }
7152        return mAccessibilityViewId;
7153    }
7154
7155    /**
7156     * Gets the unique identifier of the window in which this View reseides.
7157     *
7158     * @return The window accessibility id.
7159     *
7160     * @hide
7161     */
7162    public int getAccessibilityWindowId() {
7163        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
7164                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7165    }
7166
7167    /**
7168     * Returns the {@link View}'s content description.
7169     * <p>
7170     * <strong>Note:</strong> Do not override this method, as it will have no
7171     * effect on the content description presented to accessibility services.
7172     * You must call {@link #setContentDescription(CharSequence)} to modify the
7173     * content description.
7174     *
7175     * @return the content description
7176     * @see #setContentDescription(CharSequence)
7177     * @attr ref android.R.styleable#View_contentDescription
7178     */
7179    @ViewDebug.ExportedProperty(category = "accessibility")
7180    public CharSequence getContentDescription() {
7181        return mContentDescription;
7182    }
7183
7184    /**
7185     * Sets the {@link View}'s content description.
7186     * <p>
7187     * A content description briefly describes the view and is primarily used
7188     * for accessibility support to determine how a view should be presented to
7189     * the user. In the case of a view with no textual representation, such as
7190     * {@link android.widget.ImageButton}, a useful content description
7191     * explains what the view does. For example, an image button with a phone
7192     * icon that is used to place a call may use "Call" as its content
7193     * description. An image of a floppy disk that is used to save a file may
7194     * use "Save".
7195     *
7196     * @param contentDescription The content description.
7197     * @see #getContentDescription()
7198     * @attr ref android.R.styleable#View_contentDescription
7199     */
7200    @RemotableViewMethod
7201    public void setContentDescription(CharSequence contentDescription) {
7202        if (mContentDescription == null) {
7203            if (contentDescription == null) {
7204                return;
7205            }
7206        } else if (mContentDescription.equals(contentDescription)) {
7207            return;
7208        }
7209        mContentDescription = contentDescription;
7210        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
7211        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
7212            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
7213            notifySubtreeAccessibilityStateChangedIfNeeded();
7214        } else {
7215            notifyViewAccessibilityStateChangedIfNeeded(
7216                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
7217        }
7218    }
7219
7220    /**
7221     * Sets the id of a view before which this one is visited in accessibility traversal.
7222     * A screen-reader must visit the content of this view before the content of the one
7223     * it precedes. For example, if view B is set to be before view A, then a screen-reader
7224     * will traverse the entire content of B before traversing the entire content of A,
7225     * regardles of what traversal strategy it is using.
7226     * <p>
7227     * Views that do not have specified before/after relationships are traversed in order
7228     * determined by the screen-reader.
7229     * </p>
7230     * <p>
7231     * Setting that this view is before a view that is not important for accessibility
7232     * or if this view is not important for accessibility will have no effect as the
7233     * screen-reader is not aware of unimportant views.
7234     * </p>
7235     *
7236     * @param beforeId The id of a view this one precedes in accessibility traversal.
7237     *
7238     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
7239     *
7240     * @see #setImportantForAccessibility(int)
7241     */
7242    @RemotableViewMethod
7243    public void setAccessibilityTraversalBefore(int beforeId) {
7244        if (mAccessibilityTraversalBeforeId == beforeId) {
7245            return;
7246        }
7247        mAccessibilityTraversalBeforeId = beforeId;
7248        notifyViewAccessibilityStateChangedIfNeeded(
7249                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7250    }
7251
7252    /**
7253     * Gets the id of a view before which this one is visited in accessibility traversal.
7254     *
7255     * @return The id of a view this one precedes in accessibility traversal if
7256     *         specified, otherwise {@link #NO_ID}.
7257     *
7258     * @see #setAccessibilityTraversalBefore(int)
7259     */
7260    public int getAccessibilityTraversalBefore() {
7261        return mAccessibilityTraversalBeforeId;
7262    }
7263
7264    /**
7265     * Sets the id of a view after which this one is visited in accessibility traversal.
7266     * A screen-reader must visit the content of the other view before the content of this
7267     * one. For example, if view B is set to be after view A, then a screen-reader
7268     * will traverse the entire content of A before traversing the entire content of B,
7269     * regardles of what traversal strategy it is using.
7270     * <p>
7271     * Views that do not have specified before/after relationships are traversed in order
7272     * determined by the screen-reader.
7273     * </p>
7274     * <p>
7275     * Setting that this view is after a view that is not important for accessibility
7276     * or if this view is not important for accessibility will have no effect as the
7277     * screen-reader is not aware of unimportant views.
7278     * </p>
7279     *
7280     * @param afterId The id of a view this one succedees in accessibility traversal.
7281     *
7282     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
7283     *
7284     * @see #setImportantForAccessibility(int)
7285     */
7286    @RemotableViewMethod
7287    public void setAccessibilityTraversalAfter(int afterId) {
7288        if (mAccessibilityTraversalAfterId == afterId) {
7289            return;
7290        }
7291        mAccessibilityTraversalAfterId = afterId;
7292        notifyViewAccessibilityStateChangedIfNeeded(
7293                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7294    }
7295
7296    /**
7297     * Gets the id of a view after which this one is visited in accessibility traversal.
7298     *
7299     * @return The id of a view this one succeedes in accessibility traversal if
7300     *         specified, otherwise {@link #NO_ID}.
7301     *
7302     * @see #setAccessibilityTraversalAfter(int)
7303     */
7304    public int getAccessibilityTraversalAfter() {
7305        return mAccessibilityTraversalAfterId;
7306    }
7307
7308    /**
7309     * Gets the id of a view for which this view serves as a label for
7310     * accessibility purposes.
7311     *
7312     * @return The labeled view id.
7313     */
7314    @ViewDebug.ExportedProperty(category = "accessibility")
7315    public int getLabelFor() {
7316        return mLabelForId;
7317    }
7318
7319    /**
7320     * Sets the id of a view for which this view serves as a label for
7321     * accessibility purposes.
7322     *
7323     * @param id The labeled view id.
7324     */
7325    @RemotableViewMethod
7326    public void setLabelFor(@IdRes int id) {
7327        if (mLabelForId == id) {
7328            return;
7329        }
7330        mLabelForId = id;
7331        if (mLabelForId != View.NO_ID
7332                && mID == View.NO_ID) {
7333            mID = generateViewId();
7334        }
7335        notifyViewAccessibilityStateChangedIfNeeded(
7336                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7337    }
7338
7339    /**
7340     * Invoked whenever this view loses focus, either by losing window focus or by losing
7341     * focus within its window. This method can be used to clear any state tied to the
7342     * focus. For instance, if a button is held pressed with the trackball and the window
7343     * loses focus, this method can be used to cancel the press.
7344     *
7345     * Subclasses of View overriding this method should always call super.onFocusLost().
7346     *
7347     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
7348     * @see #onWindowFocusChanged(boolean)
7349     *
7350     * @hide pending API council approval
7351     */
7352    @CallSuper
7353    protected void onFocusLost() {
7354        resetPressedState();
7355    }
7356
7357    private void resetPressedState() {
7358        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7359            return;
7360        }
7361
7362        if (isPressed()) {
7363            setPressed(false);
7364
7365            if (!mHasPerformedLongPress) {
7366                removeLongPressCallback();
7367            }
7368        }
7369    }
7370
7371    /**
7372     * Returns true if this view has focus
7373     *
7374     * @return True if this view has focus, false otherwise.
7375     */
7376    @ViewDebug.ExportedProperty(category = "focus")
7377    public boolean isFocused() {
7378        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
7379    }
7380
7381    /**
7382     * Find the view in the hierarchy rooted at this view that currently has
7383     * focus.
7384     *
7385     * @return The view that currently has focus, or null if no focused view can
7386     *         be found.
7387     */
7388    public View findFocus() {
7389        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
7390    }
7391
7392    /**
7393     * Indicates whether this view is one of the set of scrollable containers in
7394     * its window.
7395     *
7396     * @return whether this view is one of the set of scrollable containers in
7397     * its window
7398     *
7399     * @attr ref android.R.styleable#View_isScrollContainer
7400     */
7401    public boolean isScrollContainer() {
7402        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
7403    }
7404
7405    /**
7406     * Change whether this view is one of the set of scrollable containers in
7407     * its window.  This will be used to determine whether the window can
7408     * resize or must pan when a soft input area is open -- scrollable
7409     * containers allow the window to use resize mode since the container
7410     * will appropriately shrink.
7411     *
7412     * @attr ref android.R.styleable#View_isScrollContainer
7413     */
7414    public void setScrollContainer(boolean isScrollContainer) {
7415        if (isScrollContainer) {
7416            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
7417                mAttachInfo.mScrollContainers.add(this);
7418                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
7419            }
7420            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
7421        } else {
7422            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
7423                mAttachInfo.mScrollContainers.remove(this);
7424            }
7425            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
7426        }
7427    }
7428
7429    /**
7430     * Returns the quality of the drawing cache.
7431     *
7432     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7433     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7434     *
7435     * @see #setDrawingCacheQuality(int)
7436     * @see #setDrawingCacheEnabled(boolean)
7437     * @see #isDrawingCacheEnabled()
7438     *
7439     * @attr ref android.R.styleable#View_drawingCacheQuality
7440     */
7441    @DrawingCacheQuality
7442    public int getDrawingCacheQuality() {
7443        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
7444    }
7445
7446    /**
7447     * Set the drawing cache quality of this view. This value is used only when the
7448     * drawing cache is enabled
7449     *
7450     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
7451     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
7452     *
7453     * @see #getDrawingCacheQuality()
7454     * @see #setDrawingCacheEnabled(boolean)
7455     * @see #isDrawingCacheEnabled()
7456     *
7457     * @attr ref android.R.styleable#View_drawingCacheQuality
7458     */
7459    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
7460        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
7461    }
7462
7463    /**
7464     * Returns whether the screen should remain on, corresponding to the current
7465     * value of {@link #KEEP_SCREEN_ON}.
7466     *
7467     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
7468     *
7469     * @see #setKeepScreenOn(boolean)
7470     *
7471     * @attr ref android.R.styleable#View_keepScreenOn
7472     */
7473    public boolean getKeepScreenOn() {
7474        return (mViewFlags & KEEP_SCREEN_ON) != 0;
7475    }
7476
7477    /**
7478     * Controls whether the screen should remain on, modifying the
7479     * value of {@link #KEEP_SCREEN_ON}.
7480     *
7481     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
7482     *
7483     * @see #getKeepScreenOn()
7484     *
7485     * @attr ref android.R.styleable#View_keepScreenOn
7486     */
7487    public void setKeepScreenOn(boolean keepScreenOn) {
7488        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
7489    }
7490
7491    /**
7492     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7493     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7494     *
7495     * @attr ref android.R.styleable#View_nextFocusLeft
7496     */
7497    public int getNextFocusLeftId() {
7498        return mNextFocusLeftId;
7499    }
7500
7501    /**
7502     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
7503     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
7504     * decide automatically.
7505     *
7506     * @attr ref android.R.styleable#View_nextFocusLeft
7507     */
7508    public void setNextFocusLeftId(int nextFocusLeftId) {
7509        mNextFocusLeftId = nextFocusLeftId;
7510    }
7511
7512    /**
7513     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7514     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7515     *
7516     * @attr ref android.R.styleable#View_nextFocusRight
7517     */
7518    public int getNextFocusRightId() {
7519        return mNextFocusRightId;
7520    }
7521
7522    /**
7523     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
7524     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
7525     * decide automatically.
7526     *
7527     * @attr ref android.R.styleable#View_nextFocusRight
7528     */
7529    public void setNextFocusRightId(int nextFocusRightId) {
7530        mNextFocusRightId = nextFocusRightId;
7531    }
7532
7533    /**
7534     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7535     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7536     *
7537     * @attr ref android.R.styleable#View_nextFocusUp
7538     */
7539    public int getNextFocusUpId() {
7540        return mNextFocusUpId;
7541    }
7542
7543    /**
7544     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
7545     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
7546     * decide automatically.
7547     *
7548     * @attr ref android.R.styleable#View_nextFocusUp
7549     */
7550    public void setNextFocusUpId(int nextFocusUpId) {
7551        mNextFocusUpId = nextFocusUpId;
7552    }
7553
7554    /**
7555     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7556     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7557     *
7558     * @attr ref android.R.styleable#View_nextFocusDown
7559     */
7560    public int getNextFocusDownId() {
7561        return mNextFocusDownId;
7562    }
7563
7564    /**
7565     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
7566     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
7567     * decide automatically.
7568     *
7569     * @attr ref android.R.styleable#View_nextFocusDown
7570     */
7571    public void setNextFocusDownId(int nextFocusDownId) {
7572        mNextFocusDownId = nextFocusDownId;
7573    }
7574
7575    /**
7576     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7577     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
7578     *
7579     * @attr ref android.R.styleable#View_nextFocusForward
7580     */
7581    public int getNextFocusForwardId() {
7582        return mNextFocusForwardId;
7583    }
7584
7585    /**
7586     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
7587     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
7588     * decide automatically.
7589     *
7590     * @attr ref android.R.styleable#View_nextFocusForward
7591     */
7592    public void setNextFocusForwardId(int nextFocusForwardId) {
7593        mNextFocusForwardId = nextFocusForwardId;
7594    }
7595
7596    /**
7597     * Returns the visibility of this view and all of its ancestors
7598     *
7599     * @return True if this view and all of its ancestors are {@link #VISIBLE}
7600     */
7601    public boolean isShown() {
7602        View current = this;
7603        //noinspection ConstantConditions
7604        do {
7605            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7606                return false;
7607            }
7608            ViewParent parent = current.mParent;
7609            if (parent == null) {
7610                return false; // We are not attached to the view root
7611            }
7612            if (!(parent instanceof View)) {
7613                return true;
7614            }
7615            current = (View) parent;
7616        } while (current != null);
7617
7618        return false;
7619    }
7620
7621    /**
7622     * Called by the view hierarchy when the content insets for a window have
7623     * changed, to allow it to adjust its content to fit within those windows.
7624     * The content insets tell you the space that the status bar, input method,
7625     * and other system windows infringe on the application's window.
7626     *
7627     * <p>You do not normally need to deal with this function, since the default
7628     * window decoration given to applications takes care of applying it to the
7629     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
7630     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
7631     * and your content can be placed under those system elements.  You can then
7632     * use this method within your view hierarchy if you have parts of your UI
7633     * which you would like to ensure are not being covered.
7634     *
7635     * <p>The default implementation of this method simply applies the content
7636     * insets to the view's padding, consuming that content (modifying the
7637     * insets to be 0), and returning true.  This behavior is off by default, but can
7638     * be enabled through {@link #setFitsSystemWindows(boolean)}.
7639     *
7640     * <p>This function's traversal down the hierarchy is depth-first.  The same content
7641     * insets object is propagated down the hierarchy, so any changes made to it will
7642     * be seen by all following views (including potentially ones above in
7643     * the hierarchy since this is a depth-first traversal).  The first view
7644     * that returns true will abort the entire traversal.
7645     *
7646     * <p>The default implementation works well for a situation where it is
7647     * used with a container that covers the entire window, allowing it to
7648     * apply the appropriate insets to its content on all edges.  If you need
7649     * a more complicated layout (such as two different views fitting system
7650     * windows, one on the top of the window, and one on the bottom),
7651     * you can override the method and handle the insets however you would like.
7652     * Note that the insets provided by the framework are always relative to the
7653     * far edges of the window, not accounting for the location of the called view
7654     * within that window.  (In fact when this method is called you do not yet know
7655     * where the layout will place the view, as it is done before layout happens.)
7656     *
7657     * <p>Note: unlike many View methods, there is no dispatch phase to this
7658     * call.  If you are overriding it in a ViewGroup and want to allow the
7659     * call to continue to your children, you must be sure to call the super
7660     * implementation.
7661     *
7662     * <p>Here is a sample layout that makes use of fitting system windows
7663     * to have controls for a video view placed inside of the window decorations
7664     * that it hides and shows.  This can be used with code like the second
7665     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
7666     *
7667     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
7668     *
7669     * @param insets Current content insets of the window.  Prior to
7670     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
7671     * the insets or else you and Android will be unhappy.
7672     *
7673     * @return {@code true} if this view applied the insets and it should not
7674     * continue propagating further down the hierarchy, {@code false} otherwise.
7675     * @see #getFitsSystemWindows()
7676     * @see #setFitsSystemWindows(boolean)
7677     * @see #setSystemUiVisibility(int)
7678     *
7679     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
7680     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
7681     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
7682     * to implement handling their own insets.
7683     */
7684    @Deprecated
7685    protected boolean fitSystemWindows(Rect insets) {
7686        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
7687            if (insets == null) {
7688                // Null insets by definition have already been consumed.
7689                // This call cannot apply insets since there are none to apply,
7690                // so return false.
7691                return false;
7692            }
7693            // If we're not in the process of dispatching the newer apply insets call,
7694            // that means we're not in the compatibility path. Dispatch into the newer
7695            // apply insets path and take things from there.
7696            try {
7697                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
7698                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
7699            } finally {
7700                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
7701            }
7702        } else {
7703            // We're being called from the newer apply insets path.
7704            // Perform the standard fallback behavior.
7705            return fitSystemWindowsInt(insets);
7706        }
7707    }
7708
7709    private boolean fitSystemWindowsInt(Rect insets) {
7710        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
7711            mUserPaddingStart = UNDEFINED_PADDING;
7712            mUserPaddingEnd = UNDEFINED_PADDING;
7713            Rect localInsets = sThreadLocal.get();
7714            if (localInsets == null) {
7715                localInsets = new Rect();
7716                sThreadLocal.set(localInsets);
7717            }
7718            boolean res = computeFitSystemWindows(insets, localInsets);
7719            mUserPaddingLeftInitial = localInsets.left;
7720            mUserPaddingRightInitial = localInsets.right;
7721            internalSetPadding(localInsets.left, localInsets.top,
7722                    localInsets.right, localInsets.bottom);
7723            return res;
7724        }
7725        return false;
7726    }
7727
7728    /**
7729     * Called when the view should apply {@link WindowInsets} according to its internal policy.
7730     *
7731     * <p>This method should be overridden by views that wish to apply a policy different from or
7732     * in addition to the default behavior. Clients that wish to force a view subtree
7733     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
7734     *
7735     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
7736     * it will be called during dispatch instead of this method. The listener may optionally
7737     * call this method from its own implementation if it wishes to apply the view's default
7738     * insets policy in addition to its own.</p>
7739     *
7740     * <p>Implementations of this method should either return the insets parameter unchanged
7741     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
7742     * that this view applied itself. This allows new inset types added in future platform
7743     * versions to pass through existing implementations unchanged without being erroneously
7744     * consumed.</p>
7745     *
7746     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
7747     * property is set then the view will consume the system window insets and apply them
7748     * as padding for the view.</p>
7749     *
7750     * @param insets Insets to apply
7751     * @return The supplied insets with any applied insets consumed
7752     */
7753    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
7754        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
7755            // We weren't called from within a direct call to fitSystemWindows,
7756            // call into it as a fallback in case we're in a class that overrides it
7757            // and has logic to perform.
7758            if (fitSystemWindows(insets.getSystemWindowInsets())) {
7759                return insets.consumeSystemWindowInsets();
7760            }
7761        } else {
7762            // We were called from within a direct call to fitSystemWindows.
7763            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
7764                return insets.consumeSystemWindowInsets();
7765            }
7766        }
7767        return insets;
7768    }
7769
7770    /**
7771     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
7772     * window insets to this view. The listener's
7773     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
7774     * method will be called instead of the view's
7775     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
7776     *
7777     * @param listener Listener to set
7778     *
7779     * @see #onApplyWindowInsets(WindowInsets)
7780     */
7781    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
7782        getListenerInfo().mOnApplyWindowInsetsListener = listener;
7783    }
7784
7785    /**
7786     * Request to apply the given window insets to this view or another view in its subtree.
7787     *
7788     * <p>This method should be called by clients wishing to apply insets corresponding to areas
7789     * obscured by window decorations or overlays. This can include the status and navigation bars,
7790     * action bars, input methods and more. New inset categories may be added in the future.
7791     * The method returns the insets provided minus any that were applied by this view or its
7792     * children.</p>
7793     *
7794     * <p>Clients wishing to provide custom behavior should override the
7795     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
7796     * {@link OnApplyWindowInsetsListener} via the
7797     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
7798     * method.</p>
7799     *
7800     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
7801     * </p>
7802     *
7803     * @param insets Insets to apply
7804     * @return The provided insets minus the insets that were consumed
7805     */
7806    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
7807        try {
7808            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
7809            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
7810                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
7811            } else {
7812                return onApplyWindowInsets(insets);
7813            }
7814        } finally {
7815            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
7816        }
7817    }
7818
7819    /**
7820     * Compute the view's coordinate within the surface.
7821     *
7822     * <p>Computes the coordinates of this view in its surface. The argument
7823     * must be an array of two integers. After the method returns, the array
7824     * contains the x and y location in that order.</p>
7825     * @hide
7826     * @param location an array of two integers in which to hold the coordinates
7827     */
7828    public void getLocationInSurface(@Size(2) int[] location) {
7829        getLocationInWindow(location);
7830        if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) {
7831            location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left;
7832            location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top;
7833        }
7834    }
7835
7836    /**
7837     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
7838     * only available if the view is attached.
7839     *
7840     * @return WindowInsets from the top of the view hierarchy or null if View is detached
7841     */
7842    public WindowInsets getRootWindowInsets() {
7843        if (mAttachInfo != null) {
7844            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
7845        }
7846        return null;
7847    }
7848
7849    /**
7850     * @hide Compute the insets that should be consumed by this view and the ones
7851     * that should propagate to those under it.
7852     */
7853    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7854        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7855                || mAttachInfo == null
7856                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7857                        && !mAttachInfo.mOverscanRequested)) {
7858            outLocalInsets.set(inoutInsets);
7859            inoutInsets.set(0, 0, 0, 0);
7860            return true;
7861        } else {
7862            // The application wants to take care of fitting system window for
7863            // the content...  however we still need to take care of any overscan here.
7864            final Rect overscan = mAttachInfo.mOverscanInsets;
7865            outLocalInsets.set(overscan);
7866            inoutInsets.left -= overscan.left;
7867            inoutInsets.top -= overscan.top;
7868            inoutInsets.right -= overscan.right;
7869            inoutInsets.bottom -= overscan.bottom;
7870            return false;
7871        }
7872    }
7873
7874    /**
7875     * Compute insets that should be consumed by this view and the ones that should propagate
7876     * to those under it.
7877     *
7878     * @param in Insets currently being processed by this View, likely received as a parameter
7879     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7880     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7881     *                       by this view
7882     * @return Insets that should be passed along to views under this one
7883     */
7884    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7885        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7886                || mAttachInfo == null
7887                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7888            outLocalInsets.set(in.getSystemWindowInsets());
7889            return in.consumeSystemWindowInsets();
7890        } else {
7891            outLocalInsets.set(0, 0, 0, 0);
7892            return in;
7893        }
7894    }
7895
7896    /**
7897     * Sets whether or not this view should account for system screen decorations
7898     * such as the status bar and inset its content; that is, controlling whether
7899     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7900     * executed.  See that method for more details.
7901     *
7902     * <p>Note that if you are providing your own implementation of
7903     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7904     * flag to true -- your implementation will be overriding the default
7905     * implementation that checks this flag.
7906     *
7907     * @param fitSystemWindows If true, then the default implementation of
7908     * {@link #fitSystemWindows(Rect)} will be executed.
7909     *
7910     * @attr ref android.R.styleable#View_fitsSystemWindows
7911     * @see #getFitsSystemWindows()
7912     * @see #fitSystemWindows(Rect)
7913     * @see #setSystemUiVisibility(int)
7914     */
7915    public void setFitsSystemWindows(boolean fitSystemWindows) {
7916        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7917    }
7918
7919    /**
7920     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7921     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7922     * will be executed.
7923     *
7924     * @return {@code true} if the default implementation of
7925     * {@link #fitSystemWindows(Rect)} will be executed.
7926     *
7927     * @attr ref android.R.styleable#View_fitsSystemWindows
7928     * @see #setFitsSystemWindows(boolean)
7929     * @see #fitSystemWindows(Rect)
7930     * @see #setSystemUiVisibility(int)
7931     */
7932    @ViewDebug.ExportedProperty
7933    public boolean getFitsSystemWindows() {
7934        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7935    }
7936
7937    /** @hide */
7938    public boolean fitsSystemWindows() {
7939        return getFitsSystemWindows();
7940    }
7941
7942    /**
7943     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7944     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7945     */
7946    @Deprecated
7947    public void requestFitSystemWindows() {
7948        if (mParent != null) {
7949            mParent.requestFitSystemWindows();
7950        }
7951    }
7952
7953    /**
7954     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7955     */
7956    public void requestApplyInsets() {
7957        requestFitSystemWindows();
7958    }
7959
7960    /**
7961     * For use by PhoneWindow to make its own system window fitting optional.
7962     * @hide
7963     */
7964    public void makeOptionalFitsSystemWindows() {
7965        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7966    }
7967
7968    /**
7969     * Returns the outsets, which areas of the device that aren't a surface, but we would like to
7970     * treat them as such.
7971     * @hide
7972     */
7973    public void getOutsets(Rect outOutsetRect) {
7974        if (mAttachInfo != null) {
7975            outOutsetRect.set(mAttachInfo.mOutsets);
7976        } else {
7977            outOutsetRect.setEmpty();
7978        }
7979    }
7980
7981    /**
7982     * Returns the visibility status for this view.
7983     *
7984     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7985     * @attr ref android.R.styleable#View_visibility
7986     */
7987    @ViewDebug.ExportedProperty(mapping = {
7988        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7989        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7990        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7991    })
7992    @Visibility
7993    public int getVisibility() {
7994        return mViewFlags & VISIBILITY_MASK;
7995    }
7996
7997    /**
7998     * Set the enabled state of this view.
7999     *
8000     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
8001     * @attr ref android.R.styleable#View_visibility
8002     */
8003    @RemotableViewMethod
8004    public void setVisibility(@Visibility int visibility) {
8005        setFlags(visibility, VISIBILITY_MASK);
8006    }
8007
8008    /**
8009     * Returns the enabled status for this view. The interpretation of the
8010     * enabled state varies by subclass.
8011     *
8012     * @return True if this view is enabled, false otherwise.
8013     */
8014    @ViewDebug.ExportedProperty
8015    public boolean isEnabled() {
8016        return (mViewFlags & ENABLED_MASK) == ENABLED;
8017    }
8018
8019    /**
8020     * Set the enabled state of this view. The interpretation of the enabled
8021     * state varies by subclass.
8022     *
8023     * @param enabled True if this view is enabled, false otherwise.
8024     */
8025    @RemotableViewMethod
8026    public void setEnabled(boolean enabled) {
8027        if (enabled == isEnabled()) return;
8028
8029        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
8030
8031        /*
8032         * The View most likely has to change its appearance, so refresh
8033         * the drawable state.
8034         */
8035        refreshDrawableState();
8036
8037        // Invalidate too, since the default behavior for views is to be
8038        // be drawn at 50% alpha rather than to change the drawable.
8039        invalidate(true);
8040
8041        if (!enabled) {
8042            cancelPendingInputEvents();
8043        }
8044    }
8045
8046    /**
8047     * Set whether this view can receive the focus.
8048     *
8049     * Setting this to false will also ensure that this view is not focusable
8050     * in touch mode.
8051     *
8052     * @param focusable If true, this view can receive the focus.
8053     *
8054     * @see #setFocusableInTouchMode(boolean)
8055     * @attr ref android.R.styleable#View_focusable
8056     */
8057    public void setFocusable(boolean focusable) {
8058        if (!focusable) {
8059            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
8060        }
8061        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
8062    }
8063
8064    /**
8065     * Set whether this view can receive focus while in touch mode.
8066     *
8067     * Setting this to true will also ensure that this view is focusable.
8068     *
8069     * @param focusableInTouchMode If true, this view can receive the focus while
8070     *   in touch mode.
8071     *
8072     * @see #setFocusable(boolean)
8073     * @attr ref android.R.styleable#View_focusableInTouchMode
8074     */
8075    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
8076        // Focusable in touch mode should always be set before the focusable flag
8077        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
8078        // which, in touch mode, will not successfully request focus on this view
8079        // because the focusable in touch mode flag is not set
8080        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
8081        if (focusableInTouchMode) {
8082            setFlags(FOCUSABLE, FOCUSABLE_MASK);
8083        }
8084    }
8085
8086    /**
8087     * Set whether this view should have sound effects enabled for events such as
8088     * clicking and touching.
8089     *
8090     * <p>You may wish to disable sound effects for a view if you already play sounds,
8091     * for instance, a dial key that plays dtmf tones.
8092     *
8093     * @param soundEffectsEnabled whether sound effects are enabled for this view.
8094     * @see #isSoundEffectsEnabled()
8095     * @see #playSoundEffect(int)
8096     * @attr ref android.R.styleable#View_soundEffectsEnabled
8097     */
8098    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
8099        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
8100    }
8101
8102    /**
8103     * @return whether this view should have sound effects enabled for events such as
8104     *     clicking and touching.
8105     *
8106     * @see #setSoundEffectsEnabled(boolean)
8107     * @see #playSoundEffect(int)
8108     * @attr ref android.R.styleable#View_soundEffectsEnabled
8109     */
8110    @ViewDebug.ExportedProperty
8111    public boolean isSoundEffectsEnabled() {
8112        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
8113    }
8114
8115    /**
8116     * Set whether this view should have haptic feedback for events such as
8117     * long presses.
8118     *
8119     * <p>You may wish to disable haptic feedback if your view already controls
8120     * its own haptic feedback.
8121     *
8122     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
8123     * @see #isHapticFeedbackEnabled()
8124     * @see #performHapticFeedback(int)
8125     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8126     */
8127    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
8128        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
8129    }
8130
8131    /**
8132     * @return whether this view should have haptic feedback enabled for events
8133     * long presses.
8134     *
8135     * @see #setHapticFeedbackEnabled(boolean)
8136     * @see #performHapticFeedback(int)
8137     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
8138     */
8139    @ViewDebug.ExportedProperty
8140    public boolean isHapticFeedbackEnabled() {
8141        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
8142    }
8143
8144    /**
8145     * Returns the layout direction for this view.
8146     *
8147     * @return One of {@link #LAYOUT_DIRECTION_LTR},
8148     *   {@link #LAYOUT_DIRECTION_RTL},
8149     *   {@link #LAYOUT_DIRECTION_INHERIT} or
8150     *   {@link #LAYOUT_DIRECTION_LOCALE}.
8151     *
8152     * @attr ref android.R.styleable#View_layoutDirection
8153     *
8154     * @hide
8155     */
8156    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8157        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
8158        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
8159        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
8160        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
8161    })
8162    @LayoutDir
8163    public int getRawLayoutDirection() {
8164        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
8165    }
8166
8167    /**
8168     * Set the layout direction for this view. This will propagate a reset of layout direction
8169     * resolution to the view's children and resolve layout direction for this view.
8170     *
8171     * @param layoutDirection the layout direction to set. Should be one of:
8172     *
8173     * {@link #LAYOUT_DIRECTION_LTR},
8174     * {@link #LAYOUT_DIRECTION_RTL},
8175     * {@link #LAYOUT_DIRECTION_INHERIT},
8176     * {@link #LAYOUT_DIRECTION_LOCALE}.
8177     *
8178     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
8179     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
8180     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
8181     *
8182     * @attr ref android.R.styleable#View_layoutDirection
8183     */
8184    @RemotableViewMethod
8185    public void setLayoutDirection(@LayoutDir int layoutDirection) {
8186        if (getRawLayoutDirection() != layoutDirection) {
8187            // Reset the current layout direction and the resolved one
8188            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
8189            resetRtlProperties();
8190            // Set the new layout direction (filtered)
8191            mPrivateFlags2 |=
8192                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
8193            // We need to resolve all RTL properties as they all depend on layout direction
8194            resolveRtlPropertiesIfNeeded();
8195            requestLayout();
8196            invalidate(true);
8197        }
8198    }
8199
8200    /**
8201     * Returns the resolved layout direction for this view.
8202     *
8203     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
8204     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
8205     *
8206     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
8207     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
8208     *
8209     * @attr ref android.R.styleable#View_layoutDirection
8210     */
8211    @ViewDebug.ExportedProperty(category = "layout", mapping = {
8212        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
8213        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
8214    })
8215    @ResolvedLayoutDir
8216    public int getLayoutDirection() {
8217        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
8218        if (targetSdkVersion < JELLY_BEAN_MR1) {
8219            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
8220            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
8221        }
8222        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
8223                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
8224    }
8225
8226    /**
8227     * Indicates whether or not this view's layout is right-to-left. This is resolved from
8228     * layout attribute and/or the inherited value from the parent
8229     *
8230     * @return true if the layout is right-to-left.
8231     *
8232     * @hide
8233     */
8234    @ViewDebug.ExportedProperty(category = "layout")
8235    public boolean isLayoutRtl() {
8236        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
8237    }
8238
8239    /**
8240     * Indicates whether the view is currently tracking transient state that the
8241     * app should not need to concern itself with saving and restoring, but that
8242     * the framework should take special note to preserve when possible.
8243     *
8244     * <p>A view with transient state cannot be trivially rebound from an external
8245     * data source, such as an adapter binding item views in a list. This may be
8246     * because the view is performing an animation, tracking user selection
8247     * of content, or similar.</p>
8248     *
8249     * @return true if the view has transient state
8250     */
8251    @ViewDebug.ExportedProperty(category = "layout")
8252    public boolean hasTransientState() {
8253        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
8254    }
8255
8256    /**
8257     * Set whether this view is currently tracking transient state that the
8258     * framework should attempt to preserve when possible. This flag is reference counted,
8259     * so every call to setHasTransientState(true) should be paired with a later call
8260     * to setHasTransientState(false).
8261     *
8262     * <p>A view with transient state cannot be trivially rebound from an external
8263     * data source, such as an adapter binding item views in a list. This may be
8264     * because the view is performing an animation, tracking user selection
8265     * of content, or similar.</p>
8266     *
8267     * @param hasTransientState true if this view has transient state
8268     */
8269    public void setHasTransientState(boolean hasTransientState) {
8270        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
8271                mTransientStateCount - 1;
8272        if (mTransientStateCount < 0) {
8273            mTransientStateCount = 0;
8274            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
8275                    "unmatched pair of setHasTransientState calls");
8276        } else if ((hasTransientState && mTransientStateCount == 1) ||
8277                (!hasTransientState && mTransientStateCount == 0)) {
8278            // update flag if we've just incremented up from 0 or decremented down to 0
8279            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
8280                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
8281            if (mParent != null) {
8282                try {
8283                    mParent.childHasTransientStateChanged(this, hasTransientState);
8284                } catch (AbstractMethodError e) {
8285                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8286                            " does not fully implement ViewParent", e);
8287                }
8288            }
8289        }
8290    }
8291
8292    /**
8293     * Returns true if this view is currently attached to a window.
8294     */
8295    public boolean isAttachedToWindow() {
8296        return mAttachInfo != null;
8297    }
8298
8299    /**
8300     * Returns true if this view has been through at least one layout since it
8301     * was last attached to or detached from a window.
8302     */
8303    public boolean isLaidOut() {
8304        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
8305    }
8306
8307    /**
8308     * If this view doesn't do any drawing on its own, set this flag to
8309     * allow further optimizations. By default, this flag is not set on
8310     * View, but could be set on some View subclasses such as ViewGroup.
8311     *
8312     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
8313     * you should clear this flag.
8314     *
8315     * @param willNotDraw whether or not this View draw on its own
8316     */
8317    public void setWillNotDraw(boolean willNotDraw) {
8318        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
8319    }
8320
8321    /**
8322     * Returns whether or not this View draws on its own.
8323     *
8324     * @return true if this view has nothing to draw, false otherwise
8325     */
8326    @ViewDebug.ExportedProperty(category = "drawing")
8327    public boolean willNotDraw() {
8328        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
8329    }
8330
8331    /**
8332     * When a View's drawing cache is enabled, drawing is redirected to an
8333     * offscreen bitmap. Some views, like an ImageView, must be able to
8334     * bypass this mechanism if they already draw a single bitmap, to avoid
8335     * unnecessary usage of the memory.
8336     *
8337     * @param willNotCacheDrawing true if this view does not cache its
8338     *        drawing, false otherwise
8339     */
8340    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
8341        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
8342    }
8343
8344    /**
8345     * Returns whether or not this View can cache its drawing or not.
8346     *
8347     * @return true if this view does not cache its drawing, false otherwise
8348     */
8349    @ViewDebug.ExportedProperty(category = "drawing")
8350    public boolean willNotCacheDrawing() {
8351        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
8352    }
8353
8354    /**
8355     * Indicates whether this view reacts to click events or not.
8356     *
8357     * @return true if the view is clickable, false otherwise
8358     *
8359     * @see #setClickable(boolean)
8360     * @attr ref android.R.styleable#View_clickable
8361     */
8362    @ViewDebug.ExportedProperty
8363    public boolean isClickable() {
8364        return (mViewFlags & CLICKABLE) == CLICKABLE;
8365    }
8366
8367    /**
8368     * Enables or disables click events for this view. When a view
8369     * is clickable it will change its state to "pressed" on every click.
8370     * Subclasses should set the view clickable to visually react to
8371     * user's clicks.
8372     *
8373     * @param clickable true to make the view clickable, false otherwise
8374     *
8375     * @see #isClickable()
8376     * @attr ref android.R.styleable#View_clickable
8377     */
8378    public void setClickable(boolean clickable) {
8379        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
8380    }
8381
8382    /**
8383     * Indicates whether this view reacts to long click events or not.
8384     *
8385     * @return true if the view is long clickable, false otherwise
8386     *
8387     * @see #setLongClickable(boolean)
8388     * @attr ref android.R.styleable#View_longClickable
8389     */
8390    public boolean isLongClickable() {
8391        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8392    }
8393
8394    /**
8395     * Enables or disables long click events for this view. When a view is long
8396     * clickable it reacts to the user holding down the button for a longer
8397     * duration than a tap. This event can either launch the listener or a
8398     * context menu.
8399     *
8400     * @param longClickable true to make the view long clickable, false otherwise
8401     * @see #isLongClickable()
8402     * @attr ref android.R.styleable#View_longClickable
8403     */
8404    public void setLongClickable(boolean longClickable) {
8405        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
8406    }
8407
8408    /**
8409     * Indicates whether this view reacts to context clicks or not.
8410     *
8411     * @return true if the view is context clickable, false otherwise
8412     * @see #setContextClickable(boolean)
8413     * @attr ref android.R.styleable#View_contextClickable
8414     */
8415    public boolean isContextClickable() {
8416        return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
8417    }
8418
8419    /**
8420     * Enables or disables context clicking for this view. This event can launch the listener.
8421     *
8422     * @param contextClickable true to make the view react to a context click, false otherwise
8423     * @see #isContextClickable()
8424     * @attr ref android.R.styleable#View_contextClickable
8425     */
8426    public void setContextClickable(boolean contextClickable) {
8427        setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE);
8428    }
8429
8430    /**
8431     * Sets the pressed state for this view and provides a touch coordinate for
8432     * animation hinting.
8433     *
8434     * @param pressed Pass true to set the View's internal state to "pressed",
8435     *            or false to reverts the View's internal state from a
8436     *            previously set "pressed" state.
8437     * @param x The x coordinate of the touch that caused the press
8438     * @param y The y coordinate of the touch that caused the press
8439     */
8440    private void setPressed(boolean pressed, float x, float y) {
8441        if (pressed) {
8442            drawableHotspotChanged(x, y);
8443        }
8444
8445        setPressed(pressed);
8446    }
8447
8448    /**
8449     * Sets the pressed state for this view.
8450     *
8451     * @see #isClickable()
8452     * @see #setClickable(boolean)
8453     *
8454     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
8455     *        the View's internal state from a previously set "pressed" state.
8456     */
8457    public void setPressed(boolean pressed) {
8458        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
8459
8460        if (pressed) {
8461            mPrivateFlags |= PFLAG_PRESSED;
8462        } else {
8463            mPrivateFlags &= ~PFLAG_PRESSED;
8464        }
8465
8466        if (needsRefresh) {
8467            refreshDrawableState();
8468        }
8469        dispatchSetPressed(pressed);
8470    }
8471
8472    /**
8473     * Dispatch setPressed to all of this View's children.
8474     *
8475     * @see #setPressed(boolean)
8476     *
8477     * @param pressed The new pressed state
8478     */
8479    protected void dispatchSetPressed(boolean pressed) {
8480    }
8481
8482    /**
8483     * Indicates whether the view is currently in pressed state. Unless
8484     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
8485     * the pressed state.
8486     *
8487     * @see #setPressed(boolean)
8488     * @see #isClickable()
8489     * @see #setClickable(boolean)
8490     *
8491     * @return true if the view is currently pressed, false otherwise
8492     */
8493    @ViewDebug.ExportedProperty
8494    public boolean isPressed() {
8495        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
8496    }
8497
8498    /**
8499     * @hide
8500     * Indicates whether this view will participate in data collection through
8501     * {@link ViewStructure}.  If true, it will not provide any data
8502     * for itself or its children.  If false, the normal data collection will be allowed.
8503     *
8504     * @return Returns false if assist data collection is not blocked, else true.
8505     *
8506     * @see #setAssistBlocked(boolean)
8507     * @attr ref android.R.styleable#View_assistBlocked
8508     */
8509    public boolean isAssistBlocked() {
8510        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
8511    }
8512
8513    /**
8514     * @hide
8515     * Controls whether assist data collection from this view and its children is enabled
8516     * (that is, whether {@link #onProvideStructure} and
8517     * {@link #onProvideVirtualStructure} will be called).  The default value is false,
8518     * allowing normal assist collection.  Setting this to false will disable assist collection.
8519     *
8520     * @param enabled Set to true to <em>disable</em> assist data collection, or false
8521     * (the default) to allow it.
8522     *
8523     * @see #isAssistBlocked()
8524     * @see #onProvideStructure
8525     * @see #onProvideVirtualStructure
8526     * @attr ref android.R.styleable#View_assistBlocked
8527     */
8528    public void setAssistBlocked(boolean enabled) {
8529        if (enabled) {
8530            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
8531        } else {
8532            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
8533        }
8534    }
8535
8536    /**
8537     * Indicates whether this view will save its state (that is,
8538     * whether its {@link #onSaveInstanceState} method will be called).
8539     *
8540     * @return Returns true if the view state saving is enabled, else false.
8541     *
8542     * @see #setSaveEnabled(boolean)
8543     * @attr ref android.R.styleable#View_saveEnabled
8544     */
8545    public boolean isSaveEnabled() {
8546        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
8547    }
8548
8549    /**
8550     * Controls whether the saving of this view's state is
8551     * enabled (that is, whether its {@link #onSaveInstanceState} method
8552     * will be called).  Note that even if freezing is enabled, the
8553     * view still must have an id assigned to it (via {@link #setId(int)})
8554     * for its state to be saved.  This flag can only disable the
8555     * saving of this view; any child views may still have their state saved.
8556     *
8557     * @param enabled Set to false to <em>disable</em> state saving, or true
8558     * (the default) to allow it.
8559     *
8560     * @see #isSaveEnabled()
8561     * @see #setId(int)
8562     * @see #onSaveInstanceState()
8563     * @attr ref android.R.styleable#View_saveEnabled
8564     */
8565    public void setSaveEnabled(boolean enabled) {
8566        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
8567    }
8568
8569    /**
8570     * Gets whether the framework should discard touches when the view's
8571     * window is obscured by another visible window.
8572     * Refer to the {@link View} security documentation for more details.
8573     *
8574     * @return True if touch filtering is enabled.
8575     *
8576     * @see #setFilterTouchesWhenObscured(boolean)
8577     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8578     */
8579    @ViewDebug.ExportedProperty
8580    public boolean getFilterTouchesWhenObscured() {
8581        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
8582    }
8583
8584    /**
8585     * Sets whether the framework should discard touches when the view's
8586     * window is obscured by another visible window.
8587     * Refer to the {@link View} security documentation for more details.
8588     *
8589     * @param enabled True if touch filtering should be enabled.
8590     *
8591     * @see #getFilterTouchesWhenObscured
8592     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
8593     */
8594    public void setFilterTouchesWhenObscured(boolean enabled) {
8595        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
8596                FILTER_TOUCHES_WHEN_OBSCURED);
8597    }
8598
8599    /**
8600     * Indicates whether the entire hierarchy under this view will save its
8601     * state when a state saving traversal occurs from its parent.  The default
8602     * is true; if false, these views will not be saved unless
8603     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8604     *
8605     * @return Returns true if the view state saving from parent is enabled, else false.
8606     *
8607     * @see #setSaveFromParentEnabled(boolean)
8608     */
8609    public boolean isSaveFromParentEnabled() {
8610        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
8611    }
8612
8613    /**
8614     * Controls whether the entire hierarchy under this view will save its
8615     * state when a state saving traversal occurs from its parent.  The default
8616     * is true; if false, these views will not be saved unless
8617     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
8618     *
8619     * @param enabled Set to false to <em>disable</em> state saving, or true
8620     * (the default) to allow it.
8621     *
8622     * @see #isSaveFromParentEnabled()
8623     * @see #setId(int)
8624     * @see #onSaveInstanceState()
8625     */
8626    public void setSaveFromParentEnabled(boolean enabled) {
8627        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
8628    }
8629
8630
8631    /**
8632     * Returns whether this View is able to take focus.
8633     *
8634     * @return True if this view can take focus, or false otherwise.
8635     * @attr ref android.R.styleable#View_focusable
8636     */
8637    @ViewDebug.ExportedProperty(category = "focus")
8638    public final boolean isFocusable() {
8639        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
8640    }
8641
8642    /**
8643     * When a view is focusable, it may not want to take focus when in touch mode.
8644     * For example, a button would like focus when the user is navigating via a D-pad
8645     * so that the user can click on it, but once the user starts touching the screen,
8646     * the button shouldn't take focus
8647     * @return Whether the view is focusable in touch mode.
8648     * @attr ref android.R.styleable#View_focusableInTouchMode
8649     */
8650    @ViewDebug.ExportedProperty
8651    public final boolean isFocusableInTouchMode() {
8652        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
8653    }
8654
8655    /**
8656     * Find the nearest view in the specified direction that can take focus.
8657     * This does not actually give focus to that view.
8658     *
8659     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8660     *
8661     * @return The nearest focusable in the specified direction, or null if none
8662     *         can be found.
8663     */
8664    public View focusSearch(@FocusRealDirection int direction) {
8665        if (mParent != null) {
8666            return mParent.focusSearch(this, direction);
8667        } else {
8668            return null;
8669        }
8670    }
8671
8672    /**
8673     * This method is the last chance for the focused view and its ancestors to
8674     * respond to an arrow key. This is called when the focused view did not
8675     * consume the key internally, nor could the view system find a new view in
8676     * the requested direction to give focus to.
8677     *
8678     * @param focused The currently focused view.
8679     * @param direction The direction focus wants to move. One of FOCUS_UP,
8680     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
8681     * @return True if the this view consumed this unhandled move.
8682     */
8683    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
8684        return false;
8685    }
8686
8687    /**
8688     * If a user manually specified the next view id for a particular direction,
8689     * use the root to look up the view.
8690     * @param root The root view of the hierarchy containing this view.
8691     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
8692     * or FOCUS_BACKWARD.
8693     * @return The user specified next view, or null if there is none.
8694     */
8695    View findUserSetNextFocus(View root, @FocusDirection int direction) {
8696        switch (direction) {
8697            case FOCUS_LEFT:
8698                if (mNextFocusLeftId == View.NO_ID) return null;
8699                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
8700            case FOCUS_RIGHT:
8701                if (mNextFocusRightId == View.NO_ID) return null;
8702                return findViewInsideOutShouldExist(root, mNextFocusRightId);
8703            case FOCUS_UP:
8704                if (mNextFocusUpId == View.NO_ID) return null;
8705                return findViewInsideOutShouldExist(root, mNextFocusUpId);
8706            case FOCUS_DOWN:
8707                if (mNextFocusDownId == View.NO_ID) return null;
8708                return findViewInsideOutShouldExist(root, mNextFocusDownId);
8709            case FOCUS_FORWARD:
8710                if (mNextFocusForwardId == View.NO_ID) return null;
8711                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
8712            case FOCUS_BACKWARD: {
8713                if (mID == View.NO_ID) return null;
8714                final int id = mID;
8715                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
8716                    @Override
8717                    public boolean apply(View t) {
8718                        return t.mNextFocusForwardId == id;
8719                    }
8720                });
8721            }
8722        }
8723        return null;
8724    }
8725
8726    private View findViewInsideOutShouldExist(View root, int id) {
8727        if (mMatchIdPredicate == null) {
8728            mMatchIdPredicate = new MatchIdPredicate();
8729        }
8730        mMatchIdPredicate.mId = id;
8731        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
8732        if (result == null) {
8733            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
8734        }
8735        return result;
8736    }
8737
8738    /**
8739     * Find and return all focusable views that are descendants of this view,
8740     * possibly including this view if it is focusable itself.
8741     *
8742     * @param direction The direction of the focus
8743     * @return A list of focusable views
8744     */
8745    public ArrayList<View> getFocusables(@FocusDirection int direction) {
8746        ArrayList<View> result = new ArrayList<View>(24);
8747        addFocusables(result, direction);
8748        return result;
8749    }
8750
8751    /**
8752     * Add any focusable views that are descendants of this view (possibly
8753     * including this view if it is focusable itself) to views.  If we are in touch mode,
8754     * only add views that are also focusable in touch mode.
8755     *
8756     * @param views Focusable views found so far
8757     * @param direction The direction of the focus
8758     */
8759    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
8760        addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL);
8761    }
8762
8763    /**
8764     * Adds any focusable views that are descendants of this view (possibly
8765     * including this view if it is focusable itself) to views. This method
8766     * adds all focusable views regardless if we are in touch mode or
8767     * only views focusable in touch mode if we are in touch mode or
8768     * only views that can take accessibility focus if accessibility is enabled
8769     * depending on the focusable mode parameter.
8770     *
8771     * @param views Focusable views found so far or null if all we are interested is
8772     *        the number of focusables.
8773     * @param direction The direction of the focus.
8774     * @param focusableMode The type of focusables to be added.
8775     *
8776     * @see #FOCUSABLES_ALL
8777     * @see #FOCUSABLES_TOUCH_MODE
8778     */
8779    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
8780            @FocusableMode int focusableMode) {
8781        if (views == null) {
8782            return;
8783        }
8784        if (!isFocusable()) {
8785            return;
8786        }
8787        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
8788                && !isFocusableInTouchMode()) {
8789            return;
8790        }
8791        views.add(this);
8792    }
8793
8794    /**
8795     * Finds the Views that contain given text. The containment is case insensitive.
8796     * The search is performed by either the text that the View renders or the content
8797     * description that describes the view for accessibility purposes and the view does
8798     * not render or both. Clients can specify how the search is to be performed via
8799     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
8800     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
8801     *
8802     * @param outViews The output list of matching Views.
8803     * @param searched The text to match against.
8804     *
8805     * @see #FIND_VIEWS_WITH_TEXT
8806     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
8807     * @see #setContentDescription(CharSequence)
8808     */
8809    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
8810            @FindViewFlags int flags) {
8811        if (getAccessibilityNodeProvider() != null) {
8812            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
8813                outViews.add(this);
8814            }
8815        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
8816                && (searched != null && searched.length() > 0)
8817                && (mContentDescription != null && mContentDescription.length() > 0)) {
8818            String searchedLowerCase = searched.toString().toLowerCase();
8819            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
8820            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
8821                outViews.add(this);
8822            }
8823        }
8824    }
8825
8826    /**
8827     * Find and return all touchable views that are descendants of this view,
8828     * possibly including this view if it is touchable itself.
8829     *
8830     * @return A list of touchable views
8831     */
8832    public ArrayList<View> getTouchables() {
8833        ArrayList<View> result = new ArrayList<View>();
8834        addTouchables(result);
8835        return result;
8836    }
8837
8838    /**
8839     * Add any touchable views that are descendants of this view (possibly
8840     * including this view if it is touchable itself) to views.
8841     *
8842     * @param views Touchable views found so far
8843     */
8844    public void addTouchables(ArrayList<View> views) {
8845        final int viewFlags = mViewFlags;
8846
8847        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
8848                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE)
8849                && (viewFlags & ENABLED_MASK) == ENABLED) {
8850            views.add(this);
8851        }
8852    }
8853
8854    /**
8855     * Returns whether this View is accessibility focused.
8856     *
8857     * @return True if this View is accessibility focused.
8858     */
8859    public boolean isAccessibilityFocused() {
8860        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
8861    }
8862
8863    /**
8864     * Call this to try to give accessibility focus to this view.
8865     *
8866     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8867     * returns false or the view is no visible or the view already has accessibility
8868     * focus.
8869     *
8870     * See also {@link #focusSearch(int)}, which is what you call to say that you
8871     * have focus, and you want your parent to look for the next one.
8872     *
8873     * @return Whether this view actually took accessibility focus.
8874     *
8875     * @hide
8876     */
8877    public boolean requestAccessibilityFocus() {
8878        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8879        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8880            return false;
8881        }
8882        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8883            return false;
8884        }
8885        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8886            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8887            ViewRootImpl viewRootImpl = getViewRootImpl();
8888            if (viewRootImpl != null) {
8889                viewRootImpl.setAccessibilityFocus(this, null);
8890            }
8891            invalidate();
8892            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8893            return true;
8894        }
8895        return false;
8896    }
8897
8898    /**
8899     * Call this to try to clear accessibility focus of this view.
8900     *
8901     * See also {@link #focusSearch(int)}, which is what you call to say that you
8902     * have focus, and you want your parent to look for the next one.
8903     *
8904     * @hide
8905     */
8906    public void clearAccessibilityFocus() {
8907        clearAccessibilityFocusNoCallbacks(0);
8908
8909        // Clear the global reference of accessibility focus if this view or
8910        // any of its descendants had accessibility focus. This will NOT send
8911        // an event or update internal state if focus is cleared from a
8912        // descendant view, which may leave views in inconsistent states.
8913        final ViewRootImpl viewRootImpl = getViewRootImpl();
8914        if (viewRootImpl != null) {
8915            final View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8916            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8917                viewRootImpl.setAccessibilityFocus(null, null);
8918            }
8919        }
8920    }
8921
8922    private void sendAccessibilityHoverEvent(int eventType) {
8923        // Since we are not delivering to a client accessibility events from not
8924        // important views (unless the clinet request that) we need to fire the
8925        // event from the deepest view exposed to the client. As a consequence if
8926        // the user crosses a not exposed view the client will see enter and exit
8927        // of the exposed predecessor followed by and enter and exit of that same
8928        // predecessor when entering and exiting the not exposed descendant. This
8929        // is fine since the client has a clear idea which view is hovered at the
8930        // price of a couple more events being sent. This is a simple and
8931        // working solution.
8932        View source = this;
8933        while (true) {
8934            if (source.includeForAccessibility()) {
8935                source.sendAccessibilityEvent(eventType);
8936                return;
8937            }
8938            ViewParent parent = source.getParent();
8939            if (parent instanceof View) {
8940                source = (View) parent;
8941            } else {
8942                return;
8943            }
8944        }
8945    }
8946
8947    /**
8948     * Clears accessibility focus without calling any callback methods
8949     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8950     * is used separately from that one for clearing accessibility focus when
8951     * giving this focus to another view.
8952     *
8953     * @param action The action, if any, that led to focus being cleared. Set to
8954     * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within
8955     * the window.
8956     */
8957    void clearAccessibilityFocusNoCallbacks(int action) {
8958        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8959            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8960            invalidate();
8961            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8962                AccessibilityEvent event = AccessibilityEvent.obtain(
8963                        AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8964                event.setAction(action);
8965                if (mAccessibilityDelegate != null) {
8966                    mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
8967                } else {
8968                    sendAccessibilityEventUnchecked(event);
8969                }
8970            }
8971        }
8972    }
8973
8974    /**
8975     * Call this to try to give focus to a specific view or to one of its
8976     * descendants.
8977     *
8978     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8979     * false), or if it is focusable and it is not focusable in touch mode
8980     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8981     *
8982     * See also {@link #focusSearch(int)}, which is what you call to say that you
8983     * have focus, and you want your parent to look for the next one.
8984     *
8985     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8986     * {@link #FOCUS_DOWN} and <code>null</code>.
8987     *
8988     * @return Whether this view or one of its descendants actually took focus.
8989     */
8990    public final boolean requestFocus() {
8991        return requestFocus(View.FOCUS_DOWN);
8992    }
8993
8994    /**
8995     * Call this to try to give focus to a specific view or to one of its
8996     * descendants and give it a hint about what direction focus is heading.
8997     *
8998     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8999     * false), or if it is focusable and it is not focusable in touch mode
9000     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9001     *
9002     * See also {@link #focusSearch(int)}, which is what you call to say that you
9003     * have focus, and you want your parent to look for the next one.
9004     *
9005     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
9006     * <code>null</code> set for the previously focused rectangle.
9007     *
9008     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9009     * @return Whether this view or one of its descendants actually took focus.
9010     */
9011    public final boolean requestFocus(int direction) {
9012        return requestFocus(direction, null);
9013    }
9014
9015    /**
9016     * Call this to try to give focus to a specific view or to one of its descendants
9017     * and give it hints about the direction and a specific rectangle that the focus
9018     * is coming from.  The rectangle can help give larger views a finer grained hint
9019     * about where focus is coming from, and therefore, where to show selection, or
9020     * forward focus change internally.
9021     *
9022     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
9023     * false), or if it is focusable and it is not focusable in touch mode
9024     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
9025     *
9026     * A View will not take focus if it is not visible.
9027     *
9028     * A View will not take focus if one of its parents has
9029     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
9030     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
9031     *
9032     * See also {@link #focusSearch(int)}, which is what you call to say that you
9033     * have focus, and you want your parent to look for the next one.
9034     *
9035     * You may wish to override this method if your custom {@link View} has an internal
9036     * {@link View} that it wishes to forward the request to.
9037     *
9038     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
9039     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
9040     *        to give a finer grained hint about where focus is coming from.  May be null
9041     *        if there is no hint.
9042     * @return Whether this view or one of its descendants actually took focus.
9043     */
9044    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
9045        return requestFocusNoSearch(direction, previouslyFocusedRect);
9046    }
9047
9048    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
9049        // need to be focusable
9050        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
9051                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
9052            return false;
9053        }
9054
9055        // need to be focusable in touch mode if in touch mode
9056        if (isInTouchMode() &&
9057            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
9058               return false;
9059        }
9060
9061        // need to not have any parents blocking us
9062        if (hasAncestorThatBlocksDescendantFocus()) {
9063            return false;
9064        }
9065
9066        handleFocusGainInternal(direction, previouslyFocusedRect);
9067        return true;
9068    }
9069
9070    /**
9071     * Call this to try to give focus to a specific view or to one of its descendants. This is a
9072     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
9073     * touch mode to request focus when they are touched.
9074     *
9075     * @return Whether this view or one of its descendants actually took focus.
9076     *
9077     * @see #isInTouchMode()
9078     *
9079     */
9080    public final boolean requestFocusFromTouch() {
9081        // Leave touch mode if we need to
9082        if (isInTouchMode()) {
9083            ViewRootImpl viewRoot = getViewRootImpl();
9084            if (viewRoot != null) {
9085                viewRoot.ensureTouchMode(false);
9086            }
9087        }
9088        return requestFocus(View.FOCUS_DOWN);
9089    }
9090
9091    /**
9092     * @return Whether any ancestor of this view blocks descendant focus.
9093     */
9094    private boolean hasAncestorThatBlocksDescendantFocus() {
9095        final boolean focusableInTouchMode = isFocusableInTouchMode();
9096        ViewParent ancestor = mParent;
9097        while (ancestor instanceof ViewGroup) {
9098            final ViewGroup vgAncestor = (ViewGroup) ancestor;
9099            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
9100                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
9101                return true;
9102            } else {
9103                ancestor = vgAncestor.getParent();
9104            }
9105        }
9106        return false;
9107    }
9108
9109    /**
9110     * Gets the mode for determining whether this View is important for accessibility
9111     * which is if it fires accessibility events and if it is reported to
9112     * accessibility services that query the screen.
9113     *
9114     * @return The mode for determining whether a View is important for accessibility.
9115     *
9116     * @attr ref android.R.styleable#View_importantForAccessibility
9117     *
9118     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9119     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9120     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9121     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9122     */
9123    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
9124            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
9125            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
9126            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
9127            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
9128                    to = "noHideDescendants")
9129        })
9130    public int getImportantForAccessibility() {
9131        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9132                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9133    }
9134
9135    /**
9136     * Sets the live region mode for this view. This indicates to accessibility
9137     * services whether they should automatically notify the user about changes
9138     * to the view's content description or text, or to the content descriptions
9139     * or text of the view's children (where applicable).
9140     * <p>
9141     * For example, in a login screen with a TextView that displays an "incorrect
9142     * password" notification, that view should be marked as a live region with
9143     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9144     * <p>
9145     * To disable change notifications for this view, use
9146     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
9147     * mode for most views.
9148     * <p>
9149     * To indicate that the user should be notified of changes, use
9150     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
9151     * <p>
9152     * If the view's changes should interrupt ongoing speech and notify the user
9153     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
9154     *
9155     * @param mode The live region mode for this view, one of:
9156     *        <ul>
9157     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
9158     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
9159     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
9160     *        </ul>
9161     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9162     */
9163    public void setAccessibilityLiveRegion(int mode) {
9164        if (mode != getAccessibilityLiveRegion()) {
9165            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9166            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
9167                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
9168            notifyViewAccessibilityStateChangedIfNeeded(
9169                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9170        }
9171    }
9172
9173    /**
9174     * Gets the live region mode for this View.
9175     *
9176     * @return The live region mode for the view.
9177     *
9178     * @attr ref android.R.styleable#View_accessibilityLiveRegion
9179     *
9180     * @see #setAccessibilityLiveRegion(int)
9181     */
9182    public int getAccessibilityLiveRegion() {
9183        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
9184                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
9185    }
9186
9187    /**
9188     * Sets how to determine whether this view is important for accessibility
9189     * which is if it fires accessibility events and if it is reported to
9190     * accessibility services that query the screen.
9191     *
9192     * @param mode How to determine whether this view is important for accessibility.
9193     *
9194     * @attr ref android.R.styleable#View_importantForAccessibility
9195     *
9196     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
9197     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
9198     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
9199     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
9200     */
9201    public void setImportantForAccessibility(int mode) {
9202        final int oldMode = getImportantForAccessibility();
9203        if (mode != oldMode) {
9204            final boolean hideDescendants =
9205                    mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
9206
9207            // If this node or its descendants are no longer important, try to
9208            // clear accessibility focus.
9209            if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) {
9210                final View focusHost = findAccessibilityFocusHost(hideDescendants);
9211                if (focusHost != null) {
9212                    focusHost.clearAccessibilityFocus();
9213                }
9214            }
9215
9216            // If we're moving between AUTO and another state, we might not need
9217            // to send a subtree changed notification. We'll store the computed
9218            // importance, since we'll need to check it later to make sure.
9219            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
9220                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
9221            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
9222            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9223            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
9224                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
9225            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
9226                notifySubtreeAccessibilityStateChangedIfNeeded();
9227            } else {
9228                notifyViewAccessibilityStateChangedIfNeeded(
9229                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9230            }
9231        }
9232    }
9233
9234    /**
9235     * Returns the view within this view's hierarchy that is hosting
9236     * accessibility focus.
9237     *
9238     * @param searchDescendants whether to search for focus in descendant views
9239     * @return the view hosting accessibility focus, or {@code null}
9240     */
9241    private View findAccessibilityFocusHost(boolean searchDescendants) {
9242        if (isAccessibilityFocusedViewOrHost()) {
9243            return this;
9244        }
9245
9246        if (searchDescendants) {
9247            final ViewRootImpl viewRoot = getViewRootImpl();
9248            if (viewRoot != null) {
9249                final View focusHost = viewRoot.getAccessibilityFocusedHost();
9250                if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
9251                    return focusHost;
9252                }
9253            }
9254        }
9255
9256        return null;
9257    }
9258
9259    /**
9260     * Computes whether this view should be exposed for accessibility. In
9261     * general, views that are interactive or provide information are exposed
9262     * while views that serve only as containers are hidden.
9263     * <p>
9264     * If an ancestor of this view has importance
9265     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
9266     * returns <code>false</code>.
9267     * <p>
9268     * Otherwise, the value is computed according to the view's
9269     * {@link #getImportantForAccessibility()} value:
9270     * <ol>
9271     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
9272     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
9273     * </code>
9274     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
9275     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
9276     * view satisfies any of the following:
9277     * <ul>
9278     * <li>Is actionable, e.g. {@link #isClickable()},
9279     * {@link #isLongClickable()}, or {@link #isFocusable()}
9280     * <li>Has an {@link AccessibilityDelegate}
9281     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
9282     * {@link OnKeyListener}, etc.
9283     * <li>Is an accessibility live region, e.g.
9284     * {@link #getAccessibilityLiveRegion()} is not
9285     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
9286     * </ul>
9287     * </ol>
9288     *
9289     * @return Whether the view is exposed for accessibility.
9290     * @see #setImportantForAccessibility(int)
9291     * @see #getImportantForAccessibility()
9292     */
9293    public boolean isImportantForAccessibility() {
9294        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
9295                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
9296        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
9297                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9298            return false;
9299        }
9300
9301        // Check parent mode to ensure we're not hidden.
9302        ViewParent parent = mParent;
9303        while (parent instanceof View) {
9304            if (((View) parent).getImportantForAccessibility()
9305                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
9306                return false;
9307            }
9308            parent = parent.getParent();
9309        }
9310
9311        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
9312                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
9313                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
9314    }
9315
9316    /**
9317     * Gets the parent for accessibility purposes. Note that the parent for
9318     * accessibility is not necessary the immediate parent. It is the first
9319     * predecessor that is important for accessibility.
9320     *
9321     * @return The parent for accessibility purposes.
9322     */
9323    public ViewParent getParentForAccessibility() {
9324        if (mParent instanceof View) {
9325            View parentView = (View) mParent;
9326            if (parentView.includeForAccessibility()) {
9327                return mParent;
9328            } else {
9329                return mParent.getParentForAccessibility();
9330            }
9331        }
9332        return null;
9333    }
9334
9335    /**
9336     * Adds the children of this View relevant for accessibility to the given list
9337     * as output. Since some Views are not important for accessibility the added
9338     * child views are not necessarily direct children of this view, rather they are
9339     * the first level of descendants important for accessibility.
9340     *
9341     * @param outChildren The output list that will receive children for accessibility.
9342     */
9343    public void addChildrenForAccessibility(ArrayList<View> outChildren) {
9344
9345    }
9346
9347    /**
9348     * Whether to regard this view for accessibility. A view is regarded for
9349     * accessibility if it is important for accessibility or the querying
9350     * accessibility service has explicitly requested that view not
9351     * important for accessibility are regarded.
9352     *
9353     * @return Whether to regard the view for accessibility.
9354     *
9355     * @hide
9356     */
9357    public boolean includeForAccessibility() {
9358        if (mAttachInfo != null) {
9359            return (mAttachInfo.mAccessibilityFetchFlags
9360                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
9361                    || isImportantForAccessibility();
9362        }
9363        return false;
9364    }
9365
9366    /**
9367     * Returns whether the View is considered actionable from
9368     * accessibility perspective. Such view are important for
9369     * accessibility.
9370     *
9371     * @return True if the view is actionable for accessibility.
9372     *
9373     * @hide
9374     */
9375    public boolean isActionableForAccessibility() {
9376        return (isClickable() || isLongClickable() || isFocusable());
9377    }
9378
9379    /**
9380     * Returns whether the View has registered callbacks which makes it
9381     * important for accessibility.
9382     *
9383     * @return True if the view is actionable for accessibility.
9384     */
9385    private boolean hasListenersForAccessibility() {
9386        ListenerInfo info = getListenerInfo();
9387        return mTouchDelegate != null || info.mOnKeyListener != null
9388                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
9389                || info.mOnHoverListener != null || info.mOnDragListener != null;
9390    }
9391
9392    /**
9393     * Notifies that the accessibility state of this view changed. The change
9394     * is local to this view and does not represent structural changes such
9395     * as children and parent. For example, the view became focusable. The
9396     * notification is at at most once every
9397     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9398     * to avoid unnecessary load to the system. Also once a view has a pending
9399     * notification this method is a NOP until the notification has been sent.
9400     *
9401     * @hide
9402     */
9403    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
9404        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9405            return;
9406        }
9407        if (mSendViewStateChangedAccessibilityEvent == null) {
9408            mSendViewStateChangedAccessibilityEvent =
9409                    new SendViewStateChangedAccessibilityEvent();
9410        }
9411        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
9412    }
9413
9414    /**
9415     * Notifies that the accessibility state of this view changed. The change
9416     * is *not* local to this view and does represent structural changes such
9417     * as children and parent. For example, the view size changed. The
9418     * notification is at at most once every
9419     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
9420     * to avoid unnecessary load to the system. Also once a view has a pending
9421     * notification this method is a NOP until the notification has been sent.
9422     *
9423     * @hide
9424     */
9425    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
9426        if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) {
9427            return;
9428        }
9429        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
9430            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9431            if (mParent != null) {
9432                try {
9433                    mParent.notifySubtreeAccessibilityStateChanged(
9434                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
9435                } catch (AbstractMethodError e) {
9436                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
9437                            " does not fully implement ViewParent", e);
9438                }
9439            }
9440        }
9441    }
9442
9443    /**
9444     * Change the visibility of the View without triggering any other changes. This is
9445     * important for transitions, where visibility changes should not adjust focus or
9446     * trigger a new layout. This is only used when the visibility has already been changed
9447     * and we need a transient value during an animation. When the animation completes,
9448     * the original visibility value is always restored.
9449     *
9450     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
9451     * @hide
9452     */
9453    public void setTransitionVisibility(@Visibility int visibility) {
9454        mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility;
9455    }
9456
9457    /**
9458     * Reset the flag indicating the accessibility state of the subtree rooted
9459     * at this view changed.
9460     */
9461    void resetSubtreeAccessibilityStateChanged() {
9462        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
9463    }
9464
9465    /**
9466     * Report an accessibility action to this view's parents for delegated processing.
9467     *
9468     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
9469     * call this method to delegate an accessibility action to a supporting parent. If the parent
9470     * returns true from its
9471     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
9472     * method this method will return true to signify that the action was consumed.</p>
9473     *
9474     * <p>This method is useful for implementing nested scrolling child views. If
9475     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
9476     * a custom view implementation may invoke this method to allow a parent to consume the
9477     * scroll first. If this method returns true the custom view should skip its own scrolling
9478     * behavior.</p>
9479     *
9480     * @param action Accessibility action to delegate
9481     * @param arguments Optional action arguments
9482     * @return true if the action was consumed by a parent
9483     */
9484    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
9485        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
9486            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
9487                return true;
9488            }
9489        }
9490        return false;
9491    }
9492
9493    /**
9494     * Performs the specified accessibility action on the view. For
9495     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
9496     * <p>
9497     * If an {@link AccessibilityDelegate} has been specified via calling
9498     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
9499     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
9500     * is responsible for handling this call.
9501     * </p>
9502     *
9503     * <p>The default implementation will delegate
9504     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
9505     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
9506     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
9507     *
9508     * @param action The action to perform.
9509     * @param arguments Optional action arguments.
9510     * @return Whether the action was performed.
9511     */
9512    public boolean performAccessibilityAction(int action, Bundle arguments) {
9513      if (mAccessibilityDelegate != null) {
9514          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
9515      } else {
9516          return performAccessibilityActionInternal(action, arguments);
9517      }
9518    }
9519
9520   /**
9521    * @see #performAccessibilityAction(int, Bundle)
9522    *
9523    * Note: Called from the default {@link AccessibilityDelegate}.
9524    *
9525    * @hide
9526    */
9527    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
9528        if (isNestedScrollingEnabled()
9529                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
9530                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
9531                || action == R.id.accessibilityActionScrollUp
9532                || action == R.id.accessibilityActionScrollLeft
9533                || action == R.id.accessibilityActionScrollDown
9534                || action == R.id.accessibilityActionScrollRight)) {
9535            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
9536                return true;
9537            }
9538        }
9539
9540        switch (action) {
9541            case AccessibilityNodeInfo.ACTION_CLICK: {
9542                if (isClickable()) {
9543                    performClick();
9544                    return true;
9545                }
9546            } break;
9547            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
9548                if (isLongClickable()) {
9549                    performLongClick();
9550                    return true;
9551                }
9552            } break;
9553            case AccessibilityNodeInfo.ACTION_FOCUS: {
9554                if (!hasFocus()) {
9555                    // Get out of touch mode since accessibility
9556                    // wants to move focus around.
9557                    getViewRootImpl().ensureTouchMode(false);
9558                    return requestFocus();
9559                }
9560            } break;
9561            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
9562                if (hasFocus()) {
9563                    clearFocus();
9564                    return !isFocused();
9565                }
9566            } break;
9567            case AccessibilityNodeInfo.ACTION_SELECT: {
9568                if (!isSelected()) {
9569                    setSelected(true);
9570                    return isSelected();
9571                }
9572            } break;
9573            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
9574                if (isSelected()) {
9575                    setSelected(false);
9576                    return !isSelected();
9577                }
9578            } break;
9579            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
9580                if (!isAccessibilityFocused()) {
9581                    return requestAccessibilityFocus();
9582                }
9583            } break;
9584            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
9585                if (isAccessibilityFocused()) {
9586                    clearAccessibilityFocus();
9587                    return true;
9588                }
9589            } break;
9590            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
9591                if (arguments != null) {
9592                    final int granularity = arguments.getInt(
9593                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9594                    final boolean extendSelection = arguments.getBoolean(
9595                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9596                    return traverseAtGranularity(granularity, true, extendSelection);
9597                }
9598            } break;
9599            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
9600                if (arguments != null) {
9601                    final int granularity = arguments.getInt(
9602                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
9603                    final boolean extendSelection = arguments.getBoolean(
9604                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
9605                    return traverseAtGranularity(granularity, false, extendSelection);
9606                }
9607            } break;
9608            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
9609                CharSequence text = getIterableTextForAccessibility();
9610                if (text == null) {
9611                    return false;
9612                }
9613                final int start = (arguments != null) ? arguments.getInt(
9614                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
9615                final int end = (arguments != null) ? arguments.getInt(
9616                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
9617                // Only cursor position can be specified (selection length == 0)
9618                if ((getAccessibilitySelectionStart() != start
9619                        || getAccessibilitySelectionEnd() != end)
9620                        && (start == end)) {
9621                    setAccessibilitySelection(start, end);
9622                    notifyViewAccessibilityStateChangedIfNeeded(
9623                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9624                    return true;
9625                }
9626            } break;
9627            case R.id.accessibilityActionShowOnScreen: {
9628                if (mAttachInfo != null) {
9629                    final Rect r = mAttachInfo.mTmpInvalRect;
9630                    getDrawingRect(r);
9631                    return requestRectangleOnScreen(r, true);
9632                }
9633            } break;
9634            case R.id.accessibilityActionContextClick: {
9635                if (isContextClickable()) {
9636                    performContextClick();
9637                    return true;
9638                }
9639            } break;
9640        }
9641        return false;
9642    }
9643
9644    private boolean traverseAtGranularity(int granularity, boolean forward,
9645            boolean extendSelection) {
9646        CharSequence text = getIterableTextForAccessibility();
9647        if (text == null || text.length() == 0) {
9648            return false;
9649        }
9650        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
9651        if (iterator == null) {
9652            return false;
9653        }
9654        int current = getAccessibilitySelectionEnd();
9655        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9656            current = forward ? 0 : text.length();
9657        }
9658        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
9659        if (range == null) {
9660            return false;
9661        }
9662        final int segmentStart = range[0];
9663        final int segmentEnd = range[1];
9664        int selectionStart;
9665        int selectionEnd;
9666        if (extendSelection && isAccessibilitySelectionExtendable()) {
9667            selectionStart = getAccessibilitySelectionStart();
9668            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
9669                selectionStart = forward ? segmentStart : segmentEnd;
9670            }
9671            selectionEnd = forward ? segmentEnd : segmentStart;
9672        } else {
9673            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
9674        }
9675        setAccessibilitySelection(selectionStart, selectionEnd);
9676        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
9677                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
9678        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
9679        return true;
9680    }
9681
9682    /**
9683     * Gets the text reported for accessibility purposes.
9684     *
9685     * @return The accessibility text.
9686     *
9687     * @hide
9688     */
9689    public CharSequence getIterableTextForAccessibility() {
9690        return getContentDescription();
9691    }
9692
9693    /**
9694     * Gets whether accessibility selection can be extended.
9695     *
9696     * @return If selection is extensible.
9697     *
9698     * @hide
9699     */
9700    public boolean isAccessibilitySelectionExtendable() {
9701        return false;
9702    }
9703
9704    /**
9705     * @hide
9706     */
9707    public int getAccessibilitySelectionStart() {
9708        return mAccessibilityCursorPosition;
9709    }
9710
9711    /**
9712     * @hide
9713     */
9714    public int getAccessibilitySelectionEnd() {
9715        return getAccessibilitySelectionStart();
9716    }
9717
9718    /**
9719     * @hide
9720     */
9721    public void setAccessibilitySelection(int start, int end) {
9722        if (start ==  end && end == mAccessibilityCursorPosition) {
9723            return;
9724        }
9725        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
9726            mAccessibilityCursorPosition = start;
9727        } else {
9728            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
9729        }
9730        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
9731    }
9732
9733    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
9734            int fromIndex, int toIndex) {
9735        if (mParent == null) {
9736            return;
9737        }
9738        AccessibilityEvent event = AccessibilityEvent.obtain(
9739                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
9740        onInitializeAccessibilityEvent(event);
9741        onPopulateAccessibilityEvent(event);
9742        event.setFromIndex(fromIndex);
9743        event.setToIndex(toIndex);
9744        event.setAction(action);
9745        event.setMovementGranularity(granularity);
9746        mParent.requestSendAccessibilityEvent(this, event);
9747    }
9748
9749    /**
9750     * @hide
9751     */
9752    public TextSegmentIterator getIteratorForGranularity(int granularity) {
9753        switch (granularity) {
9754            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
9755                CharSequence text = getIterableTextForAccessibility();
9756                if (text != null && text.length() > 0) {
9757                    CharacterTextSegmentIterator iterator =
9758                        CharacterTextSegmentIterator.getInstance(
9759                                mContext.getResources().getConfiguration().locale);
9760                    iterator.initialize(text.toString());
9761                    return iterator;
9762                }
9763            } break;
9764            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
9765                CharSequence text = getIterableTextForAccessibility();
9766                if (text != null && text.length() > 0) {
9767                    WordTextSegmentIterator iterator =
9768                        WordTextSegmentIterator.getInstance(
9769                                mContext.getResources().getConfiguration().locale);
9770                    iterator.initialize(text.toString());
9771                    return iterator;
9772                }
9773            } break;
9774            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
9775                CharSequence text = getIterableTextForAccessibility();
9776                if (text != null && text.length() > 0) {
9777                    ParagraphTextSegmentIterator iterator =
9778                        ParagraphTextSegmentIterator.getInstance();
9779                    iterator.initialize(text.toString());
9780                    return iterator;
9781                }
9782            } break;
9783        }
9784        return null;
9785    }
9786
9787    /**
9788     * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()}
9789     * and {@link #onFinishTemporaryDetach()}.
9790     */
9791    public final boolean isTemporarilyDetached() {
9792        return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0;
9793    }
9794
9795    /**
9796     * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is
9797     * a container View.
9798     */
9799    @CallSuper
9800    public void dispatchStartTemporaryDetach() {
9801        mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH;
9802        onStartTemporaryDetach();
9803    }
9804
9805    /**
9806     * This is called when a container is going to temporarily detach a child, with
9807     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
9808     * It will either be followed by {@link #onFinishTemporaryDetach()} or
9809     * {@link #onDetachedFromWindow()} when the container is done.
9810     */
9811    public void onStartTemporaryDetach() {
9812        removeUnsetPressCallback();
9813        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
9814    }
9815
9816    /**
9817     * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is
9818     * a container View.
9819     */
9820    @CallSuper
9821    public void dispatchFinishTemporaryDetach() {
9822        onFinishTemporaryDetach();
9823        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
9824    }
9825
9826    /**
9827     * Called after {@link #onStartTemporaryDetach} when the container is done
9828     * changing the view.
9829     */
9830    public void onFinishTemporaryDetach() {
9831    }
9832
9833    /**
9834     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
9835     * for this view's window.  Returns null if the view is not currently attached
9836     * to the window.  Normally you will not need to use this directly, but
9837     * just use the standard high-level event callbacks like
9838     * {@link #onKeyDown(int, KeyEvent)}.
9839     */
9840    public KeyEvent.DispatcherState getKeyDispatcherState() {
9841        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
9842    }
9843
9844    /**
9845     * Dispatch a key event before it is processed by any input method
9846     * associated with the view hierarchy.  This can be used to intercept
9847     * key events in special situations before the IME consumes them; a
9848     * typical example would be handling the BACK key to update the application's
9849     * UI instead of allowing the IME to see it and close itself.
9850     *
9851     * @param event The key event to be dispatched.
9852     * @return True if the event was handled, false otherwise.
9853     */
9854    public boolean dispatchKeyEventPreIme(KeyEvent event) {
9855        return onKeyPreIme(event.getKeyCode(), event);
9856    }
9857
9858    /**
9859     * Dispatch a key event to the next view on the focus path. This path runs
9860     * from the top of the view tree down to the currently focused view. If this
9861     * view has focus, it will dispatch to itself. Otherwise it will dispatch
9862     * the next node down the focus path. This method also fires any key
9863     * listeners.
9864     *
9865     * @param event The key event to be dispatched.
9866     * @return True if the event was handled, false otherwise.
9867     */
9868    public boolean dispatchKeyEvent(KeyEvent event) {
9869        if (mInputEventConsistencyVerifier != null) {
9870            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
9871        }
9872
9873        // Give any attached key listener a first crack at the event.
9874        //noinspection SimplifiableIfStatement
9875        ListenerInfo li = mListenerInfo;
9876        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
9877                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
9878            return true;
9879        }
9880
9881        if (event.dispatch(this, mAttachInfo != null
9882                ? mAttachInfo.mKeyDispatchState : null, this)) {
9883            return true;
9884        }
9885
9886        if (mInputEventConsistencyVerifier != null) {
9887            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9888        }
9889        return false;
9890    }
9891
9892    /**
9893     * Dispatches a key shortcut event.
9894     *
9895     * @param event The key event to be dispatched.
9896     * @return True if the event was handled by the view, false otherwise.
9897     */
9898    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
9899        return onKeyShortcut(event.getKeyCode(), event);
9900    }
9901
9902    /**
9903     * Pass the touch screen motion event down to the target view, or this
9904     * view if it is the target.
9905     *
9906     * @param event The motion event to be dispatched.
9907     * @return True if the event was handled by the view, false otherwise.
9908     */
9909    public boolean dispatchTouchEvent(MotionEvent event) {
9910        // If the event should be handled by accessibility focus first.
9911        if (event.isTargetAccessibilityFocus()) {
9912            // We don't have focus or no virtual descendant has it, do not handle the event.
9913            if (!isAccessibilityFocusedViewOrHost()) {
9914                return false;
9915            }
9916            // We have focus and got the event, then use normal event dispatch.
9917            event.setTargetAccessibilityFocus(false);
9918        }
9919
9920        boolean result = false;
9921
9922        if (mInputEventConsistencyVerifier != null) {
9923            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
9924        }
9925
9926        final int actionMasked = event.getActionMasked();
9927        if (actionMasked == MotionEvent.ACTION_DOWN) {
9928            // Defensive cleanup for new gesture
9929            stopNestedScroll();
9930        }
9931
9932        if (onFilterTouchEventForSecurity(event)) {
9933            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
9934                result = true;
9935            }
9936            //noinspection SimplifiableIfStatement
9937            ListenerInfo li = mListenerInfo;
9938            if (li != null && li.mOnTouchListener != null
9939                    && (mViewFlags & ENABLED_MASK) == ENABLED
9940                    && li.mOnTouchListener.onTouch(this, event)) {
9941                result = true;
9942            }
9943
9944            if (!result && onTouchEvent(event)) {
9945                result = true;
9946            }
9947        }
9948
9949        if (!result && mInputEventConsistencyVerifier != null) {
9950            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9951        }
9952
9953        // Clean up after nested scrolls if this is the end of a gesture;
9954        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9955        // of the gesture.
9956        if (actionMasked == MotionEvent.ACTION_UP ||
9957                actionMasked == MotionEvent.ACTION_CANCEL ||
9958                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9959            stopNestedScroll();
9960        }
9961
9962        return result;
9963    }
9964
9965    boolean isAccessibilityFocusedViewOrHost() {
9966        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9967                .getAccessibilityFocusedHost() == this);
9968    }
9969
9970    /**
9971     * Filter the touch event to apply security policies.
9972     *
9973     * @param event The motion event to be filtered.
9974     * @return True if the event should be dispatched, false if the event should be dropped.
9975     *
9976     * @see #getFilterTouchesWhenObscured
9977     */
9978    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9979        //noinspection RedundantIfStatement
9980        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9981                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9982            // Window is obscured, drop this touch.
9983            return false;
9984        }
9985        return true;
9986    }
9987
9988    /**
9989     * Pass a trackball motion event down to the focused view.
9990     *
9991     * @param event The motion event to be dispatched.
9992     * @return True if the event was handled by the view, false otherwise.
9993     */
9994    public boolean dispatchTrackballEvent(MotionEvent event) {
9995        if (mInputEventConsistencyVerifier != null) {
9996            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9997        }
9998
9999        return onTrackballEvent(event);
10000    }
10001
10002    /**
10003     * Dispatch a generic motion event.
10004     * <p>
10005     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10006     * are delivered to the view under the pointer.  All other generic motion events are
10007     * delivered to the focused view.  Hover events are handled specially and are delivered
10008     * to {@link #onHoverEvent(MotionEvent)}.
10009     * </p>
10010     *
10011     * @param event The motion event to be dispatched.
10012     * @return True if the event was handled by the view, false otherwise.
10013     */
10014    public boolean dispatchGenericMotionEvent(MotionEvent event) {
10015        if (mInputEventConsistencyVerifier != null) {
10016            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
10017        }
10018
10019        final int source = event.getSource();
10020        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
10021            final int action = event.getAction();
10022            if (action == MotionEvent.ACTION_HOVER_ENTER
10023                    || action == MotionEvent.ACTION_HOVER_MOVE
10024                    || action == MotionEvent.ACTION_HOVER_EXIT) {
10025                if (dispatchHoverEvent(event)) {
10026                    return true;
10027                }
10028            } else if (dispatchGenericPointerEvent(event)) {
10029                return true;
10030            }
10031        } else if (dispatchGenericFocusedEvent(event)) {
10032            return true;
10033        }
10034
10035        if (dispatchGenericMotionEventInternal(event)) {
10036            return true;
10037        }
10038
10039        if (mInputEventConsistencyVerifier != null) {
10040            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10041        }
10042        return false;
10043    }
10044
10045    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
10046        //noinspection SimplifiableIfStatement
10047        ListenerInfo li = mListenerInfo;
10048        if (li != null && li.mOnGenericMotionListener != null
10049                && (mViewFlags & ENABLED_MASK) == ENABLED
10050                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
10051            return true;
10052        }
10053
10054        if (onGenericMotionEvent(event)) {
10055            return true;
10056        }
10057
10058        final int actionButton = event.getActionButton();
10059        switch (event.getActionMasked()) {
10060            case MotionEvent.ACTION_BUTTON_PRESS:
10061                if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress
10062                        && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10063                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10064                    if (performContextClick(event.getX(), event.getY())) {
10065                        mInContextButtonPress = true;
10066                        setPressed(true, event.getX(), event.getY());
10067                        removeTapCallback();
10068                        removeLongPressCallback();
10069                        return true;
10070                    }
10071                }
10072                break;
10073
10074            case MotionEvent.ACTION_BUTTON_RELEASE:
10075                if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY
10076                        || actionButton == MotionEvent.BUTTON_SECONDARY)) {
10077                    mInContextButtonPress = false;
10078                    mIgnoreNextUpEvent = true;
10079                }
10080                break;
10081        }
10082
10083        if (mInputEventConsistencyVerifier != null) {
10084            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
10085        }
10086        return false;
10087    }
10088
10089    /**
10090     * Dispatch a hover event.
10091     * <p>
10092     * Do not call this method directly.
10093     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10094     * </p>
10095     *
10096     * @param event The motion event to be dispatched.
10097     * @return True if the event was handled by the view, false otherwise.
10098     */
10099    protected boolean dispatchHoverEvent(MotionEvent event) {
10100        ListenerInfo li = mListenerInfo;
10101        //noinspection SimplifiableIfStatement
10102        if (li != null && li.mOnHoverListener != null
10103                && (mViewFlags & ENABLED_MASK) == ENABLED
10104                && li.mOnHoverListener.onHover(this, event)) {
10105            return true;
10106        }
10107
10108        return onHoverEvent(event);
10109    }
10110
10111    /**
10112     * Returns true if the view has a child to which it has recently sent
10113     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
10114     * it does not have a hovered child, then it must be the innermost hovered view.
10115     * @hide
10116     */
10117    protected boolean hasHoveredChild() {
10118        return false;
10119    }
10120
10121    /**
10122     * Dispatch a generic motion event to the view under the first pointer.
10123     * <p>
10124     * Do not call this method directly.
10125     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10126     * </p>
10127     *
10128     * @param event The motion event to be dispatched.
10129     * @return True if the event was handled by the view, false otherwise.
10130     */
10131    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
10132        return false;
10133    }
10134
10135    /**
10136     * Dispatch a generic motion event to the currently focused view.
10137     * <p>
10138     * Do not call this method directly.
10139     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
10140     * </p>
10141     *
10142     * @param event The motion event to be dispatched.
10143     * @return True if the event was handled by the view, false otherwise.
10144     */
10145    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
10146        return false;
10147    }
10148
10149    /**
10150     * Dispatch a pointer event.
10151     * <p>
10152     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
10153     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
10154     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
10155     * and should not be expected to handle other pointing device features.
10156     * </p>
10157     *
10158     * @param event The motion event to be dispatched.
10159     * @return True if the event was handled by the view, false otherwise.
10160     * @hide
10161     */
10162    public final boolean dispatchPointerEvent(MotionEvent event) {
10163        if (event.isTouchEvent()) {
10164            return dispatchTouchEvent(event);
10165        } else {
10166            return dispatchGenericMotionEvent(event);
10167        }
10168    }
10169
10170    /**
10171     * Called when the window containing this view gains or loses window focus.
10172     * ViewGroups should override to route to their children.
10173     *
10174     * @param hasFocus True if the window containing this view now has focus,
10175     *        false otherwise.
10176     */
10177    public void dispatchWindowFocusChanged(boolean hasFocus) {
10178        onWindowFocusChanged(hasFocus);
10179    }
10180
10181    /**
10182     * Called when the window containing this view gains or loses focus.  Note
10183     * that this is separate from view focus: to receive key events, both
10184     * your view and its window must have focus.  If a window is displayed
10185     * on top of yours that takes input focus, then your own window will lose
10186     * focus but the view focus will remain unchanged.
10187     *
10188     * @param hasWindowFocus True if the window containing this view now has
10189     *        focus, false otherwise.
10190     */
10191    public void onWindowFocusChanged(boolean hasWindowFocus) {
10192        InputMethodManager imm = InputMethodManager.peekInstance();
10193        if (!hasWindowFocus) {
10194            if (isPressed()) {
10195                setPressed(false);
10196            }
10197            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10198                imm.focusOut(this);
10199            }
10200            removeLongPressCallback();
10201            removeTapCallback();
10202            onFocusLost();
10203        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
10204            imm.focusIn(this);
10205        }
10206        refreshDrawableState();
10207    }
10208
10209    /**
10210     * Returns true if this view is in a window that currently has window focus.
10211     * Note that this is not the same as the view itself having focus.
10212     *
10213     * @return True if this view is in a window that currently has window focus.
10214     */
10215    public boolean hasWindowFocus() {
10216        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
10217    }
10218
10219    /**
10220     * Dispatch a view visibility change down the view hierarchy.
10221     * ViewGroups should override to route to their children.
10222     * @param changedView The view whose visibility changed. Could be 'this' or
10223     * an ancestor view.
10224     * @param visibility The new visibility of changedView: {@link #VISIBLE},
10225     * {@link #INVISIBLE} or {@link #GONE}.
10226     */
10227    protected void dispatchVisibilityChanged(@NonNull View changedView,
10228            @Visibility int visibility) {
10229        onVisibilityChanged(changedView, visibility);
10230    }
10231
10232    /**
10233     * Called when the visibility of the view or an ancestor of the view has
10234     * changed.
10235     *
10236     * @param changedView The view whose visibility changed. May be
10237     *                    {@code this} or an ancestor view.
10238     * @param visibility The new visibility, one of {@link #VISIBLE},
10239     *                   {@link #INVISIBLE} or {@link #GONE}.
10240     */
10241    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
10242    }
10243
10244    /**
10245     * Dispatch a hint about whether this view is displayed. For instance, when
10246     * a View moves out of the screen, it might receives a display hint indicating
10247     * the view is not displayed. Applications should not <em>rely</em> on this hint
10248     * as there is no guarantee that they will receive one.
10249     *
10250     * @param hint A hint about whether or not this view is displayed:
10251     * {@link #VISIBLE} or {@link #INVISIBLE}.
10252     */
10253    public void dispatchDisplayHint(@Visibility int hint) {
10254        onDisplayHint(hint);
10255    }
10256
10257    /**
10258     * Gives this view a hint about whether is displayed or not. For instance, when
10259     * a View moves out of the screen, it might receives a display hint indicating
10260     * the view is not displayed. Applications should not <em>rely</em> on this hint
10261     * as there is no guarantee that they will receive one.
10262     *
10263     * @param hint A hint about whether or not this view is displayed:
10264     * {@link #VISIBLE} or {@link #INVISIBLE}.
10265     */
10266    protected void onDisplayHint(@Visibility int hint) {
10267    }
10268
10269    /**
10270     * Dispatch a window visibility change down the view hierarchy.
10271     * ViewGroups should override to route to their children.
10272     *
10273     * @param visibility The new visibility of the window.
10274     *
10275     * @see #onWindowVisibilityChanged(int)
10276     */
10277    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
10278        onWindowVisibilityChanged(visibility);
10279    }
10280
10281    /**
10282     * Called when the window containing has change its visibility
10283     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
10284     * that this tells you whether or not your window is being made visible
10285     * to the window manager; this does <em>not</em> tell you whether or not
10286     * your window is obscured by other windows on the screen, even if it
10287     * is itself visible.
10288     *
10289     * @param visibility The new visibility of the window.
10290     */
10291    protected void onWindowVisibilityChanged(@Visibility int visibility) {
10292        if (visibility == VISIBLE) {
10293            initialAwakenScrollBars();
10294        }
10295    }
10296
10297    /**
10298     * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by
10299     * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()},
10300     * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}.
10301     *
10302     * @param isVisible true if this view's visibility to the user is uninterrupted by its
10303     *                  ancestors or by window visibility
10304     * @return true if this view is visible to the user, not counting clipping or overlapping
10305     */
10306    @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) {
10307        final boolean thisVisible = getVisibility() == VISIBLE;
10308        // If we're not visible but something is telling us we are, ignore it.
10309        if (thisVisible || !isVisible) {
10310            onVisibilityAggregated(isVisible);
10311        }
10312        return thisVisible && isVisible;
10313    }
10314
10315    /**
10316     * Called when the user-visibility of this View is potentially affected by a change
10317     * to this view itself, an ancestor view or the window this view is attached to.
10318     *
10319     * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE}
10320     *                  and this view's window is also visible
10321     */
10322    @CallSuper
10323    public void onVisibilityAggregated(boolean isVisible) {
10324        if (isVisible && mAttachInfo != null) {
10325            initialAwakenScrollBars();
10326        }
10327
10328        final Drawable dr = mBackground;
10329        if (dr != null && isVisible != dr.isVisible()) {
10330            dr.setVisible(isVisible, false);
10331        }
10332        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
10333        if (fg != null && isVisible != fg.isVisible()) {
10334            fg.setVisible(isVisible, false);
10335        }
10336    }
10337
10338    /**
10339     * Returns the current visibility of the window this view is attached to
10340     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
10341     *
10342     * @return Returns the current visibility of the view's window.
10343     */
10344    @Visibility
10345    public int getWindowVisibility() {
10346        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
10347    }
10348
10349    /**
10350     * Retrieve the overall visible display size in which the window this view is
10351     * attached to has been positioned in.  This takes into account screen
10352     * decorations above the window, for both cases where the window itself
10353     * is being position inside of them or the window is being placed under
10354     * then and covered insets are used for the window to position its content
10355     * inside.  In effect, this tells you the available area where content can
10356     * be placed and remain visible to users.
10357     *
10358     * <p>This function requires an IPC back to the window manager to retrieve
10359     * the requested information, so should not be used in performance critical
10360     * code like drawing.
10361     *
10362     * @param outRect Filled in with the visible display frame.  If the view
10363     * is not attached to a window, this is simply the raw display size.
10364     */
10365    public void getWindowVisibleDisplayFrame(Rect outRect) {
10366        if (mAttachInfo != null) {
10367            try {
10368                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10369            } catch (RemoteException e) {
10370                return;
10371            }
10372            // XXX This is really broken, and probably all needs to be done
10373            // in the window manager, and we need to know more about whether
10374            // we want the area behind or in front of the IME.
10375            final Rect insets = mAttachInfo.mVisibleInsets;
10376            outRect.left += insets.left;
10377            outRect.top += insets.top;
10378            outRect.right -= insets.right;
10379            outRect.bottom -= insets.bottom;
10380            return;
10381        }
10382        // The view is not attached to a display so we don't have a context.
10383        // Make a best guess about the display size.
10384        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10385        d.getRectSize(outRect);
10386    }
10387
10388    /**
10389     * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window
10390     * is currently in without any insets.
10391     *
10392     * @hide
10393     */
10394    public void getWindowDisplayFrame(Rect outRect) {
10395        if (mAttachInfo != null) {
10396            try {
10397                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
10398            } catch (RemoteException e) {
10399                return;
10400            }
10401            return;
10402        }
10403        // The view is not attached to a display so we don't have a context.
10404        // Make a best guess about the display size.
10405        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
10406        d.getRectSize(outRect);
10407    }
10408
10409    /**
10410     * Dispatch a notification about a resource configuration change down
10411     * the view hierarchy.
10412     * ViewGroups should override to route to their children.
10413     *
10414     * @param newConfig The new resource configuration.
10415     *
10416     * @see #onConfigurationChanged(android.content.res.Configuration)
10417     */
10418    public void dispatchConfigurationChanged(Configuration newConfig) {
10419        onConfigurationChanged(newConfig);
10420    }
10421
10422    /**
10423     * Called when the current configuration of the resources being used
10424     * by the application have changed.  You can use this to decide when
10425     * to reload resources that can changed based on orientation and other
10426     * configuration characteristics.  You only need to use this if you are
10427     * not relying on the normal {@link android.app.Activity} mechanism of
10428     * recreating the activity instance upon a configuration change.
10429     *
10430     * @param newConfig The new resource configuration.
10431     */
10432    protected void onConfigurationChanged(Configuration newConfig) {
10433    }
10434
10435    /**
10436     * Private function to aggregate all per-view attributes in to the view
10437     * root.
10438     */
10439    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10440        performCollectViewAttributes(attachInfo, visibility);
10441    }
10442
10443    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
10444        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
10445            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
10446                attachInfo.mKeepScreenOn = true;
10447            }
10448            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
10449            ListenerInfo li = mListenerInfo;
10450            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
10451                attachInfo.mHasSystemUiListeners = true;
10452            }
10453        }
10454    }
10455
10456    void needGlobalAttributesUpdate(boolean force) {
10457        final AttachInfo ai = mAttachInfo;
10458        if (ai != null && !ai.mRecomputeGlobalAttributes) {
10459            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
10460                    || ai.mHasSystemUiListeners) {
10461                ai.mRecomputeGlobalAttributes = true;
10462            }
10463        }
10464    }
10465
10466    /**
10467     * Returns whether the device is currently in touch mode.  Touch mode is entered
10468     * once the user begins interacting with the device by touch, and affects various
10469     * things like whether focus is always visible to the user.
10470     *
10471     * @return Whether the device is in touch mode.
10472     */
10473    @ViewDebug.ExportedProperty
10474    public boolean isInTouchMode() {
10475        if (mAttachInfo != null) {
10476            return mAttachInfo.mInTouchMode;
10477        } else {
10478            return ViewRootImpl.isInTouchMode();
10479        }
10480    }
10481
10482    /**
10483     * Returns the context the view is running in, through which it can
10484     * access the current theme, resources, etc.
10485     *
10486     * @return The view's Context.
10487     */
10488    @ViewDebug.CapturedViewProperty
10489    public final Context getContext() {
10490        return mContext;
10491    }
10492
10493    /**
10494     * Handle a key event before it is processed by any input method
10495     * associated with the view hierarchy.  This can be used to intercept
10496     * key events in special situations before the IME consumes them; a
10497     * typical example would be handling the BACK key to update the application's
10498     * UI instead of allowing the IME to see it and close itself.
10499     *
10500     * @param keyCode The value in event.getKeyCode().
10501     * @param event Description of the key event.
10502     * @return If you handled the event, return true. If you want to allow the
10503     *         event to be handled by the next receiver, return false.
10504     */
10505    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
10506        return false;
10507    }
10508
10509    /**
10510     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
10511     * KeyEvent.Callback.onKeyDown()}: perform press of the view
10512     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
10513     * is released, if the view is enabled and clickable.
10514     * <p>
10515     * Key presses in software keyboards will generally NOT trigger this
10516     * listener, although some may elect to do so in some situations. Do not
10517     * rely on this to catch software key presses.
10518     *
10519     * @param keyCode a key code that represents the button pressed, from
10520     *                {@link android.view.KeyEvent}
10521     * @param event the KeyEvent object that defines the button action
10522     */
10523    public boolean onKeyDown(int keyCode, KeyEvent event) {
10524        if (KeyEvent.isConfirmKey(keyCode)) {
10525            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10526                return true;
10527            }
10528
10529            // Long clickable items don't necessarily have to be clickable.
10530            if (((mViewFlags & CLICKABLE) == CLICKABLE
10531                    || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
10532                    && (event.getRepeatCount() == 0)) {
10533                // For the purposes of menu anchoring and drawable hotspots,
10534                // key events are considered to be at the center of the view.
10535                final float x = getWidth() / 2f;
10536                final float y = getHeight() / 2f;
10537                setPressed(true, x, y);
10538                checkForLongClick(0, x, y);
10539                return true;
10540            }
10541        }
10542
10543        return false;
10544    }
10545
10546    /**
10547     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
10548     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
10549     * the event).
10550     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10551     * although some may elect to do so in some situations. Do not rely on this to
10552     * catch software key presses.
10553     */
10554    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
10555        return false;
10556    }
10557
10558    /**
10559     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
10560     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
10561     * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER}
10562     * or {@link KeyEvent#KEYCODE_SPACE} is released.
10563     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10564     * although some may elect to do so in some situations. Do not rely on this to
10565     * catch software key presses.
10566     *
10567     * @param keyCode A key code that represents the button pressed, from
10568     *                {@link android.view.KeyEvent}.
10569     * @param event   The KeyEvent object that defines the button action.
10570     */
10571    public boolean onKeyUp(int keyCode, KeyEvent event) {
10572        if (KeyEvent.isConfirmKey(keyCode)) {
10573            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
10574                return true;
10575            }
10576            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
10577                setPressed(false);
10578
10579                if (!mHasPerformedLongPress) {
10580                    // This is a tap, so remove the longpress check
10581                    removeLongPressCallback();
10582                    return performClick();
10583                }
10584            }
10585        }
10586        return false;
10587    }
10588
10589    /**
10590     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
10591     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
10592     * the event).
10593     * <p>Key presses in software keyboards will generally NOT trigger this listener,
10594     * although some may elect to do so in some situations. Do not rely on this to
10595     * catch software key presses.
10596     *
10597     * @param keyCode     A key code that represents the button pressed, from
10598     *                    {@link android.view.KeyEvent}.
10599     * @param repeatCount The number of times the action was made.
10600     * @param event       The KeyEvent object that defines the button action.
10601     */
10602    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
10603        return false;
10604    }
10605
10606    /**
10607     * Called on the focused view when a key shortcut event is not handled.
10608     * Override this method to implement local key shortcuts for the View.
10609     * Key shortcuts can also be implemented by setting the
10610     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
10611     *
10612     * @param keyCode The value in event.getKeyCode().
10613     * @param event Description of the key event.
10614     * @return If you handled the event, return true. If you want to allow the
10615     *         event to be handled by the next receiver, return false.
10616     */
10617    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
10618        return false;
10619    }
10620
10621    /**
10622     * Check whether the called view is a text editor, in which case it
10623     * would make sense to automatically display a soft input window for
10624     * it.  Subclasses should override this if they implement
10625     * {@link #onCreateInputConnection(EditorInfo)} to return true if
10626     * a call on that method would return a non-null InputConnection, and
10627     * they are really a first-class editor that the user would normally
10628     * start typing on when the go into a window containing your view.
10629     *
10630     * <p>The default implementation always returns false.  This does
10631     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
10632     * will not be called or the user can not otherwise perform edits on your
10633     * view; it is just a hint to the system that this is not the primary
10634     * purpose of this view.
10635     *
10636     * @return Returns true if this view is a text editor, else false.
10637     */
10638    public boolean onCheckIsTextEditor() {
10639        return false;
10640    }
10641
10642    /**
10643     * Create a new InputConnection for an InputMethod to interact
10644     * with the view.  The default implementation returns null, since it doesn't
10645     * support input methods.  You can override this to implement such support.
10646     * This is only needed for views that take focus and text input.
10647     *
10648     * <p>When implementing this, you probably also want to implement
10649     * {@link #onCheckIsTextEditor()} to indicate you will return a
10650     * non-null InputConnection.</p>
10651     *
10652     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
10653     * object correctly and in its entirety, so that the connected IME can rely
10654     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
10655     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
10656     * must be filled in with the correct cursor position for IMEs to work correctly
10657     * with your application.</p>
10658     *
10659     * @param outAttrs Fill in with attribute information about the connection.
10660     */
10661    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
10662        return null;
10663    }
10664
10665    /**
10666     * Called by the {@link android.view.inputmethod.InputMethodManager}
10667     * when a view who is not the current
10668     * input connection target is trying to make a call on the manager.  The
10669     * default implementation returns false; you can override this to return
10670     * true for certain views if you are performing InputConnection proxying
10671     * to them.
10672     * @param view The View that is making the InputMethodManager call.
10673     * @return Return true to allow the call, false to reject.
10674     */
10675    public boolean checkInputConnectionProxy(View view) {
10676        return false;
10677    }
10678
10679    /**
10680     * Show the context menu for this view. It is not safe to hold on to the
10681     * menu after returning from this method.
10682     *
10683     * You should normally not overload this method. Overload
10684     * {@link #onCreateContextMenu(ContextMenu)} or define an
10685     * {@link OnCreateContextMenuListener} to add items to the context menu.
10686     *
10687     * @param menu The context menu to populate
10688     */
10689    public void createContextMenu(ContextMenu menu) {
10690        ContextMenuInfo menuInfo = getContextMenuInfo();
10691
10692        // Sets the current menu info so all items added to menu will have
10693        // my extra info set.
10694        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
10695
10696        onCreateContextMenu(menu);
10697        ListenerInfo li = mListenerInfo;
10698        if (li != null && li.mOnCreateContextMenuListener != null) {
10699            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
10700        }
10701
10702        // Clear the extra information so subsequent items that aren't mine don't
10703        // have my extra info.
10704        ((MenuBuilder)menu).setCurrentMenuInfo(null);
10705
10706        if (mParent != null) {
10707            mParent.createContextMenu(menu);
10708        }
10709    }
10710
10711    /**
10712     * Views should implement this if they have extra information to associate
10713     * with the context menu. The return result is supplied as a parameter to
10714     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
10715     * callback.
10716     *
10717     * @return Extra information about the item for which the context menu
10718     *         should be shown. This information will vary across different
10719     *         subclasses of View.
10720     */
10721    protected ContextMenuInfo getContextMenuInfo() {
10722        return null;
10723    }
10724
10725    /**
10726     * Views should implement this if the view itself is going to add items to
10727     * the context menu.
10728     *
10729     * @param menu the context menu to populate
10730     */
10731    protected void onCreateContextMenu(ContextMenu menu) {
10732    }
10733
10734    /**
10735     * Implement this method to handle trackball motion events.  The
10736     * <em>relative</em> movement of the trackball since the last event
10737     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
10738     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
10739     * that a movement of 1 corresponds to the user pressing one DPAD key (so
10740     * they will often be fractional values, representing the more fine-grained
10741     * movement information available from a trackball).
10742     *
10743     * @param event The motion event.
10744     * @return True if the event was handled, false otherwise.
10745     */
10746    public boolean onTrackballEvent(MotionEvent event) {
10747        return false;
10748    }
10749
10750    /**
10751     * Implement this method to handle generic motion events.
10752     * <p>
10753     * Generic motion events describe joystick movements, mouse hovers, track pad
10754     * touches, scroll wheel movements and other input events.  The
10755     * {@link MotionEvent#getSource() source} of the motion event specifies
10756     * the class of input that was received.  Implementations of this method
10757     * must examine the bits in the source before processing the event.
10758     * The following code example shows how this is done.
10759     * </p><p>
10760     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
10761     * are delivered to the view under the pointer.  All other generic motion events are
10762     * delivered to the focused view.
10763     * </p>
10764     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
10765     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
10766     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
10767     *             // process the joystick movement...
10768     *             return true;
10769     *         }
10770     *     }
10771     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
10772     *         switch (event.getAction()) {
10773     *             case MotionEvent.ACTION_HOVER_MOVE:
10774     *                 // process the mouse hover movement...
10775     *                 return true;
10776     *             case MotionEvent.ACTION_SCROLL:
10777     *                 // process the scroll wheel movement...
10778     *                 return true;
10779     *         }
10780     *     }
10781     *     return super.onGenericMotionEvent(event);
10782     * }</pre>
10783     *
10784     * @param event The generic motion event being processed.
10785     * @return True if the event was handled, false otherwise.
10786     */
10787    public boolean onGenericMotionEvent(MotionEvent event) {
10788        return false;
10789    }
10790
10791    /**
10792     * Implement this method to handle hover events.
10793     * <p>
10794     * This method is called whenever a pointer is hovering into, over, or out of the
10795     * bounds of a view and the view is not currently being touched.
10796     * Hover events are represented as pointer events with action
10797     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
10798     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
10799     * </p>
10800     * <ul>
10801     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
10802     * when the pointer enters the bounds of the view.</li>
10803     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
10804     * when the pointer has already entered the bounds of the view and has moved.</li>
10805     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
10806     * when the pointer has exited the bounds of the view or when the pointer is
10807     * about to go down due to a button click, tap, or similar user action that
10808     * causes the view to be touched.</li>
10809     * </ul>
10810     * <p>
10811     * The view should implement this method to return true to indicate that it is
10812     * handling the hover event, such as by changing its drawable state.
10813     * </p><p>
10814     * The default implementation calls {@link #setHovered} to update the hovered state
10815     * of the view when a hover enter or hover exit event is received, if the view
10816     * is enabled and is clickable.  The default implementation also sends hover
10817     * accessibility events.
10818     * </p>
10819     *
10820     * @param event The motion event that describes the hover.
10821     * @return True if the view handled the hover event.
10822     *
10823     * @see #isHovered
10824     * @see #setHovered
10825     * @see #onHoverChanged
10826     */
10827    public boolean onHoverEvent(MotionEvent event) {
10828        // The root view may receive hover (or touch) events that are outside the bounds of
10829        // the window.  This code ensures that we only send accessibility events for
10830        // hovers that are actually within the bounds of the root view.
10831        final int action = event.getActionMasked();
10832        if (!mSendingHoverAccessibilityEvents) {
10833            if ((action == MotionEvent.ACTION_HOVER_ENTER
10834                    || action == MotionEvent.ACTION_HOVER_MOVE)
10835                    && !hasHoveredChild()
10836                    && pointInView(event.getX(), event.getY())) {
10837                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
10838                mSendingHoverAccessibilityEvents = true;
10839            }
10840        } else {
10841            if (action == MotionEvent.ACTION_HOVER_EXIT
10842                    || (action == MotionEvent.ACTION_MOVE
10843                            && !pointInView(event.getX(), event.getY()))) {
10844                mSendingHoverAccessibilityEvents = false;
10845                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
10846            }
10847        }
10848
10849        if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE)
10850                && event.isFromSource(InputDevice.SOURCE_MOUSE)
10851                && isOnScrollbar(event.getX(), event.getY())) {
10852            awakenScrollBars();
10853        }
10854        if (isHoverable()) {
10855            switch (action) {
10856                case MotionEvent.ACTION_HOVER_ENTER:
10857                    setHovered(true);
10858                    break;
10859                case MotionEvent.ACTION_HOVER_EXIT:
10860                    setHovered(false);
10861                    break;
10862            }
10863
10864            // Dispatch the event to onGenericMotionEvent before returning true.
10865            // This is to provide compatibility with existing applications that
10866            // handled HOVER_MOVE events in onGenericMotionEvent and that would
10867            // break because of the new default handling for hoverable views
10868            // in onHoverEvent.
10869            // Note that onGenericMotionEvent will be called by default when
10870            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
10871            dispatchGenericMotionEventInternal(event);
10872            // The event was already handled by calling setHovered(), so always
10873            // return true.
10874            return true;
10875        }
10876
10877        return false;
10878    }
10879
10880    /**
10881     * Returns true if the view should handle {@link #onHoverEvent}
10882     * by calling {@link #setHovered} to change its hovered state.
10883     *
10884     * @return True if the view is hoverable.
10885     */
10886    private boolean isHoverable() {
10887        final int viewFlags = mViewFlags;
10888        if ((viewFlags & ENABLED_MASK) == DISABLED) {
10889            return false;
10890        }
10891
10892        return (viewFlags & CLICKABLE) == CLICKABLE
10893                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
10894                || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
10895    }
10896
10897    /**
10898     * Returns true if the view is currently hovered.
10899     *
10900     * @return True if the view is currently hovered.
10901     *
10902     * @see #setHovered
10903     * @see #onHoverChanged
10904     */
10905    @ViewDebug.ExportedProperty
10906    public boolean isHovered() {
10907        return (mPrivateFlags & PFLAG_HOVERED) != 0;
10908    }
10909
10910    /**
10911     * Sets whether the view is currently hovered.
10912     * <p>
10913     * Calling this method also changes the drawable state of the view.  This
10914     * enables the view to react to hover by using different drawable resources
10915     * to change its appearance.
10916     * </p><p>
10917     * The {@link #onHoverChanged} method is called when the hovered state changes.
10918     * </p>
10919     *
10920     * @param hovered True if the view is hovered.
10921     *
10922     * @see #isHovered
10923     * @see #onHoverChanged
10924     */
10925    public void setHovered(boolean hovered) {
10926        if (hovered) {
10927            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
10928                mPrivateFlags |= PFLAG_HOVERED;
10929                refreshDrawableState();
10930                onHoverChanged(true);
10931            }
10932        } else {
10933            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
10934                mPrivateFlags &= ~PFLAG_HOVERED;
10935                refreshDrawableState();
10936                onHoverChanged(false);
10937            }
10938        }
10939    }
10940
10941    /**
10942     * Implement this method to handle hover state changes.
10943     * <p>
10944     * This method is called whenever the hover state changes as a result of a
10945     * call to {@link #setHovered}.
10946     * </p>
10947     *
10948     * @param hovered The current hover state, as returned by {@link #isHovered}.
10949     *
10950     * @see #isHovered
10951     * @see #setHovered
10952     */
10953    public void onHoverChanged(boolean hovered) {
10954    }
10955
10956    /**
10957     * Handles scroll bar dragging by mouse input.
10958     *
10959     * @hide
10960     * @param event The motion event.
10961     *
10962     * @return true if the event was handled as a scroll bar dragging, false otherwise.
10963     */
10964    protected boolean handleScrollBarDragging(MotionEvent event) {
10965        if (mScrollCache == null) {
10966            return false;
10967        }
10968        final float x = event.getX();
10969        final float y = event.getY();
10970        final int action = event.getAction();
10971        if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING
10972                && action != MotionEvent.ACTION_DOWN)
10973                    || !event.isFromSource(InputDevice.SOURCE_MOUSE)
10974                    || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) {
10975            mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
10976            return false;
10977        }
10978
10979        switch (action) {
10980            case MotionEvent.ACTION_MOVE:
10981                if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) {
10982                    return false;
10983                }
10984                if (mScrollCache.mScrollBarDraggingState
10985                        == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) {
10986                    final Rect bounds = mScrollCache.mScrollBarBounds;
10987                    getVerticalScrollBarBounds(bounds);
10988                    final int range = computeVerticalScrollRange();
10989                    final int offset = computeVerticalScrollOffset();
10990                    final int extent = computeVerticalScrollExtent();
10991
10992                    final int thumbLength = ScrollBarUtils.getThumbLength(
10993                            bounds.height(), bounds.width(), extent, range);
10994                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
10995                            bounds.height(), thumbLength, extent, range, offset);
10996
10997                    final float diff = y - mScrollCache.mScrollBarDraggingPos;
10998                    final float maxThumbOffset = bounds.height() - thumbLength;
10999                    final float newThumbOffset =
11000                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11001                    final int height = getHeight();
11002                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11003                            && height > 0 && extent > 0) {
11004                        final int newY = Math.round((range - extent)
11005                                / ((float)extent / height) * (newThumbOffset / maxThumbOffset));
11006                        if (newY != getScrollY()) {
11007                            mScrollCache.mScrollBarDraggingPos = y;
11008                            setScrollY(newY);
11009                        }
11010                    }
11011                    return true;
11012                }
11013                if (mScrollCache.mScrollBarDraggingState
11014                        == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) {
11015                    final Rect bounds = mScrollCache.mScrollBarBounds;
11016                    getHorizontalScrollBarBounds(bounds);
11017                    final int range = computeHorizontalScrollRange();
11018                    final int offset = computeHorizontalScrollOffset();
11019                    final int extent = computeHorizontalScrollExtent();
11020
11021                    final int thumbLength = ScrollBarUtils.getThumbLength(
11022                            bounds.width(), bounds.height(), extent, range);
11023                    final int thumbOffset = ScrollBarUtils.getThumbOffset(
11024                            bounds.width(), thumbLength, extent, range, offset);
11025
11026                    final float diff = x - mScrollCache.mScrollBarDraggingPos;
11027                    final float maxThumbOffset = bounds.width() - thumbLength;
11028                    final float newThumbOffset =
11029                            Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset);
11030                    final int width = getWidth();
11031                    if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0
11032                            && width > 0 && extent > 0) {
11033                        final int newX = Math.round((range - extent)
11034                                / ((float)extent / width) * (newThumbOffset / maxThumbOffset));
11035                        if (newX != getScrollX()) {
11036                            mScrollCache.mScrollBarDraggingPos = x;
11037                            setScrollX(newX);
11038                        }
11039                    }
11040                    return true;
11041                }
11042            case MotionEvent.ACTION_DOWN:
11043                if (mScrollCache.state == ScrollabilityCache.OFF) {
11044                    return false;
11045                }
11046                if (isOnVerticalScrollbarThumb(x, y)) {
11047                    mScrollCache.mScrollBarDraggingState =
11048                            ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR;
11049                    mScrollCache.mScrollBarDraggingPos = y;
11050                    return true;
11051                }
11052                if (isOnHorizontalScrollbarThumb(x, y)) {
11053                    mScrollCache.mScrollBarDraggingState =
11054                            ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR;
11055                    mScrollCache.mScrollBarDraggingPos = x;
11056                    return true;
11057                }
11058        }
11059        mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING;
11060        return false;
11061    }
11062
11063    /**
11064     * Implement this method to handle touch screen motion events.
11065     * <p>
11066     * If this method is used to detect click actions, it is recommended that
11067     * the actions be performed by implementing and calling
11068     * {@link #performClick()}. This will ensure consistent system behavior,
11069     * including:
11070     * <ul>
11071     * <li>obeying click sound preferences
11072     * <li>dispatching OnClickListener calls
11073     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
11074     * accessibility features are enabled
11075     * </ul>
11076     *
11077     * @param event The motion event.
11078     * @return True if the event was handled, false otherwise.
11079     */
11080    public boolean onTouchEvent(MotionEvent event) {
11081        final float x = event.getX();
11082        final float y = event.getY();
11083        final int viewFlags = mViewFlags;
11084        final int action = event.getAction();
11085
11086        if ((viewFlags & ENABLED_MASK) == DISABLED) {
11087            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
11088                setPressed(false);
11089            }
11090            // A disabled view that is clickable still consumes the touch
11091            // events, it just doesn't respond to them.
11092            return (((viewFlags & CLICKABLE) == CLICKABLE
11093                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
11094                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
11095        }
11096        if (mTouchDelegate != null) {
11097            if (mTouchDelegate.onTouchEvent(event)) {
11098                return true;
11099            }
11100        }
11101
11102        if (((viewFlags & CLICKABLE) == CLICKABLE ||
11103                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
11104                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
11105            switch (action) {
11106                case MotionEvent.ACTION_UP:
11107                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
11108                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
11109                        // take focus if we don't have it already and we should in
11110                        // touch mode.
11111                        boolean focusTaken = false;
11112                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
11113                            focusTaken = requestFocus();
11114                        }
11115
11116                        if (prepressed) {
11117                            // The button is being released before we actually
11118                            // showed it as pressed.  Make it show the pressed
11119                            // state now (before scheduling the click) to ensure
11120                            // the user sees it.
11121                            setPressed(true, x, y);
11122                       }
11123
11124                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
11125                            // This is a tap, so remove the longpress check
11126                            removeLongPressCallback();
11127
11128                            // Only perform take click actions if we were in the pressed state
11129                            if (!focusTaken) {
11130                                // Use a Runnable and post this rather than calling
11131                                // performClick directly. This lets other visual state
11132                                // of the view update before click actions start.
11133                                if (mPerformClick == null) {
11134                                    mPerformClick = new PerformClick();
11135                                }
11136                                if (!post(mPerformClick)) {
11137                                    performClick();
11138                                }
11139                            }
11140                        }
11141
11142                        if (mUnsetPressedState == null) {
11143                            mUnsetPressedState = new UnsetPressedState();
11144                        }
11145
11146                        if (prepressed) {
11147                            postDelayed(mUnsetPressedState,
11148                                    ViewConfiguration.getPressedStateDuration());
11149                        } else if (!post(mUnsetPressedState)) {
11150                            // If the post failed, unpress right now
11151                            mUnsetPressedState.run();
11152                        }
11153
11154                        removeTapCallback();
11155                    }
11156                    mIgnoreNextUpEvent = false;
11157                    break;
11158
11159                case MotionEvent.ACTION_DOWN:
11160                    mHasPerformedLongPress = false;
11161
11162                    if (performButtonActionOnTouchDown(event)) {
11163                        break;
11164                    }
11165
11166                    // Walk up the hierarchy to determine if we're inside a scrolling container.
11167                    boolean isInScrollingContainer = isInScrollingContainer();
11168
11169                    // For views inside a scrolling container, delay the pressed feedback for
11170                    // a short period in case this is a scroll.
11171                    if (isInScrollingContainer) {
11172                        mPrivateFlags |= PFLAG_PREPRESSED;
11173                        if (mPendingCheckForTap == null) {
11174                            mPendingCheckForTap = new CheckForTap();
11175                        }
11176                        mPendingCheckForTap.x = event.getX();
11177                        mPendingCheckForTap.y = event.getY();
11178                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
11179                    } else {
11180                        // Not inside a scrolling container, so show the feedback right away
11181                        setPressed(true, x, y);
11182                        checkForLongClick(0, x, y);
11183                    }
11184                    break;
11185
11186                case MotionEvent.ACTION_CANCEL:
11187                    setPressed(false);
11188                    removeTapCallback();
11189                    removeLongPressCallback();
11190                    mInContextButtonPress = false;
11191                    mHasPerformedLongPress = false;
11192                    mIgnoreNextUpEvent = false;
11193                    break;
11194
11195                case MotionEvent.ACTION_MOVE:
11196                    drawableHotspotChanged(x, y);
11197
11198                    // Be lenient about moving outside of buttons
11199                    if (!pointInView(x, y, mTouchSlop)) {
11200                        // Outside button
11201                        removeTapCallback();
11202                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
11203                            // Remove any future long press/tap checks
11204                            removeLongPressCallback();
11205
11206                            setPressed(false);
11207                        }
11208                    }
11209                    break;
11210            }
11211
11212            return true;
11213        }
11214
11215        return false;
11216    }
11217
11218    /**
11219     * @hide
11220     */
11221    public boolean isInScrollingContainer() {
11222        ViewParent p = getParent();
11223        while (p != null && p instanceof ViewGroup) {
11224            if (((ViewGroup) p).shouldDelayChildPressedState()) {
11225                return true;
11226            }
11227            p = p.getParent();
11228        }
11229        return false;
11230    }
11231
11232    /**
11233     * Remove the longpress detection timer.
11234     */
11235    private void removeLongPressCallback() {
11236        if (mPendingCheckForLongPress != null) {
11237          removeCallbacks(mPendingCheckForLongPress);
11238        }
11239    }
11240
11241    /**
11242     * Remove the pending click action
11243     */
11244    private void removePerformClickCallback() {
11245        if (mPerformClick != null) {
11246            removeCallbacks(mPerformClick);
11247        }
11248    }
11249
11250    /**
11251     * Remove the prepress detection timer.
11252     */
11253    private void removeUnsetPressCallback() {
11254        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
11255            setPressed(false);
11256            removeCallbacks(mUnsetPressedState);
11257        }
11258    }
11259
11260    /**
11261     * Remove the tap detection timer.
11262     */
11263    private void removeTapCallback() {
11264        if (mPendingCheckForTap != null) {
11265            mPrivateFlags &= ~PFLAG_PREPRESSED;
11266            removeCallbacks(mPendingCheckForTap);
11267        }
11268    }
11269
11270    /**
11271     * Cancels a pending long press.  Your subclass can use this if you
11272     * want the context menu to come up if the user presses and holds
11273     * at the same place, but you don't want it to come up if they press
11274     * and then move around enough to cause scrolling.
11275     */
11276    public void cancelLongPress() {
11277        removeLongPressCallback();
11278
11279        /*
11280         * The prepressed state handled by the tap callback is a display
11281         * construct, but the tap callback will post a long press callback
11282         * less its own timeout. Remove it here.
11283         */
11284        removeTapCallback();
11285    }
11286
11287    /**
11288     * Remove the pending callback for sending a
11289     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
11290     */
11291    private void removeSendViewScrolledAccessibilityEventCallback() {
11292        if (mSendViewScrolledAccessibilityEvent != null) {
11293            removeCallbacks(mSendViewScrolledAccessibilityEvent);
11294            mSendViewScrolledAccessibilityEvent.mIsPending = false;
11295        }
11296    }
11297
11298    /**
11299     * Sets the TouchDelegate for this View.
11300     */
11301    public void setTouchDelegate(TouchDelegate delegate) {
11302        mTouchDelegate = delegate;
11303    }
11304
11305    /**
11306     * Gets the TouchDelegate for this View.
11307     */
11308    public TouchDelegate getTouchDelegate() {
11309        return mTouchDelegate;
11310    }
11311
11312    /**
11313     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
11314     *
11315     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
11316     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
11317     * available. This method should only be called for touch events.
11318     *
11319     * <p class="note">This api is not intended for most applications. Buffered dispatch
11320     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
11321     * streams will not improve your input latency. Side effects include: increased latency,
11322     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
11323     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
11324     * you.</p>
11325     */
11326    public final void requestUnbufferedDispatch(MotionEvent event) {
11327        final int action = event.getAction();
11328        if (mAttachInfo == null
11329                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
11330                || !event.isTouchEvent()) {
11331            return;
11332        }
11333        mAttachInfo.mUnbufferedDispatchRequested = true;
11334    }
11335
11336    /**
11337     * Set flags controlling behavior of this view.
11338     *
11339     * @param flags Constant indicating the value which should be set
11340     * @param mask Constant indicating the bit range that should be changed
11341     */
11342    void setFlags(int flags, int mask) {
11343        final boolean accessibilityEnabled =
11344                AccessibilityManager.getInstance(mContext).isEnabled();
11345        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
11346
11347        int old = mViewFlags;
11348        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
11349
11350        int changed = mViewFlags ^ old;
11351        if (changed == 0) {
11352            return;
11353        }
11354        int privateFlags = mPrivateFlags;
11355
11356        /* Check if the FOCUSABLE bit has changed */
11357        if (((changed & FOCUSABLE_MASK) != 0) &&
11358                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
11359            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
11360                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
11361                /* Give up focus if we are no longer focusable */
11362                clearFocus();
11363            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
11364                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
11365                /*
11366                 * Tell the view system that we are now available to take focus
11367                 * if no one else already has it.
11368                 */
11369                if (mParent != null) mParent.focusableViewAvailable(this);
11370            }
11371        }
11372
11373        final int newVisibility = flags & VISIBILITY_MASK;
11374        if (newVisibility == VISIBLE) {
11375            if ((changed & VISIBILITY_MASK) != 0) {
11376                /*
11377                 * If this view is becoming visible, invalidate it in case it changed while
11378                 * it was not visible. Marking it drawn ensures that the invalidation will
11379                 * go through.
11380                 */
11381                mPrivateFlags |= PFLAG_DRAWN;
11382                invalidate(true);
11383
11384                needGlobalAttributesUpdate(true);
11385
11386                // a view becoming visible is worth notifying the parent
11387                // about in case nothing has focus.  even if this specific view
11388                // isn't focusable, it may contain something that is, so let
11389                // the root view try to give this focus if nothing else does.
11390                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
11391                    mParent.focusableViewAvailable(this);
11392                }
11393            }
11394        }
11395
11396        /* Check if the GONE bit has changed */
11397        if ((changed & GONE) != 0) {
11398            needGlobalAttributesUpdate(false);
11399            requestLayout();
11400
11401            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
11402                if (hasFocus()) clearFocus();
11403                clearAccessibilityFocus();
11404                destroyDrawingCache();
11405                if (mParent instanceof View) {
11406                    // GONE views noop invalidation, so invalidate the parent
11407                    ((View) mParent).invalidate(true);
11408                }
11409                // Mark the view drawn to ensure that it gets invalidated properly the next
11410                // time it is visible and gets invalidated
11411                mPrivateFlags |= PFLAG_DRAWN;
11412            }
11413            if (mAttachInfo != null) {
11414                mAttachInfo.mViewVisibilityChanged = true;
11415            }
11416        }
11417
11418        /* Check if the VISIBLE bit has changed */
11419        if ((changed & INVISIBLE) != 0) {
11420            needGlobalAttributesUpdate(false);
11421            /*
11422             * If this view is becoming invisible, set the DRAWN flag so that
11423             * the next invalidate() will not be skipped.
11424             */
11425            mPrivateFlags |= PFLAG_DRAWN;
11426
11427            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
11428                // root view becoming invisible shouldn't clear focus and accessibility focus
11429                if (getRootView() != this) {
11430                    if (hasFocus()) clearFocus();
11431                    clearAccessibilityFocus();
11432                }
11433            }
11434            if (mAttachInfo != null) {
11435                mAttachInfo.mViewVisibilityChanged = true;
11436            }
11437        }
11438
11439        if ((changed & VISIBILITY_MASK) != 0) {
11440            // If the view is invisible, cleanup its display list to free up resources
11441            if (newVisibility != VISIBLE && mAttachInfo != null) {
11442                cleanupDraw();
11443            }
11444
11445            if (mParent instanceof ViewGroup) {
11446                ((ViewGroup) mParent).onChildVisibilityChanged(this,
11447                        (changed & VISIBILITY_MASK), newVisibility);
11448                ((View) mParent).invalidate(true);
11449            } else if (mParent != null) {
11450                mParent.invalidateChild(this, null);
11451            }
11452
11453            if (mAttachInfo != null) {
11454                dispatchVisibilityChanged(this, newVisibility);
11455
11456                // Aggregated visibility changes are dispatched to attached views
11457                // in visible windows where the parent is currently shown/drawn
11458                // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot),
11459                // discounting clipping or overlapping. This makes it a good place
11460                // to change animation states.
11461                if (mParent != null && getWindowVisibility() == VISIBLE &&
11462                        ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) {
11463                    dispatchVisibilityAggregated(newVisibility == VISIBLE);
11464                }
11465                notifySubtreeAccessibilityStateChangedIfNeeded();
11466            }
11467        }
11468
11469        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
11470            destroyDrawingCache();
11471        }
11472
11473        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
11474            destroyDrawingCache();
11475            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11476            invalidateParentCaches();
11477        }
11478
11479        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
11480            destroyDrawingCache();
11481            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11482        }
11483
11484        if ((changed & DRAW_MASK) != 0) {
11485            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
11486                if (mBackground != null
11487                        || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) {
11488                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11489                } else {
11490                    mPrivateFlags |= PFLAG_SKIP_DRAW;
11491                }
11492            } else {
11493                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
11494            }
11495            requestLayout();
11496            invalidate(true);
11497        }
11498
11499        if ((changed & KEEP_SCREEN_ON) != 0) {
11500            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11501                mParent.recomputeViewAttributes(this);
11502            }
11503        }
11504
11505        if (accessibilityEnabled) {
11506            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
11507                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
11508                    || (changed & CONTEXT_CLICKABLE) != 0) {
11509                if (oldIncludeForAccessibility != includeForAccessibility()) {
11510                    notifySubtreeAccessibilityStateChangedIfNeeded();
11511                } else {
11512                    notifyViewAccessibilityStateChangedIfNeeded(
11513                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11514                }
11515            } else if ((changed & ENABLED_MASK) != 0) {
11516                notifyViewAccessibilityStateChangedIfNeeded(
11517                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11518            }
11519        }
11520    }
11521
11522    /**
11523     * Change the view's z order in the tree, so it's on top of other sibling
11524     * views. This ordering change may affect layout, if the parent container
11525     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
11526     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
11527     * method should be followed by calls to {@link #requestLayout()} and
11528     * {@link View#invalidate()} on the view's parent to force the parent to redraw
11529     * with the new child ordering.
11530     *
11531     * @see ViewGroup#bringChildToFront(View)
11532     */
11533    public void bringToFront() {
11534        if (mParent != null) {
11535            mParent.bringChildToFront(this);
11536        }
11537    }
11538
11539    /**
11540     * This is called in response to an internal scroll in this view (i.e., the
11541     * view scrolled its own contents). This is typically as a result of
11542     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
11543     * called.
11544     *
11545     * @param l Current horizontal scroll origin.
11546     * @param t Current vertical scroll origin.
11547     * @param oldl Previous horizontal scroll origin.
11548     * @param oldt Previous vertical scroll origin.
11549     */
11550    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
11551        notifySubtreeAccessibilityStateChangedIfNeeded();
11552
11553        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
11554            postSendViewScrolledAccessibilityEventCallback();
11555        }
11556
11557        mBackgroundSizeChanged = true;
11558        if (mForegroundInfo != null) {
11559            mForegroundInfo.mBoundsChanged = true;
11560        }
11561
11562        final AttachInfo ai = mAttachInfo;
11563        if (ai != null) {
11564            ai.mViewScrollChanged = true;
11565        }
11566
11567        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
11568            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
11569        }
11570    }
11571
11572    /**
11573     * Interface definition for a callback to be invoked when the scroll
11574     * X or Y positions of a view change.
11575     * <p>
11576     * <b>Note:</b> Some views handle scrolling independently from View and may
11577     * have their own separate listeners for scroll-type events. For example,
11578     * {@link android.widget.ListView ListView} allows clients to register an
11579     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
11580     * to listen for changes in list scroll position.
11581     *
11582     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
11583     */
11584    public interface OnScrollChangeListener {
11585        /**
11586         * Called when the scroll position of a view changes.
11587         *
11588         * @param v The view whose scroll position has changed.
11589         * @param scrollX Current horizontal scroll origin.
11590         * @param scrollY Current vertical scroll origin.
11591         * @param oldScrollX Previous horizontal scroll origin.
11592         * @param oldScrollY Previous vertical scroll origin.
11593         */
11594        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
11595    }
11596
11597    /**
11598     * Interface definition for a callback to be invoked when the layout bounds of a view
11599     * changes due to layout processing.
11600     */
11601    public interface OnLayoutChangeListener {
11602        /**
11603         * Called when the layout bounds of a view changes due to layout processing.
11604         *
11605         * @param v The view whose bounds have changed.
11606         * @param left The new value of the view's left property.
11607         * @param top The new value of the view's top property.
11608         * @param right The new value of the view's right property.
11609         * @param bottom The new value of the view's bottom property.
11610         * @param oldLeft The previous value of the view's left property.
11611         * @param oldTop The previous value of the view's top property.
11612         * @param oldRight The previous value of the view's right property.
11613         * @param oldBottom The previous value of the view's bottom property.
11614         */
11615        void onLayoutChange(View v, int left, int top, int right, int bottom,
11616            int oldLeft, int oldTop, int oldRight, int oldBottom);
11617    }
11618
11619    /**
11620     * This is called during layout when the size of this view has changed. If
11621     * you were just added to the view hierarchy, you're called with the old
11622     * values of 0.
11623     *
11624     * @param w Current width of this view.
11625     * @param h Current height of this view.
11626     * @param oldw Old width of this view.
11627     * @param oldh Old height of this view.
11628     */
11629    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
11630    }
11631
11632    /**
11633     * Called by draw to draw the child views. This may be overridden
11634     * by derived classes to gain control just before its children are drawn
11635     * (but after its own view has been drawn).
11636     * @param canvas the canvas on which to draw the view
11637     */
11638    protected void dispatchDraw(Canvas canvas) {
11639
11640    }
11641
11642    /**
11643     * Gets the parent of this view. Note that the parent is a
11644     * ViewParent and not necessarily a View.
11645     *
11646     * @return Parent of this view.
11647     */
11648    public final ViewParent getParent() {
11649        return mParent;
11650    }
11651
11652    /**
11653     * Set the horizontal scrolled position of your view. This will cause a call to
11654     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11655     * invalidated.
11656     * @param value the x position to scroll to
11657     */
11658    public void setScrollX(int value) {
11659        scrollTo(value, mScrollY);
11660    }
11661
11662    /**
11663     * Set the vertical scrolled position of your view. This will cause a call to
11664     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11665     * invalidated.
11666     * @param value the y position to scroll to
11667     */
11668    public void setScrollY(int value) {
11669        scrollTo(mScrollX, value);
11670    }
11671
11672    /**
11673     * Return the scrolled left position of this view. This is the left edge of
11674     * the displayed part of your view. You do not need to draw any pixels
11675     * farther left, since those are outside of the frame of your view on
11676     * screen.
11677     *
11678     * @return The left edge of the displayed part of your view, in pixels.
11679     */
11680    public final int getScrollX() {
11681        return mScrollX;
11682    }
11683
11684    /**
11685     * Return the scrolled top position of this view. This is the top edge of
11686     * the displayed part of your view. You do not need to draw any pixels above
11687     * it, since those are outside of the frame of your view on screen.
11688     *
11689     * @return The top edge of the displayed part of your view, in pixels.
11690     */
11691    public final int getScrollY() {
11692        return mScrollY;
11693    }
11694
11695    /**
11696     * Return the width of the your view.
11697     *
11698     * @return The width of your view, in pixels.
11699     */
11700    @ViewDebug.ExportedProperty(category = "layout")
11701    public final int getWidth() {
11702        return mRight - mLeft;
11703    }
11704
11705    /**
11706     * Return the height of your view.
11707     *
11708     * @return The height of your view, in pixels.
11709     */
11710    @ViewDebug.ExportedProperty(category = "layout")
11711    public final int getHeight() {
11712        return mBottom - mTop;
11713    }
11714
11715    /**
11716     * Return the visible drawing bounds of your view. Fills in the output
11717     * rectangle with the values from getScrollX(), getScrollY(),
11718     * getWidth(), and getHeight(). These bounds do not account for any
11719     * transformation properties currently set on the view, such as
11720     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
11721     *
11722     * @param outRect The (scrolled) drawing bounds of the view.
11723     */
11724    public void getDrawingRect(Rect outRect) {
11725        outRect.left = mScrollX;
11726        outRect.top = mScrollY;
11727        outRect.right = mScrollX + (mRight - mLeft);
11728        outRect.bottom = mScrollY + (mBottom - mTop);
11729    }
11730
11731    /**
11732     * Like {@link #getMeasuredWidthAndState()}, but only returns the
11733     * raw width component (that is the result is masked by
11734     * {@link #MEASURED_SIZE_MASK}).
11735     *
11736     * @return The raw measured width of this view.
11737     */
11738    public final int getMeasuredWidth() {
11739        return mMeasuredWidth & MEASURED_SIZE_MASK;
11740    }
11741
11742    /**
11743     * Return the full width measurement information for this view as computed
11744     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11745     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11746     * This should be used during measurement and layout calculations only. Use
11747     * {@link #getWidth()} to see how wide a view is after layout.
11748     *
11749     * @return The measured width of this view as a bit mask.
11750     */
11751    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11752            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11753                    name = "MEASURED_STATE_TOO_SMALL"),
11754    })
11755    public final int getMeasuredWidthAndState() {
11756        return mMeasuredWidth;
11757    }
11758
11759    /**
11760     * Like {@link #getMeasuredHeightAndState()}, but only returns the
11761     * raw height component (that is the result is masked by
11762     * {@link #MEASURED_SIZE_MASK}).
11763     *
11764     * @return The raw measured height of this view.
11765     */
11766    public final int getMeasuredHeight() {
11767        return mMeasuredHeight & MEASURED_SIZE_MASK;
11768    }
11769
11770    /**
11771     * Return the full height measurement information for this view as computed
11772     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
11773     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11774     * This should be used during measurement and layout calculations only. Use
11775     * {@link #getHeight()} to see how wide a view is after layout.
11776     *
11777     * @return The measured height of this view as a bit mask.
11778     */
11779    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
11780            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
11781                    name = "MEASURED_STATE_TOO_SMALL"),
11782    })
11783    public final int getMeasuredHeightAndState() {
11784        return mMeasuredHeight;
11785    }
11786
11787    /**
11788     * Return only the state bits of {@link #getMeasuredWidthAndState()}
11789     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
11790     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
11791     * and the height component is at the shifted bits
11792     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
11793     */
11794    public final int getMeasuredState() {
11795        return (mMeasuredWidth&MEASURED_STATE_MASK)
11796                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
11797                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
11798    }
11799
11800    /**
11801     * The transform matrix of this view, which is calculated based on the current
11802     * rotation, scale, and pivot properties.
11803     *
11804     * @see #getRotation()
11805     * @see #getScaleX()
11806     * @see #getScaleY()
11807     * @see #getPivotX()
11808     * @see #getPivotY()
11809     * @return The current transform matrix for the view
11810     */
11811    public Matrix getMatrix() {
11812        ensureTransformationInfo();
11813        final Matrix matrix = mTransformationInfo.mMatrix;
11814        mRenderNode.getMatrix(matrix);
11815        return matrix;
11816    }
11817
11818    /**
11819     * Returns true if the transform matrix is the identity matrix.
11820     * Recomputes the matrix if necessary.
11821     *
11822     * @return True if the transform matrix is the identity matrix, false otherwise.
11823     */
11824    final boolean hasIdentityMatrix() {
11825        return mRenderNode.hasIdentityMatrix();
11826    }
11827
11828    void ensureTransformationInfo() {
11829        if (mTransformationInfo == null) {
11830            mTransformationInfo = new TransformationInfo();
11831        }
11832    }
11833
11834    /**
11835     * Utility method to retrieve the inverse of the current mMatrix property.
11836     * We cache the matrix to avoid recalculating it when transform properties
11837     * have not changed.
11838     *
11839     * @return The inverse of the current matrix of this view.
11840     * @hide
11841     */
11842    public final Matrix getInverseMatrix() {
11843        ensureTransformationInfo();
11844        if (mTransformationInfo.mInverseMatrix == null) {
11845            mTransformationInfo.mInverseMatrix = new Matrix();
11846        }
11847        final Matrix matrix = mTransformationInfo.mInverseMatrix;
11848        mRenderNode.getInverseMatrix(matrix);
11849        return matrix;
11850    }
11851
11852    /**
11853     * Gets the distance along the Z axis from the camera to this view.
11854     *
11855     * @see #setCameraDistance(float)
11856     *
11857     * @return The distance along the Z axis.
11858     */
11859    public float getCameraDistance() {
11860        final float dpi = mResources.getDisplayMetrics().densityDpi;
11861        return -(mRenderNode.getCameraDistance() * dpi);
11862    }
11863
11864    /**
11865     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
11866     * views are drawn) from the camera to this view. The camera's distance
11867     * affects 3D transformations, for instance rotations around the X and Y
11868     * axis. If the rotationX or rotationY properties are changed and this view is
11869     * large (more than half the size of the screen), it is recommended to always
11870     * use a camera distance that's greater than the height (X axis rotation) or
11871     * the width (Y axis rotation) of this view.</p>
11872     *
11873     * <p>The distance of the camera from the view plane can have an affect on the
11874     * perspective distortion of the view when it is rotated around the x or y axis.
11875     * For example, a large distance will result in a large viewing angle, and there
11876     * will not be much perspective distortion of the view as it rotates. A short
11877     * distance may cause much more perspective distortion upon rotation, and can
11878     * also result in some drawing artifacts if the rotated view ends up partially
11879     * behind the camera (which is why the recommendation is to use a distance at
11880     * least as far as the size of the view, if the view is to be rotated.)</p>
11881     *
11882     * <p>The distance is expressed in "depth pixels." The default distance depends
11883     * on the screen density. For instance, on a medium density display, the
11884     * default distance is 1280. On a high density display, the default distance
11885     * is 1920.</p>
11886     *
11887     * <p>If you want to specify a distance that leads to visually consistent
11888     * results across various densities, use the following formula:</p>
11889     * <pre>
11890     * float scale = context.getResources().getDisplayMetrics().density;
11891     * view.setCameraDistance(distance * scale);
11892     * </pre>
11893     *
11894     * <p>The density scale factor of a high density display is 1.5,
11895     * and 1920 = 1280 * 1.5.</p>
11896     *
11897     * @param distance The distance in "depth pixels", if negative the opposite
11898     *        value is used
11899     *
11900     * @see #setRotationX(float)
11901     * @see #setRotationY(float)
11902     */
11903    public void setCameraDistance(float distance) {
11904        final float dpi = mResources.getDisplayMetrics().densityDpi;
11905
11906        invalidateViewProperty(true, false);
11907        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
11908        invalidateViewProperty(false, false);
11909
11910        invalidateParentIfNeededAndWasQuickRejected();
11911    }
11912
11913    /**
11914     * The degrees that the view is rotated around the pivot point.
11915     *
11916     * @see #setRotation(float)
11917     * @see #getPivotX()
11918     * @see #getPivotY()
11919     *
11920     * @return The degrees of rotation.
11921     */
11922    @ViewDebug.ExportedProperty(category = "drawing")
11923    public float getRotation() {
11924        return mRenderNode.getRotation();
11925    }
11926
11927    /**
11928     * Sets the degrees that the view is rotated around the pivot point. Increasing values
11929     * result in clockwise rotation.
11930     *
11931     * @param rotation The degrees of rotation.
11932     *
11933     * @see #getRotation()
11934     * @see #getPivotX()
11935     * @see #getPivotY()
11936     * @see #setRotationX(float)
11937     * @see #setRotationY(float)
11938     *
11939     * @attr ref android.R.styleable#View_rotation
11940     */
11941    public void setRotation(float rotation) {
11942        if (rotation != getRotation()) {
11943            // Double-invalidation is necessary to capture view's old and new areas
11944            invalidateViewProperty(true, false);
11945            mRenderNode.setRotation(rotation);
11946            invalidateViewProperty(false, true);
11947
11948            invalidateParentIfNeededAndWasQuickRejected();
11949            notifySubtreeAccessibilityStateChangedIfNeeded();
11950        }
11951    }
11952
11953    /**
11954     * The degrees that the view is rotated around the vertical axis through the pivot point.
11955     *
11956     * @see #getPivotX()
11957     * @see #getPivotY()
11958     * @see #setRotationY(float)
11959     *
11960     * @return The degrees of Y rotation.
11961     */
11962    @ViewDebug.ExportedProperty(category = "drawing")
11963    public float getRotationY() {
11964        return mRenderNode.getRotationY();
11965    }
11966
11967    /**
11968     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
11969     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
11970     * down the y axis.
11971     *
11972     * When rotating large views, it is recommended to adjust the camera distance
11973     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
11974     *
11975     * @param rotationY The degrees of Y rotation.
11976     *
11977     * @see #getRotationY()
11978     * @see #getPivotX()
11979     * @see #getPivotY()
11980     * @see #setRotation(float)
11981     * @see #setRotationX(float)
11982     * @see #setCameraDistance(float)
11983     *
11984     * @attr ref android.R.styleable#View_rotationY
11985     */
11986    public void setRotationY(float rotationY) {
11987        if (rotationY != getRotationY()) {
11988            invalidateViewProperty(true, false);
11989            mRenderNode.setRotationY(rotationY);
11990            invalidateViewProperty(false, true);
11991
11992            invalidateParentIfNeededAndWasQuickRejected();
11993            notifySubtreeAccessibilityStateChangedIfNeeded();
11994        }
11995    }
11996
11997    /**
11998     * The degrees that the view is rotated around the horizontal axis through the pivot point.
11999     *
12000     * @see #getPivotX()
12001     * @see #getPivotY()
12002     * @see #setRotationX(float)
12003     *
12004     * @return The degrees of X rotation.
12005     */
12006    @ViewDebug.ExportedProperty(category = "drawing")
12007    public float getRotationX() {
12008        return mRenderNode.getRotationX();
12009    }
12010
12011    /**
12012     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
12013     * Increasing values result in clockwise rotation from the viewpoint of looking down the
12014     * x axis.
12015     *
12016     * When rotating large views, it is recommended to adjust the camera distance
12017     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
12018     *
12019     * @param rotationX The degrees of X rotation.
12020     *
12021     * @see #getRotationX()
12022     * @see #getPivotX()
12023     * @see #getPivotY()
12024     * @see #setRotation(float)
12025     * @see #setRotationY(float)
12026     * @see #setCameraDistance(float)
12027     *
12028     * @attr ref android.R.styleable#View_rotationX
12029     */
12030    public void setRotationX(float rotationX) {
12031        if (rotationX != getRotationX()) {
12032            invalidateViewProperty(true, false);
12033            mRenderNode.setRotationX(rotationX);
12034            invalidateViewProperty(false, true);
12035
12036            invalidateParentIfNeededAndWasQuickRejected();
12037            notifySubtreeAccessibilityStateChangedIfNeeded();
12038        }
12039    }
12040
12041    /**
12042     * The amount that the view is scaled in x around the pivot point, as a proportion of
12043     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
12044     *
12045     * <p>By default, this is 1.0f.
12046     *
12047     * @see #getPivotX()
12048     * @see #getPivotY()
12049     * @return The scaling factor.
12050     */
12051    @ViewDebug.ExportedProperty(category = "drawing")
12052    public float getScaleX() {
12053        return mRenderNode.getScaleX();
12054    }
12055
12056    /**
12057     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
12058     * the view's unscaled width. A value of 1 means that no scaling is applied.
12059     *
12060     * @param scaleX The scaling factor.
12061     * @see #getPivotX()
12062     * @see #getPivotY()
12063     *
12064     * @attr ref android.R.styleable#View_scaleX
12065     */
12066    public void setScaleX(float scaleX) {
12067        if (scaleX != getScaleX()) {
12068            invalidateViewProperty(true, false);
12069            mRenderNode.setScaleX(scaleX);
12070            invalidateViewProperty(false, true);
12071
12072            invalidateParentIfNeededAndWasQuickRejected();
12073            notifySubtreeAccessibilityStateChangedIfNeeded();
12074        }
12075    }
12076
12077    /**
12078     * The amount that the view is scaled in y around the pivot point, as a proportion of
12079     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
12080     *
12081     * <p>By default, this is 1.0f.
12082     *
12083     * @see #getPivotX()
12084     * @see #getPivotY()
12085     * @return The scaling factor.
12086     */
12087    @ViewDebug.ExportedProperty(category = "drawing")
12088    public float getScaleY() {
12089        return mRenderNode.getScaleY();
12090    }
12091
12092    /**
12093     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
12094     * the view's unscaled width. A value of 1 means that no scaling is applied.
12095     *
12096     * @param scaleY The scaling factor.
12097     * @see #getPivotX()
12098     * @see #getPivotY()
12099     *
12100     * @attr ref android.R.styleable#View_scaleY
12101     */
12102    public void setScaleY(float scaleY) {
12103        if (scaleY != getScaleY()) {
12104            invalidateViewProperty(true, false);
12105            mRenderNode.setScaleY(scaleY);
12106            invalidateViewProperty(false, true);
12107
12108            invalidateParentIfNeededAndWasQuickRejected();
12109            notifySubtreeAccessibilityStateChangedIfNeeded();
12110        }
12111    }
12112
12113    /**
12114     * The x location of the point around which the view is {@link #setRotation(float) rotated}
12115     * and {@link #setScaleX(float) scaled}.
12116     *
12117     * @see #getRotation()
12118     * @see #getScaleX()
12119     * @see #getScaleY()
12120     * @see #getPivotY()
12121     * @return The x location of the pivot point.
12122     *
12123     * @attr ref android.R.styleable#View_transformPivotX
12124     */
12125    @ViewDebug.ExportedProperty(category = "drawing")
12126    public float getPivotX() {
12127        return mRenderNode.getPivotX();
12128    }
12129
12130    /**
12131     * Sets the x location of the point around which the view is
12132     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
12133     * By default, the pivot point is centered on the object.
12134     * Setting this property disables this behavior and causes the view to use only the
12135     * explicitly set pivotX and pivotY values.
12136     *
12137     * @param pivotX The x location of the pivot point.
12138     * @see #getRotation()
12139     * @see #getScaleX()
12140     * @see #getScaleY()
12141     * @see #getPivotY()
12142     *
12143     * @attr ref android.R.styleable#View_transformPivotX
12144     */
12145    public void setPivotX(float pivotX) {
12146        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
12147            invalidateViewProperty(true, false);
12148            mRenderNode.setPivotX(pivotX);
12149            invalidateViewProperty(false, true);
12150
12151            invalidateParentIfNeededAndWasQuickRejected();
12152        }
12153    }
12154
12155    /**
12156     * The y location of the point around which the view is {@link #setRotation(float) rotated}
12157     * and {@link #setScaleY(float) scaled}.
12158     *
12159     * @see #getRotation()
12160     * @see #getScaleX()
12161     * @see #getScaleY()
12162     * @see #getPivotY()
12163     * @return The y location of the pivot point.
12164     *
12165     * @attr ref android.R.styleable#View_transformPivotY
12166     */
12167    @ViewDebug.ExportedProperty(category = "drawing")
12168    public float getPivotY() {
12169        return mRenderNode.getPivotY();
12170    }
12171
12172    /**
12173     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
12174     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
12175     * Setting this property disables this behavior and causes the view to use only the
12176     * explicitly set pivotX and pivotY values.
12177     *
12178     * @param pivotY The y location of the pivot point.
12179     * @see #getRotation()
12180     * @see #getScaleX()
12181     * @see #getScaleY()
12182     * @see #getPivotY()
12183     *
12184     * @attr ref android.R.styleable#View_transformPivotY
12185     */
12186    public void setPivotY(float pivotY) {
12187        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
12188            invalidateViewProperty(true, false);
12189            mRenderNode.setPivotY(pivotY);
12190            invalidateViewProperty(false, true);
12191
12192            invalidateParentIfNeededAndWasQuickRejected();
12193        }
12194    }
12195
12196    /**
12197     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
12198     * completely transparent and 1 means the view is completely opaque.
12199     *
12200     * <p>By default this is 1.0f.
12201     * @return The opacity of the view.
12202     */
12203    @ViewDebug.ExportedProperty(category = "drawing")
12204    public float getAlpha() {
12205        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
12206    }
12207
12208    /**
12209     * Sets the behavior for overlapping rendering for this view (see {@link
12210     * #hasOverlappingRendering()} for more details on this behavior). Calling this method
12211     * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass,
12212     * providing the value which is then used internally. That is, when {@link
12213     * #forceHasOverlappingRendering(boolean)} is called, the value of {@link
12214     * #hasOverlappingRendering()} is ignored and the value passed into this method is used
12215     * instead.
12216     *
12217     * @param hasOverlappingRendering The value for overlapping rendering to be used internally
12218     * instead of that returned by {@link #hasOverlappingRendering()}.
12219     *
12220     * @attr ref android.R.styleable#View_forceHasOverlappingRendering
12221     */
12222    public void forceHasOverlappingRendering(boolean hasOverlappingRendering) {
12223        mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED;
12224        if (hasOverlappingRendering) {
12225            mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12226        } else {
12227            mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE;
12228        }
12229    }
12230
12231    /**
12232     * Returns the value for overlapping rendering that is used internally. This is either
12233     * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or
12234     * the return value of {@link #hasOverlappingRendering()}, otherwise.
12235     *
12236     * @return The value for overlapping rendering being used internally.
12237     */
12238    public final boolean getHasOverlappingRendering() {
12239        return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ?
12240                (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 :
12241                hasOverlappingRendering();
12242    }
12243
12244    /**
12245     * Returns whether this View has content which overlaps.
12246     *
12247     * <p>This function, intended to be overridden by specific View types, is an optimization when
12248     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
12249     * an offscreen buffer and then composited into place, which can be expensive. If the view has
12250     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
12251     * directly. An example of overlapping rendering is a TextView with a background image, such as
12252     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
12253     * ImageView with only the foreground image. The default implementation returns true; subclasses
12254     * should override if they have cases which can be optimized.</p>
12255     *
12256     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
12257     * necessitates that a View return true if it uses the methods internally without passing the
12258     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
12259     *
12260     * <p><strong>Note:</strong> The return value of this method is ignored if {@link
12261     * #forceHasOverlappingRendering(boolean)} has been called on this view.</p>
12262     *
12263     * @return true if the content in this view might overlap, false otherwise.
12264     */
12265    @ViewDebug.ExportedProperty(category = "drawing")
12266    public boolean hasOverlappingRendering() {
12267        return true;
12268    }
12269
12270    /**
12271     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
12272     * completely transparent and 1 means the view is completely opaque.
12273     *
12274     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
12275     * can have significant performance implications, especially for large views. It is best to use
12276     * the alpha property sparingly and transiently, as in the case of fading animations.</p>
12277     *
12278     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
12279     * strongly recommended for performance reasons to either override
12280     * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a
12281     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
12282     * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below,
12283     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
12284     * of rendering cost, even for simple or small views. Starting with
12285     * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically
12286     * applied to the view at the rendering level.</p>
12287     *
12288     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
12289     * responsible for applying the opacity itself.</p>
12290     *
12291     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
12292     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
12293     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
12294     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
12295     *
12296     * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha
12297     * value will clip a View to its bounds, unless the View returns <code>false</code> from
12298     * {@link #hasOverlappingRendering}.</p>
12299     *
12300     * @param alpha The opacity of the view.
12301     *
12302     * @see #hasOverlappingRendering()
12303     * @see #setLayerType(int, android.graphics.Paint)
12304     *
12305     * @attr ref android.R.styleable#View_alpha
12306     */
12307    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
12308        ensureTransformationInfo();
12309        if (mTransformationInfo.mAlpha != alpha) {
12310            mTransformationInfo.mAlpha = alpha;
12311            if (onSetAlpha((int) (alpha * 255))) {
12312                mPrivateFlags |= PFLAG_ALPHA_SET;
12313                // subclass is handling alpha - don't optimize rendering cache invalidation
12314                invalidateParentCaches();
12315                invalidate(true);
12316            } else {
12317                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12318                invalidateViewProperty(true, false);
12319                mRenderNode.setAlpha(getFinalAlpha());
12320                notifyViewAccessibilityStateChangedIfNeeded(
12321                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
12322            }
12323        }
12324    }
12325
12326    /**
12327     * Faster version of setAlpha() which performs the same steps except there are
12328     * no calls to invalidate(). The caller of this function should perform proper invalidation
12329     * on the parent and this object. The return value indicates whether the subclass handles
12330     * alpha (the return value for onSetAlpha()).
12331     *
12332     * @param alpha The new value for the alpha property
12333     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
12334     *         the new value for the alpha property is different from the old value
12335     */
12336    boolean setAlphaNoInvalidation(float alpha) {
12337        ensureTransformationInfo();
12338        if (mTransformationInfo.mAlpha != alpha) {
12339            mTransformationInfo.mAlpha = alpha;
12340            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
12341            if (subclassHandlesAlpha) {
12342                mPrivateFlags |= PFLAG_ALPHA_SET;
12343                return true;
12344            } else {
12345                mPrivateFlags &= ~PFLAG_ALPHA_SET;
12346                mRenderNode.setAlpha(getFinalAlpha());
12347            }
12348        }
12349        return false;
12350    }
12351
12352    /**
12353     * This property is hidden and intended only for use by the Fade transition, which
12354     * animates it to produce a visual translucency that does not side-effect (or get
12355     * affected by) the real alpha property. This value is composited with the other
12356     * alpha value (and the AlphaAnimation value, when that is present) to produce
12357     * a final visual translucency result, which is what is passed into the DisplayList.
12358     *
12359     * @hide
12360     */
12361    public void setTransitionAlpha(float alpha) {
12362        ensureTransformationInfo();
12363        if (mTransformationInfo.mTransitionAlpha != alpha) {
12364            mTransformationInfo.mTransitionAlpha = alpha;
12365            mPrivateFlags &= ~PFLAG_ALPHA_SET;
12366            invalidateViewProperty(true, false);
12367            mRenderNode.setAlpha(getFinalAlpha());
12368        }
12369    }
12370
12371    /**
12372     * Calculates the visual alpha of this view, which is a combination of the actual
12373     * alpha value and the transitionAlpha value (if set).
12374     */
12375    private float getFinalAlpha() {
12376        if (mTransformationInfo != null) {
12377            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
12378        }
12379        return 1;
12380    }
12381
12382    /**
12383     * This property is hidden and intended only for use by the Fade transition, which
12384     * animates it to produce a visual translucency that does not side-effect (or get
12385     * affected by) the real alpha property. This value is composited with the other
12386     * alpha value (and the AlphaAnimation value, when that is present) to produce
12387     * a final visual translucency result, which is what is passed into the DisplayList.
12388     *
12389     * @hide
12390     */
12391    @ViewDebug.ExportedProperty(category = "drawing")
12392    public float getTransitionAlpha() {
12393        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
12394    }
12395
12396    /**
12397     * Top position of this view relative to its parent.
12398     *
12399     * @return The top of this view, in pixels.
12400     */
12401    @ViewDebug.CapturedViewProperty
12402    public final int getTop() {
12403        return mTop;
12404    }
12405
12406    /**
12407     * Sets the top position of this view relative to its parent. This method is meant to be called
12408     * by the layout system and should not generally be called otherwise, because the property
12409     * may be changed at any time by the layout.
12410     *
12411     * @param top The top of this view, in pixels.
12412     */
12413    public final void setTop(int top) {
12414        if (top != mTop) {
12415            final boolean matrixIsIdentity = hasIdentityMatrix();
12416            if (matrixIsIdentity) {
12417                if (mAttachInfo != null) {
12418                    int minTop;
12419                    int yLoc;
12420                    if (top < mTop) {
12421                        minTop = top;
12422                        yLoc = top - mTop;
12423                    } else {
12424                        minTop = mTop;
12425                        yLoc = 0;
12426                    }
12427                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
12428                }
12429            } else {
12430                // Double-invalidation is necessary to capture view's old and new areas
12431                invalidate(true);
12432            }
12433
12434            int width = mRight - mLeft;
12435            int oldHeight = mBottom - mTop;
12436
12437            mTop = top;
12438            mRenderNode.setTop(mTop);
12439
12440            sizeChange(width, mBottom - mTop, width, oldHeight);
12441
12442            if (!matrixIsIdentity) {
12443                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12444                invalidate(true);
12445            }
12446            mBackgroundSizeChanged = true;
12447            if (mForegroundInfo != null) {
12448                mForegroundInfo.mBoundsChanged = true;
12449            }
12450            invalidateParentIfNeeded();
12451            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12452                // View was rejected last time it was drawn by its parent; this may have changed
12453                invalidateParentIfNeeded();
12454            }
12455        }
12456    }
12457
12458    /**
12459     * Bottom position of this view relative to its parent.
12460     *
12461     * @return The bottom of this view, in pixels.
12462     */
12463    @ViewDebug.CapturedViewProperty
12464    public final int getBottom() {
12465        return mBottom;
12466    }
12467
12468    /**
12469     * True if this view has changed since the last time being drawn.
12470     *
12471     * @return The dirty state of this view.
12472     */
12473    public boolean isDirty() {
12474        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
12475    }
12476
12477    /**
12478     * Sets the bottom position of this view relative to its parent. This method is meant to be
12479     * called by the layout system and should not generally be called otherwise, because the
12480     * property may be changed at any time by the layout.
12481     *
12482     * @param bottom The bottom of this view, in pixels.
12483     */
12484    public final void setBottom(int bottom) {
12485        if (bottom != mBottom) {
12486            final boolean matrixIsIdentity = hasIdentityMatrix();
12487            if (matrixIsIdentity) {
12488                if (mAttachInfo != null) {
12489                    int maxBottom;
12490                    if (bottom < mBottom) {
12491                        maxBottom = mBottom;
12492                    } else {
12493                        maxBottom = bottom;
12494                    }
12495                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
12496                }
12497            } else {
12498                // Double-invalidation is necessary to capture view's old and new areas
12499                invalidate(true);
12500            }
12501
12502            int width = mRight - mLeft;
12503            int oldHeight = mBottom - mTop;
12504
12505            mBottom = bottom;
12506            mRenderNode.setBottom(mBottom);
12507
12508            sizeChange(width, mBottom - mTop, width, oldHeight);
12509
12510            if (!matrixIsIdentity) {
12511                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12512                invalidate(true);
12513            }
12514            mBackgroundSizeChanged = true;
12515            if (mForegroundInfo != null) {
12516                mForegroundInfo.mBoundsChanged = true;
12517            }
12518            invalidateParentIfNeeded();
12519            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12520                // View was rejected last time it was drawn by its parent; this may have changed
12521                invalidateParentIfNeeded();
12522            }
12523        }
12524    }
12525
12526    /**
12527     * Left position of this view relative to its parent.
12528     *
12529     * @return The left edge of this view, in pixels.
12530     */
12531    @ViewDebug.CapturedViewProperty
12532    public final int getLeft() {
12533        return mLeft;
12534    }
12535
12536    /**
12537     * Sets the left position of this view relative to its parent. This method is meant to be called
12538     * by the layout system and should not generally be called otherwise, because the property
12539     * may be changed at any time by the layout.
12540     *
12541     * @param left The left of this view, in pixels.
12542     */
12543    public final void setLeft(int left) {
12544        if (left != mLeft) {
12545            final boolean matrixIsIdentity = hasIdentityMatrix();
12546            if (matrixIsIdentity) {
12547                if (mAttachInfo != null) {
12548                    int minLeft;
12549                    int xLoc;
12550                    if (left < mLeft) {
12551                        minLeft = left;
12552                        xLoc = left - mLeft;
12553                    } else {
12554                        minLeft = mLeft;
12555                        xLoc = 0;
12556                    }
12557                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
12558                }
12559            } else {
12560                // Double-invalidation is necessary to capture view's old and new areas
12561                invalidate(true);
12562            }
12563
12564            int oldWidth = mRight - mLeft;
12565            int height = mBottom - mTop;
12566
12567            mLeft = left;
12568            mRenderNode.setLeft(left);
12569
12570            sizeChange(mRight - mLeft, height, oldWidth, height);
12571
12572            if (!matrixIsIdentity) {
12573                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12574                invalidate(true);
12575            }
12576            mBackgroundSizeChanged = true;
12577            if (mForegroundInfo != null) {
12578                mForegroundInfo.mBoundsChanged = true;
12579            }
12580            invalidateParentIfNeeded();
12581            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12582                // View was rejected last time it was drawn by its parent; this may have changed
12583                invalidateParentIfNeeded();
12584            }
12585        }
12586    }
12587
12588    /**
12589     * Right position of this view relative to its parent.
12590     *
12591     * @return The right edge of this view, in pixels.
12592     */
12593    @ViewDebug.CapturedViewProperty
12594    public final int getRight() {
12595        return mRight;
12596    }
12597
12598    /**
12599     * Sets the right position of this view relative to its parent. This method is meant to be called
12600     * by the layout system and should not generally be called otherwise, because the property
12601     * may be changed at any time by the layout.
12602     *
12603     * @param right The right of this view, in pixels.
12604     */
12605    public final void setRight(int right) {
12606        if (right != mRight) {
12607            final boolean matrixIsIdentity = hasIdentityMatrix();
12608            if (matrixIsIdentity) {
12609                if (mAttachInfo != null) {
12610                    int maxRight;
12611                    if (right < mRight) {
12612                        maxRight = mRight;
12613                    } else {
12614                        maxRight = right;
12615                    }
12616                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
12617                }
12618            } else {
12619                // Double-invalidation is necessary to capture view's old and new areas
12620                invalidate(true);
12621            }
12622
12623            int oldWidth = mRight - mLeft;
12624            int height = mBottom - mTop;
12625
12626            mRight = right;
12627            mRenderNode.setRight(mRight);
12628
12629            sizeChange(mRight - mLeft, height, oldWidth, height);
12630
12631            if (!matrixIsIdentity) {
12632                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12633                invalidate(true);
12634            }
12635            mBackgroundSizeChanged = true;
12636            if (mForegroundInfo != null) {
12637                mForegroundInfo.mBoundsChanged = true;
12638            }
12639            invalidateParentIfNeeded();
12640            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
12641                // View was rejected last time it was drawn by its parent; this may have changed
12642                invalidateParentIfNeeded();
12643            }
12644        }
12645    }
12646
12647    /**
12648     * The visual x position of this view, in pixels. This is equivalent to the
12649     * {@link #setTranslationX(float) translationX} property plus the current
12650     * {@link #getLeft() left} property.
12651     *
12652     * @return The visual x position of this view, in pixels.
12653     */
12654    @ViewDebug.ExportedProperty(category = "drawing")
12655    public float getX() {
12656        return mLeft + getTranslationX();
12657    }
12658
12659    /**
12660     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
12661     * {@link #setTranslationX(float) translationX} property to be the difference between
12662     * the x value passed in and the current {@link #getLeft() left} property.
12663     *
12664     * @param x The visual x position of this view, in pixels.
12665     */
12666    public void setX(float x) {
12667        setTranslationX(x - mLeft);
12668    }
12669
12670    /**
12671     * The visual y position of this view, in pixels. This is equivalent to the
12672     * {@link #setTranslationY(float) translationY} property plus the current
12673     * {@link #getTop() top} property.
12674     *
12675     * @return The visual y position of this view, in pixels.
12676     */
12677    @ViewDebug.ExportedProperty(category = "drawing")
12678    public float getY() {
12679        return mTop + getTranslationY();
12680    }
12681
12682    /**
12683     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
12684     * {@link #setTranslationY(float) translationY} property to be the difference between
12685     * the y value passed in and the current {@link #getTop() top} property.
12686     *
12687     * @param y The visual y position of this view, in pixels.
12688     */
12689    public void setY(float y) {
12690        setTranslationY(y - mTop);
12691    }
12692
12693    /**
12694     * The visual z position of this view, in pixels. This is equivalent to the
12695     * {@link #setTranslationZ(float) translationZ} property plus the current
12696     * {@link #getElevation() elevation} property.
12697     *
12698     * @return The visual z position of this view, in pixels.
12699     */
12700    @ViewDebug.ExportedProperty(category = "drawing")
12701    public float getZ() {
12702        return getElevation() + getTranslationZ();
12703    }
12704
12705    /**
12706     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
12707     * {@link #setTranslationZ(float) translationZ} property to be the difference between
12708     * the x value passed in and the current {@link #getElevation() elevation} property.
12709     *
12710     * @param z The visual z position of this view, in pixels.
12711     */
12712    public void setZ(float z) {
12713        setTranslationZ(z - getElevation());
12714    }
12715
12716    /**
12717     * The base elevation of this view relative to its parent, in pixels.
12718     *
12719     * @return The base depth position of the view, in pixels.
12720     */
12721    @ViewDebug.ExportedProperty(category = "drawing")
12722    public float getElevation() {
12723        return mRenderNode.getElevation();
12724    }
12725
12726    /**
12727     * Sets the base elevation of this view, in pixels.
12728     *
12729     * @attr ref android.R.styleable#View_elevation
12730     */
12731    public void setElevation(float elevation) {
12732        if (elevation != getElevation()) {
12733            invalidateViewProperty(true, false);
12734            mRenderNode.setElevation(elevation);
12735            invalidateViewProperty(false, true);
12736
12737            invalidateParentIfNeededAndWasQuickRejected();
12738        }
12739    }
12740
12741    /**
12742     * The horizontal location of this view relative to its {@link #getLeft() left} position.
12743     * This position is post-layout, in addition to wherever the object's
12744     * layout placed it.
12745     *
12746     * @return The horizontal position of this view relative to its left position, in pixels.
12747     */
12748    @ViewDebug.ExportedProperty(category = "drawing")
12749    public float getTranslationX() {
12750        return mRenderNode.getTranslationX();
12751    }
12752
12753    /**
12754     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
12755     * This effectively positions the object post-layout, in addition to wherever the object's
12756     * layout placed it.
12757     *
12758     * @param translationX The horizontal position of this view relative to its left position,
12759     * in pixels.
12760     *
12761     * @attr ref android.R.styleable#View_translationX
12762     */
12763    public void setTranslationX(float translationX) {
12764        if (translationX != getTranslationX()) {
12765            invalidateViewProperty(true, false);
12766            mRenderNode.setTranslationX(translationX);
12767            invalidateViewProperty(false, true);
12768
12769            invalidateParentIfNeededAndWasQuickRejected();
12770            notifySubtreeAccessibilityStateChangedIfNeeded();
12771        }
12772    }
12773
12774    /**
12775     * The vertical location of this view relative to its {@link #getTop() top} position.
12776     * This position is post-layout, in addition to wherever the object's
12777     * layout placed it.
12778     *
12779     * @return The vertical position of this view relative to its top position,
12780     * in pixels.
12781     */
12782    @ViewDebug.ExportedProperty(category = "drawing")
12783    public float getTranslationY() {
12784        return mRenderNode.getTranslationY();
12785    }
12786
12787    /**
12788     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
12789     * This effectively positions the object post-layout, in addition to wherever the object's
12790     * layout placed it.
12791     *
12792     * @param translationY The vertical position of this view relative to its top position,
12793     * in pixels.
12794     *
12795     * @attr ref android.R.styleable#View_translationY
12796     */
12797    public void setTranslationY(float translationY) {
12798        if (translationY != getTranslationY()) {
12799            invalidateViewProperty(true, false);
12800            mRenderNode.setTranslationY(translationY);
12801            invalidateViewProperty(false, true);
12802
12803            invalidateParentIfNeededAndWasQuickRejected();
12804            notifySubtreeAccessibilityStateChangedIfNeeded();
12805        }
12806    }
12807
12808    /**
12809     * The depth location of this view relative to its {@link #getElevation() elevation}.
12810     *
12811     * @return The depth of this view relative to its elevation.
12812     */
12813    @ViewDebug.ExportedProperty(category = "drawing")
12814    public float getTranslationZ() {
12815        return mRenderNode.getTranslationZ();
12816    }
12817
12818    /**
12819     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
12820     *
12821     * @attr ref android.R.styleable#View_translationZ
12822     */
12823    public void setTranslationZ(float translationZ) {
12824        if (translationZ != getTranslationZ()) {
12825            invalidateViewProperty(true, false);
12826            mRenderNode.setTranslationZ(translationZ);
12827            invalidateViewProperty(false, true);
12828
12829            invalidateParentIfNeededAndWasQuickRejected();
12830        }
12831    }
12832
12833    /** @hide */
12834    public void setAnimationMatrix(Matrix matrix) {
12835        invalidateViewProperty(true, false);
12836        mRenderNode.setAnimationMatrix(matrix);
12837        invalidateViewProperty(false, true);
12838
12839        invalidateParentIfNeededAndWasQuickRejected();
12840    }
12841
12842    /**
12843     * Returns the current StateListAnimator if exists.
12844     *
12845     * @return StateListAnimator or null if it does not exists
12846     * @see    #setStateListAnimator(android.animation.StateListAnimator)
12847     */
12848    public StateListAnimator getStateListAnimator() {
12849        return mStateListAnimator;
12850    }
12851
12852    /**
12853     * Attaches the provided StateListAnimator to this View.
12854     * <p>
12855     * Any previously attached StateListAnimator will be detached.
12856     *
12857     * @param stateListAnimator The StateListAnimator to update the view
12858     * @see {@link android.animation.StateListAnimator}
12859     */
12860    public void setStateListAnimator(StateListAnimator stateListAnimator) {
12861        if (mStateListAnimator == stateListAnimator) {
12862            return;
12863        }
12864        if (mStateListAnimator != null) {
12865            mStateListAnimator.setTarget(null);
12866        }
12867        mStateListAnimator = stateListAnimator;
12868        if (stateListAnimator != null) {
12869            stateListAnimator.setTarget(this);
12870            if (isAttachedToWindow()) {
12871                stateListAnimator.setState(getDrawableState());
12872            }
12873        }
12874    }
12875
12876    /**
12877     * Returns whether the Outline should be used to clip the contents of the View.
12878     * <p>
12879     * Note that this flag will only be respected if the View's Outline returns true from
12880     * {@link Outline#canClip()}.
12881     *
12882     * @see #setOutlineProvider(ViewOutlineProvider)
12883     * @see #setClipToOutline(boolean)
12884     */
12885    public final boolean getClipToOutline() {
12886        return mRenderNode.getClipToOutline();
12887    }
12888
12889    /**
12890     * Sets whether the View's Outline should be used to clip the contents of the View.
12891     * <p>
12892     * Only a single non-rectangular clip can be applied on a View at any time.
12893     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
12894     * circular reveal} animation take priority over Outline clipping, and
12895     * child Outline clipping takes priority over Outline clipping done by a
12896     * parent.
12897     * <p>
12898     * Note that this flag will only be respected if the View's Outline returns true from
12899     * {@link Outline#canClip()}.
12900     *
12901     * @see #setOutlineProvider(ViewOutlineProvider)
12902     * @see #getClipToOutline()
12903     */
12904    public void setClipToOutline(boolean clipToOutline) {
12905        damageInParent();
12906        if (getClipToOutline() != clipToOutline) {
12907            mRenderNode.setClipToOutline(clipToOutline);
12908        }
12909    }
12910
12911    // correspond to the enum values of View_outlineProvider
12912    private static final int PROVIDER_BACKGROUND = 0;
12913    private static final int PROVIDER_NONE = 1;
12914    private static final int PROVIDER_BOUNDS = 2;
12915    private static final int PROVIDER_PADDED_BOUNDS = 3;
12916    private void setOutlineProviderFromAttribute(int providerInt) {
12917        switch (providerInt) {
12918            case PROVIDER_BACKGROUND:
12919                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
12920                break;
12921            case PROVIDER_NONE:
12922                setOutlineProvider(null);
12923                break;
12924            case PROVIDER_BOUNDS:
12925                setOutlineProvider(ViewOutlineProvider.BOUNDS);
12926                break;
12927            case PROVIDER_PADDED_BOUNDS:
12928                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
12929                break;
12930        }
12931    }
12932
12933    /**
12934     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
12935     * the shape of the shadow it casts, and enables outline clipping.
12936     * <p>
12937     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
12938     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
12939     * outline provider with this method allows this behavior to be overridden.
12940     * <p>
12941     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
12942     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
12943     * <p>
12944     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
12945     *
12946     * @see #setClipToOutline(boolean)
12947     * @see #getClipToOutline()
12948     * @see #getOutlineProvider()
12949     */
12950    public void setOutlineProvider(ViewOutlineProvider provider) {
12951        mOutlineProvider = provider;
12952        invalidateOutline();
12953    }
12954
12955    /**
12956     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
12957     * that defines the shape of the shadow it casts, and enables outline clipping.
12958     *
12959     * @see #setOutlineProvider(ViewOutlineProvider)
12960     */
12961    public ViewOutlineProvider getOutlineProvider() {
12962        return mOutlineProvider;
12963    }
12964
12965    /**
12966     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
12967     *
12968     * @see #setOutlineProvider(ViewOutlineProvider)
12969     */
12970    public void invalidateOutline() {
12971        rebuildOutline();
12972
12973        notifySubtreeAccessibilityStateChangedIfNeeded();
12974        invalidateViewProperty(false, false);
12975    }
12976
12977    /**
12978     * Internal version of {@link #invalidateOutline()} which invalidates the
12979     * outline without invalidating the view itself. This is intended to be called from
12980     * within methods in the View class itself which are the result of the view being
12981     * invalidated already. For example, when we are drawing the background of a View,
12982     * we invalidate the outline in case it changed in the meantime, but we do not
12983     * need to invalidate the view because we're already drawing the background as part
12984     * of drawing the view in response to an earlier invalidation of the view.
12985     */
12986    private void rebuildOutline() {
12987        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
12988        if (mAttachInfo == null) return;
12989
12990        if (mOutlineProvider == null) {
12991            // no provider, remove outline
12992            mRenderNode.setOutline(null);
12993        } else {
12994            final Outline outline = mAttachInfo.mTmpOutline;
12995            outline.setEmpty();
12996            outline.setAlpha(1.0f);
12997
12998            mOutlineProvider.getOutline(this, outline);
12999            mRenderNode.setOutline(outline);
13000        }
13001    }
13002
13003    /**
13004     * HierarchyViewer only
13005     *
13006     * @hide
13007     */
13008    @ViewDebug.ExportedProperty(category = "drawing")
13009    public boolean hasShadow() {
13010        return mRenderNode.hasShadow();
13011    }
13012
13013
13014    /** @hide */
13015    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
13016        mRenderNode.setRevealClip(shouldClip, x, y, radius);
13017        invalidateViewProperty(false, false);
13018    }
13019
13020    /**
13021     * Hit rectangle in parent's coordinates
13022     *
13023     * @param outRect The hit rectangle of the view.
13024     */
13025    public void getHitRect(Rect outRect) {
13026        if (hasIdentityMatrix() || mAttachInfo == null) {
13027            outRect.set(mLeft, mTop, mRight, mBottom);
13028        } else {
13029            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
13030            tmpRect.set(0, 0, getWidth(), getHeight());
13031            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
13032            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
13033                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
13034        }
13035    }
13036
13037    /**
13038     * Determines whether the given point, in local coordinates is inside the view.
13039     */
13040    /*package*/ final boolean pointInView(float localX, float localY) {
13041        return pointInView(localX, localY, 0);
13042    }
13043
13044    /**
13045     * Utility method to determine whether the given point, in local coordinates,
13046     * is inside the view, where the area of the view is expanded by the slop factor.
13047     * This method is called while processing touch-move events to determine if the event
13048     * is still within the view.
13049     *
13050     * @hide
13051     */
13052    public boolean pointInView(float localX, float localY, float slop) {
13053        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
13054                localY < ((mBottom - mTop) + slop);
13055    }
13056
13057    /**
13058     * When a view has focus and the user navigates away from it, the next view is searched for
13059     * starting from the rectangle filled in by this method.
13060     *
13061     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
13062     * of the view.  However, if your view maintains some idea of internal selection,
13063     * such as a cursor, or a selected row or column, you should override this method and
13064     * fill in a more specific rectangle.
13065     *
13066     * @param r The rectangle to fill in, in this view's coordinates.
13067     */
13068    public void getFocusedRect(Rect r) {
13069        getDrawingRect(r);
13070    }
13071
13072    /**
13073     * If some part of this view is not clipped by any of its parents, then
13074     * return that area in r in global (root) coordinates. To convert r to local
13075     * coordinates (without taking possible View rotations into account), offset
13076     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
13077     * If the view is completely clipped or translated out, return false.
13078     *
13079     * @param r If true is returned, r holds the global coordinates of the
13080     *        visible portion of this view.
13081     * @param globalOffset If true is returned, globalOffset holds the dx,dy
13082     *        between this view and its root. globalOffet may be null.
13083     * @return true if r is non-empty (i.e. part of the view is visible at the
13084     *         root level.
13085     */
13086    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
13087        int width = mRight - mLeft;
13088        int height = mBottom - mTop;
13089        if (width > 0 && height > 0) {
13090            r.set(0, 0, width, height);
13091            if (globalOffset != null) {
13092                globalOffset.set(-mScrollX, -mScrollY);
13093            }
13094            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
13095        }
13096        return false;
13097    }
13098
13099    public final boolean getGlobalVisibleRect(Rect r) {
13100        return getGlobalVisibleRect(r, null);
13101    }
13102
13103    public final boolean getLocalVisibleRect(Rect r) {
13104        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
13105        if (getGlobalVisibleRect(r, offset)) {
13106            r.offset(-offset.x, -offset.y); // make r local
13107            return true;
13108        }
13109        return false;
13110    }
13111
13112    /**
13113     * Offset this view's vertical location by the specified number of pixels.
13114     *
13115     * @param offset the number of pixels to offset the view by
13116     */
13117    public void offsetTopAndBottom(int offset) {
13118        if (offset != 0) {
13119            final boolean matrixIsIdentity = hasIdentityMatrix();
13120            if (matrixIsIdentity) {
13121                if (isHardwareAccelerated()) {
13122                    invalidateViewProperty(false, false);
13123                } else {
13124                    final ViewParent p = mParent;
13125                    if (p != null && mAttachInfo != null) {
13126                        final Rect r = mAttachInfo.mTmpInvalRect;
13127                        int minTop;
13128                        int maxBottom;
13129                        int yLoc;
13130                        if (offset < 0) {
13131                            minTop = mTop + offset;
13132                            maxBottom = mBottom;
13133                            yLoc = offset;
13134                        } else {
13135                            minTop = mTop;
13136                            maxBottom = mBottom + offset;
13137                            yLoc = 0;
13138                        }
13139                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
13140                        p.invalidateChild(this, r);
13141                    }
13142                }
13143            } else {
13144                invalidateViewProperty(false, false);
13145            }
13146
13147            mTop += offset;
13148            mBottom += offset;
13149            mRenderNode.offsetTopAndBottom(offset);
13150            if (isHardwareAccelerated()) {
13151                invalidateViewProperty(false, false);
13152                invalidateParentIfNeededAndWasQuickRejected();
13153            } else {
13154                if (!matrixIsIdentity) {
13155                    invalidateViewProperty(false, true);
13156                }
13157                invalidateParentIfNeeded();
13158            }
13159            notifySubtreeAccessibilityStateChangedIfNeeded();
13160        }
13161    }
13162
13163    /**
13164     * Offset this view's horizontal location by the specified amount of pixels.
13165     *
13166     * @param offset the number of pixels to offset the view by
13167     */
13168    public void offsetLeftAndRight(int offset) {
13169        if (offset != 0) {
13170            final boolean matrixIsIdentity = hasIdentityMatrix();
13171            if (matrixIsIdentity) {
13172                if (isHardwareAccelerated()) {
13173                    invalidateViewProperty(false, false);
13174                } else {
13175                    final ViewParent p = mParent;
13176                    if (p != null && mAttachInfo != null) {
13177                        final Rect r = mAttachInfo.mTmpInvalRect;
13178                        int minLeft;
13179                        int maxRight;
13180                        if (offset < 0) {
13181                            minLeft = mLeft + offset;
13182                            maxRight = mRight;
13183                        } else {
13184                            minLeft = mLeft;
13185                            maxRight = mRight + offset;
13186                        }
13187                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
13188                        p.invalidateChild(this, r);
13189                    }
13190                }
13191            } else {
13192                invalidateViewProperty(false, false);
13193            }
13194
13195            mLeft += offset;
13196            mRight += offset;
13197            mRenderNode.offsetLeftAndRight(offset);
13198            if (isHardwareAccelerated()) {
13199                invalidateViewProperty(false, false);
13200                invalidateParentIfNeededAndWasQuickRejected();
13201            } else {
13202                if (!matrixIsIdentity) {
13203                    invalidateViewProperty(false, true);
13204                }
13205                invalidateParentIfNeeded();
13206            }
13207            notifySubtreeAccessibilityStateChangedIfNeeded();
13208        }
13209    }
13210
13211    /**
13212     * Get the LayoutParams associated with this view. All views should have
13213     * layout parameters. These supply parameters to the <i>parent</i> of this
13214     * view specifying how it should be arranged. There are many subclasses of
13215     * ViewGroup.LayoutParams, and these correspond to the different subclasses
13216     * of ViewGroup that are responsible for arranging their children.
13217     *
13218     * This method may return null if this View is not attached to a parent
13219     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
13220     * was not invoked successfully. When a View is attached to a parent
13221     * ViewGroup, this method must not return null.
13222     *
13223     * @return The LayoutParams associated with this view, or null if no
13224     *         parameters have been set yet
13225     */
13226    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
13227    public ViewGroup.LayoutParams getLayoutParams() {
13228        return mLayoutParams;
13229    }
13230
13231    /**
13232     * Set the layout parameters associated with this view. These supply
13233     * parameters to the <i>parent</i> of this view specifying how it should be
13234     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
13235     * correspond to the different subclasses of ViewGroup that are responsible
13236     * for arranging their children.
13237     *
13238     * @param params The layout parameters for this view, cannot be null
13239     */
13240    public void setLayoutParams(ViewGroup.LayoutParams params) {
13241        if (params == null) {
13242            throw new NullPointerException("Layout parameters cannot be null");
13243        }
13244        mLayoutParams = params;
13245        resolveLayoutParams();
13246        if (mParent instanceof ViewGroup) {
13247            ((ViewGroup) mParent).onSetLayoutParams(this, params);
13248        }
13249        requestLayout();
13250    }
13251
13252    /**
13253     * Resolve the layout parameters depending on the resolved layout direction
13254     *
13255     * @hide
13256     */
13257    public void resolveLayoutParams() {
13258        if (mLayoutParams != null) {
13259            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
13260        }
13261    }
13262
13263    /**
13264     * Set the scrolled position of your view. This will cause a call to
13265     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13266     * invalidated.
13267     * @param x the x position to scroll to
13268     * @param y the y position to scroll to
13269     */
13270    public void scrollTo(int x, int y) {
13271        if (mScrollX != x || mScrollY != y) {
13272            int oldX = mScrollX;
13273            int oldY = mScrollY;
13274            mScrollX = x;
13275            mScrollY = y;
13276            invalidateParentCaches();
13277            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
13278            if (!awakenScrollBars()) {
13279                postInvalidateOnAnimation();
13280            }
13281        }
13282    }
13283
13284    /**
13285     * Move the scrolled position of your view. This will cause a call to
13286     * {@link #onScrollChanged(int, int, int, int)} and the view will be
13287     * invalidated.
13288     * @param x the amount of pixels to scroll by horizontally
13289     * @param y the amount of pixels to scroll by vertically
13290     */
13291    public void scrollBy(int x, int y) {
13292        scrollTo(mScrollX + x, mScrollY + y);
13293    }
13294
13295    /**
13296     * <p>Trigger the scrollbars to draw. When invoked this method starts an
13297     * animation to fade the scrollbars out after a default delay. If a subclass
13298     * provides animated scrolling, the start delay should equal the duration
13299     * of the scrolling animation.</p>
13300     *
13301     * <p>The animation starts only if at least one of the scrollbars is
13302     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
13303     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13304     * this method returns true, and false otherwise. If the animation is
13305     * started, this method calls {@link #invalidate()}; in that case the
13306     * caller should not call {@link #invalidate()}.</p>
13307     *
13308     * <p>This method should be invoked every time a subclass directly updates
13309     * the scroll parameters.</p>
13310     *
13311     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
13312     * and {@link #scrollTo(int, int)}.</p>
13313     *
13314     * @return true if the animation is played, false otherwise
13315     *
13316     * @see #awakenScrollBars(int)
13317     * @see #scrollBy(int, int)
13318     * @see #scrollTo(int, int)
13319     * @see #isHorizontalScrollBarEnabled()
13320     * @see #isVerticalScrollBarEnabled()
13321     * @see #setHorizontalScrollBarEnabled(boolean)
13322     * @see #setVerticalScrollBarEnabled(boolean)
13323     */
13324    protected boolean awakenScrollBars() {
13325        return mScrollCache != null &&
13326                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
13327    }
13328
13329    /**
13330     * Trigger the scrollbars to draw.
13331     * This method differs from awakenScrollBars() only in its default duration.
13332     * initialAwakenScrollBars() will show the scroll bars for longer than
13333     * usual to give the user more of a chance to notice them.
13334     *
13335     * @return true if the animation is played, false otherwise.
13336     */
13337    private boolean initialAwakenScrollBars() {
13338        return mScrollCache != null &&
13339                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
13340    }
13341
13342    /**
13343     * <p>
13344     * Trigger the scrollbars to draw. When invoked this method starts an
13345     * animation to fade the scrollbars out after a fixed delay. If a subclass
13346     * provides animated scrolling, the start delay should equal the duration of
13347     * the scrolling animation.
13348     * </p>
13349     *
13350     * <p>
13351     * The animation starts only if at least one of the scrollbars is enabled,
13352     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13353     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13354     * this method returns true, and false otherwise. If the animation is
13355     * started, this method calls {@link #invalidate()}; in that case the caller
13356     * should not call {@link #invalidate()}.
13357     * </p>
13358     *
13359     * <p>
13360     * This method should be invoked every time a subclass directly updates the
13361     * scroll parameters.
13362     * </p>
13363     *
13364     * @param startDelay the delay, in milliseconds, after which the animation
13365     *        should start; when the delay is 0, the animation starts
13366     *        immediately
13367     * @return true if the animation is played, false otherwise
13368     *
13369     * @see #scrollBy(int, int)
13370     * @see #scrollTo(int, int)
13371     * @see #isHorizontalScrollBarEnabled()
13372     * @see #isVerticalScrollBarEnabled()
13373     * @see #setHorizontalScrollBarEnabled(boolean)
13374     * @see #setVerticalScrollBarEnabled(boolean)
13375     */
13376    protected boolean awakenScrollBars(int startDelay) {
13377        return awakenScrollBars(startDelay, true);
13378    }
13379
13380    /**
13381     * <p>
13382     * Trigger the scrollbars to draw. When invoked this method starts an
13383     * animation to fade the scrollbars out after a fixed delay. If a subclass
13384     * provides animated scrolling, the start delay should equal the duration of
13385     * the scrolling animation.
13386     * </p>
13387     *
13388     * <p>
13389     * The animation starts only if at least one of the scrollbars is enabled,
13390     * as specified by {@link #isHorizontalScrollBarEnabled()} and
13391     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
13392     * this method returns true, and false otherwise. If the animation is
13393     * started, this method calls {@link #invalidate()} if the invalidate parameter
13394     * is set to true; in that case the caller
13395     * should not call {@link #invalidate()}.
13396     * </p>
13397     *
13398     * <p>
13399     * This method should be invoked every time a subclass directly updates the
13400     * scroll parameters.
13401     * </p>
13402     *
13403     * @param startDelay the delay, in milliseconds, after which the animation
13404     *        should start; when the delay is 0, the animation starts
13405     *        immediately
13406     *
13407     * @param invalidate Whether this method should call invalidate
13408     *
13409     * @return true if the animation is played, false otherwise
13410     *
13411     * @see #scrollBy(int, int)
13412     * @see #scrollTo(int, int)
13413     * @see #isHorizontalScrollBarEnabled()
13414     * @see #isVerticalScrollBarEnabled()
13415     * @see #setHorizontalScrollBarEnabled(boolean)
13416     * @see #setVerticalScrollBarEnabled(boolean)
13417     */
13418    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
13419        final ScrollabilityCache scrollCache = mScrollCache;
13420
13421        if (scrollCache == null || !scrollCache.fadeScrollBars) {
13422            return false;
13423        }
13424
13425        if (scrollCache.scrollBar == null) {
13426            scrollCache.scrollBar = new ScrollBarDrawable();
13427            scrollCache.scrollBar.setState(getDrawableState());
13428            scrollCache.scrollBar.setCallback(this);
13429        }
13430
13431        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
13432
13433            if (invalidate) {
13434                // Invalidate to show the scrollbars
13435                postInvalidateOnAnimation();
13436            }
13437
13438            if (scrollCache.state == ScrollabilityCache.OFF) {
13439                // FIXME: this is copied from WindowManagerService.
13440                // We should get this value from the system when it
13441                // is possible to do so.
13442                final int KEY_REPEAT_FIRST_DELAY = 750;
13443                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
13444            }
13445
13446            // Tell mScrollCache when we should start fading. This may
13447            // extend the fade start time if one was already scheduled
13448            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
13449            scrollCache.fadeStartTime = fadeStartTime;
13450            scrollCache.state = ScrollabilityCache.ON;
13451
13452            // Schedule our fader to run, unscheduling any old ones first
13453            if (mAttachInfo != null) {
13454                mAttachInfo.mHandler.removeCallbacks(scrollCache);
13455                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
13456            }
13457
13458            return true;
13459        }
13460
13461        return false;
13462    }
13463
13464    /**
13465     * Do not invalidate views which are not visible and which are not running an animation. They
13466     * will not get drawn and they should not set dirty flags as if they will be drawn
13467     */
13468    private boolean skipInvalidate() {
13469        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
13470                (!(mParent instanceof ViewGroup) ||
13471                        !((ViewGroup) mParent).isViewTransitioning(this));
13472    }
13473
13474    /**
13475     * Mark the area defined by dirty as needing to be drawn. If the view is
13476     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13477     * point in the future.
13478     * <p>
13479     * This must be called from a UI thread. To call from a non-UI thread, call
13480     * {@link #postInvalidate()}.
13481     * <p>
13482     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
13483     * {@code dirty}.
13484     *
13485     * @param dirty the rectangle representing the bounds of the dirty region
13486     */
13487    public void invalidate(Rect dirty) {
13488        final int scrollX = mScrollX;
13489        final int scrollY = mScrollY;
13490        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
13491                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
13492    }
13493
13494    /**
13495     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
13496     * coordinates of the dirty rect are relative to the view. If the view is
13497     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
13498     * point in the future.
13499     * <p>
13500     * This must be called from a UI thread. To call from a non-UI thread, call
13501     * {@link #postInvalidate()}.
13502     *
13503     * @param l the left position of the dirty region
13504     * @param t the top position of the dirty region
13505     * @param r the right position of the dirty region
13506     * @param b the bottom position of the dirty region
13507     */
13508    public void invalidate(int l, int t, int r, int b) {
13509        final int scrollX = mScrollX;
13510        final int scrollY = mScrollY;
13511        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
13512    }
13513
13514    /**
13515     * Invalidate the whole view. If the view is visible,
13516     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
13517     * the future.
13518     * <p>
13519     * This must be called from a UI thread. To call from a non-UI thread, call
13520     * {@link #postInvalidate()}.
13521     */
13522    public void invalidate() {
13523        invalidate(true);
13524    }
13525
13526    /**
13527     * This is where the invalidate() work actually happens. A full invalidate()
13528     * causes the drawing cache to be invalidated, but this function can be
13529     * called with invalidateCache set to false to skip that invalidation step
13530     * for cases that do not need it (for example, a component that remains at
13531     * the same dimensions with the same content).
13532     *
13533     * @param invalidateCache Whether the drawing cache for this view should be
13534     *            invalidated as well. This is usually true for a full
13535     *            invalidate, but may be set to false if the View's contents or
13536     *            dimensions have not changed.
13537     */
13538    void invalidate(boolean invalidateCache) {
13539        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
13540    }
13541
13542    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
13543            boolean fullInvalidate) {
13544        if (mGhostView != null) {
13545            mGhostView.invalidate(true);
13546            return;
13547        }
13548
13549        if (skipInvalidate()) {
13550            return;
13551        }
13552
13553        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
13554                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
13555                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
13556                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
13557            if (fullInvalidate) {
13558                mLastIsOpaque = isOpaque();
13559                mPrivateFlags &= ~PFLAG_DRAWN;
13560            }
13561
13562            mPrivateFlags |= PFLAG_DIRTY;
13563
13564            if (invalidateCache) {
13565                mPrivateFlags |= PFLAG_INVALIDATED;
13566                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13567            }
13568
13569            // Propagate the damage rectangle to the parent view.
13570            final AttachInfo ai = mAttachInfo;
13571            final ViewParent p = mParent;
13572            if (p != null && ai != null && l < r && t < b) {
13573                final Rect damage = ai.mTmpInvalRect;
13574                damage.set(l, t, r, b);
13575                p.invalidateChild(this, damage);
13576            }
13577
13578            // Damage the entire projection receiver, if necessary.
13579            if (mBackground != null && mBackground.isProjected()) {
13580                final View receiver = getProjectionReceiver();
13581                if (receiver != null) {
13582                    receiver.damageInParent();
13583                }
13584            }
13585
13586            // Damage the entire IsolatedZVolume receiving this view's shadow.
13587            if (isHardwareAccelerated() && getZ() != 0) {
13588                damageShadowReceiver();
13589            }
13590        }
13591    }
13592
13593    /**
13594     * @return this view's projection receiver, or {@code null} if none exists
13595     */
13596    private View getProjectionReceiver() {
13597        ViewParent p = getParent();
13598        while (p != null && p instanceof View) {
13599            final View v = (View) p;
13600            if (v.isProjectionReceiver()) {
13601                return v;
13602            }
13603            p = p.getParent();
13604        }
13605
13606        return null;
13607    }
13608
13609    /**
13610     * @return whether the view is a projection receiver
13611     */
13612    private boolean isProjectionReceiver() {
13613        return mBackground != null;
13614    }
13615
13616    /**
13617     * Damage area of the screen that can be covered by this View's shadow.
13618     *
13619     * This method will guarantee that any changes to shadows cast by a View
13620     * are damaged on the screen for future redraw.
13621     */
13622    private void damageShadowReceiver() {
13623        final AttachInfo ai = mAttachInfo;
13624        if (ai != null) {
13625            ViewParent p = getParent();
13626            if (p != null && p instanceof ViewGroup) {
13627                final ViewGroup vg = (ViewGroup) p;
13628                vg.damageInParent();
13629            }
13630        }
13631    }
13632
13633    /**
13634     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
13635     * set any flags or handle all of the cases handled by the default invalidation methods.
13636     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
13637     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
13638     * walk up the hierarchy, transforming the dirty rect as necessary.
13639     *
13640     * The method also handles normal invalidation logic if display list properties are not
13641     * being used in this view. The invalidateParent and forceRedraw flags are used by that
13642     * backup approach, to handle these cases used in the various property-setting methods.
13643     *
13644     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
13645     * are not being used in this view
13646     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
13647     * list properties are not being used in this view
13648     */
13649    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
13650        if (!isHardwareAccelerated()
13651                || !mRenderNode.isValid()
13652                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
13653            if (invalidateParent) {
13654                invalidateParentCaches();
13655            }
13656            if (forceRedraw) {
13657                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
13658            }
13659            invalidate(false);
13660        } else {
13661            damageInParent();
13662        }
13663        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
13664            damageShadowReceiver();
13665        }
13666    }
13667
13668    /**
13669     * Tells the parent view to damage this view's bounds.
13670     *
13671     * @hide
13672     */
13673    protected void damageInParent() {
13674        final AttachInfo ai = mAttachInfo;
13675        final ViewParent p = mParent;
13676        if (p != null && ai != null) {
13677            final Rect r = ai.mTmpInvalRect;
13678            r.set(0, 0, mRight - mLeft, mBottom - mTop);
13679            if (mParent instanceof ViewGroup) {
13680                ((ViewGroup) mParent).damageChild(this, r);
13681            } else {
13682                mParent.invalidateChild(this, r);
13683            }
13684        }
13685    }
13686
13687    /**
13688     * Utility method to transform a given Rect by the current matrix of this view.
13689     */
13690    void transformRect(final Rect rect) {
13691        if (!getMatrix().isIdentity()) {
13692            RectF boundingRect = mAttachInfo.mTmpTransformRect;
13693            boundingRect.set(rect);
13694            getMatrix().mapRect(boundingRect);
13695            rect.set((int) Math.floor(boundingRect.left),
13696                    (int) Math.floor(boundingRect.top),
13697                    (int) Math.ceil(boundingRect.right),
13698                    (int) Math.ceil(boundingRect.bottom));
13699        }
13700    }
13701
13702    /**
13703     * Used to indicate that the parent of this view should clear its caches. This functionality
13704     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13705     * which is necessary when various parent-managed properties of the view change, such as
13706     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
13707     * clears the parent caches and does not causes an invalidate event.
13708     *
13709     * @hide
13710     */
13711    protected void invalidateParentCaches() {
13712        if (mParent instanceof View) {
13713            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
13714        }
13715    }
13716
13717    /**
13718     * Used to indicate that the parent of this view should be invalidated. This functionality
13719     * is used to force the parent to rebuild its display list (when hardware-accelerated),
13720     * which is necessary when various parent-managed properties of the view change, such as
13721     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
13722     * an invalidation event to the parent.
13723     *
13724     * @hide
13725     */
13726    protected void invalidateParentIfNeeded() {
13727        if (isHardwareAccelerated() && mParent instanceof View) {
13728            ((View) mParent).invalidate(true);
13729        }
13730    }
13731
13732    /**
13733     * @hide
13734     */
13735    protected void invalidateParentIfNeededAndWasQuickRejected() {
13736        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
13737            // View was rejected last time it was drawn by its parent; this may have changed
13738            invalidateParentIfNeeded();
13739        }
13740    }
13741
13742    /**
13743     * Indicates whether this View is opaque. An opaque View guarantees that it will
13744     * draw all the pixels overlapping its bounds using a fully opaque color.
13745     *
13746     * Subclasses of View should override this method whenever possible to indicate
13747     * whether an instance is opaque. Opaque Views are treated in a special way by
13748     * the View hierarchy, possibly allowing it to perform optimizations during
13749     * invalidate/draw passes.
13750     *
13751     * @return True if this View is guaranteed to be fully opaque, false otherwise.
13752     */
13753    @ViewDebug.ExportedProperty(category = "drawing")
13754    public boolean isOpaque() {
13755        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
13756                getFinalAlpha() >= 1.0f;
13757    }
13758
13759    /**
13760     * @hide
13761     */
13762    protected void computeOpaqueFlags() {
13763        // Opaque if:
13764        //   - Has a background
13765        //   - Background is opaque
13766        //   - Doesn't have scrollbars or scrollbars overlay
13767
13768        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
13769            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
13770        } else {
13771            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
13772        }
13773
13774        final int flags = mViewFlags;
13775        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
13776                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
13777                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
13778            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
13779        } else {
13780            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
13781        }
13782    }
13783
13784    /**
13785     * @hide
13786     */
13787    protected boolean hasOpaqueScrollbars() {
13788        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
13789    }
13790
13791    /**
13792     * @return A handler associated with the thread running the View. This
13793     * handler can be used to pump events in the UI events queue.
13794     */
13795    public Handler getHandler() {
13796        final AttachInfo attachInfo = mAttachInfo;
13797        if (attachInfo != null) {
13798            return attachInfo.mHandler;
13799        }
13800        return null;
13801    }
13802
13803    /**
13804     * Returns the queue of runnable for this view.
13805     *
13806     * @return the queue of runnables for this view
13807     */
13808    private HandlerActionQueue getRunQueue() {
13809        if (mRunQueue == null) {
13810            mRunQueue = new HandlerActionQueue();
13811        }
13812        return mRunQueue;
13813    }
13814
13815    /**
13816     * Gets the view root associated with the View.
13817     * @return The view root, or null if none.
13818     * @hide
13819     */
13820    public ViewRootImpl getViewRootImpl() {
13821        if (mAttachInfo != null) {
13822            return mAttachInfo.mViewRootImpl;
13823        }
13824        return null;
13825    }
13826
13827    /**
13828     * @hide
13829     */
13830    public ThreadedRenderer getThreadedRenderer() {
13831        return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null;
13832    }
13833
13834    /**
13835     * <p>Causes the Runnable to be added to the message queue.
13836     * The runnable will be run on the user interface thread.</p>
13837     *
13838     * @param action The Runnable that will be executed.
13839     *
13840     * @return Returns true if the Runnable was successfully placed in to the
13841     *         message queue.  Returns false on failure, usually because the
13842     *         looper processing the message queue is exiting.
13843     *
13844     * @see #postDelayed
13845     * @see #removeCallbacks
13846     */
13847    public boolean post(Runnable action) {
13848        final AttachInfo attachInfo = mAttachInfo;
13849        if (attachInfo != null) {
13850            return attachInfo.mHandler.post(action);
13851        }
13852
13853        // Postpone the runnable until we know on which thread it needs to run.
13854        // Assume that the runnable will be successfully placed after attach.
13855        getRunQueue().post(action);
13856        return true;
13857    }
13858
13859    /**
13860     * <p>Causes the Runnable to be added to the message queue, to be run
13861     * after the specified amount of time elapses.
13862     * The runnable will be run on the user interface thread.</p>
13863     *
13864     * @param action The Runnable that will be executed.
13865     * @param delayMillis The delay (in milliseconds) until the Runnable
13866     *        will be executed.
13867     *
13868     * @return true if the Runnable was successfully placed in to the
13869     *         message queue.  Returns false on failure, usually because the
13870     *         looper processing the message queue is exiting.  Note that a
13871     *         result of true does not mean the Runnable will be processed --
13872     *         if the looper is quit before the delivery time of the message
13873     *         occurs then the message will be dropped.
13874     *
13875     * @see #post
13876     * @see #removeCallbacks
13877     */
13878    public boolean postDelayed(Runnable action, long delayMillis) {
13879        final AttachInfo attachInfo = mAttachInfo;
13880        if (attachInfo != null) {
13881            return attachInfo.mHandler.postDelayed(action, delayMillis);
13882        }
13883
13884        // Postpone the runnable until we know on which thread it needs to run.
13885        // Assume that the runnable will be successfully placed after attach.
13886        getRunQueue().postDelayed(action, delayMillis);
13887        return true;
13888    }
13889
13890    /**
13891     * <p>Causes the Runnable to execute on the next animation time step.
13892     * The runnable will be run on the user interface thread.</p>
13893     *
13894     * @param action The Runnable that will be executed.
13895     *
13896     * @see #postOnAnimationDelayed
13897     * @see #removeCallbacks
13898     */
13899    public void postOnAnimation(Runnable action) {
13900        final AttachInfo attachInfo = mAttachInfo;
13901        if (attachInfo != null) {
13902            attachInfo.mViewRootImpl.mChoreographer.postCallback(
13903                    Choreographer.CALLBACK_ANIMATION, action, null);
13904        } else {
13905            // Postpone the runnable until we know
13906            // on which thread it needs to run.
13907            getRunQueue().post(action);
13908        }
13909    }
13910
13911    /**
13912     * <p>Causes the Runnable to execute on the next animation time step,
13913     * after the specified amount of time elapses.
13914     * The runnable will be run on the user interface thread.</p>
13915     *
13916     * @param action The Runnable that will be executed.
13917     * @param delayMillis The delay (in milliseconds) until the Runnable
13918     *        will be executed.
13919     *
13920     * @see #postOnAnimation
13921     * @see #removeCallbacks
13922     */
13923    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
13924        final AttachInfo attachInfo = mAttachInfo;
13925        if (attachInfo != null) {
13926            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13927                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
13928        } else {
13929            // Postpone the runnable until we know
13930            // on which thread it needs to run.
13931            getRunQueue().postDelayed(action, delayMillis);
13932        }
13933    }
13934
13935    /**
13936     * <p>Removes the specified Runnable from the message queue.</p>
13937     *
13938     * @param action The Runnable to remove from the message handling queue
13939     *
13940     * @return true if this view could ask the Handler to remove the Runnable,
13941     *         false otherwise. When the returned value is true, the Runnable
13942     *         may or may not have been actually removed from the message queue
13943     *         (for instance, if the Runnable was not in the queue already.)
13944     *
13945     * @see #post
13946     * @see #postDelayed
13947     * @see #postOnAnimation
13948     * @see #postOnAnimationDelayed
13949     */
13950    public boolean removeCallbacks(Runnable action) {
13951        if (action != null) {
13952            final AttachInfo attachInfo = mAttachInfo;
13953            if (attachInfo != null) {
13954                attachInfo.mHandler.removeCallbacks(action);
13955                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13956                        Choreographer.CALLBACK_ANIMATION, action, null);
13957            }
13958            getRunQueue().removeCallbacks(action);
13959        }
13960        return true;
13961    }
13962
13963    /**
13964     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
13965     * Use this to invalidate the View from a non-UI thread.</p>
13966     *
13967     * <p>This method can be invoked from outside of the UI thread
13968     * only when this View is attached to a window.</p>
13969     *
13970     * @see #invalidate()
13971     * @see #postInvalidateDelayed(long)
13972     */
13973    public void postInvalidate() {
13974        postInvalidateDelayed(0);
13975    }
13976
13977    /**
13978     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
13979     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
13980     *
13981     * <p>This method can be invoked from outside of the UI thread
13982     * only when this View is attached to a window.</p>
13983     *
13984     * @param left The left coordinate of the rectangle to invalidate.
13985     * @param top The top coordinate of the rectangle to invalidate.
13986     * @param right The right coordinate of the rectangle to invalidate.
13987     * @param bottom The bottom coordinate of the rectangle to invalidate.
13988     *
13989     * @see #invalidate(int, int, int, int)
13990     * @see #invalidate(Rect)
13991     * @see #postInvalidateDelayed(long, int, int, int, int)
13992     */
13993    public void postInvalidate(int left, int top, int right, int bottom) {
13994        postInvalidateDelayed(0, left, top, right, bottom);
13995    }
13996
13997    /**
13998     * <p>Cause an invalidate to happen on a subsequent cycle through the event
13999     * loop. Waits for the specified amount of time.</p>
14000     *
14001     * <p>This method can be invoked from outside of the UI thread
14002     * only when this View is attached to a window.</p>
14003     *
14004     * @param delayMilliseconds the duration in milliseconds to delay the
14005     *         invalidation by
14006     *
14007     * @see #invalidate()
14008     * @see #postInvalidate()
14009     */
14010    public void postInvalidateDelayed(long delayMilliseconds) {
14011        // We try only with the AttachInfo because there's no point in invalidating
14012        // if we are not attached to our window
14013        final AttachInfo attachInfo = mAttachInfo;
14014        if (attachInfo != null) {
14015            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
14016        }
14017    }
14018
14019    /**
14020     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
14021     * through the event loop. Waits for the specified amount of time.</p>
14022     *
14023     * <p>This method can be invoked from outside of the UI thread
14024     * only when this View is attached to a window.</p>
14025     *
14026     * @param delayMilliseconds the duration in milliseconds to delay the
14027     *         invalidation by
14028     * @param left The left coordinate of the rectangle to invalidate.
14029     * @param top The top coordinate of the rectangle to invalidate.
14030     * @param right The right coordinate of the rectangle to invalidate.
14031     * @param bottom The bottom coordinate of the rectangle to invalidate.
14032     *
14033     * @see #invalidate(int, int, int, int)
14034     * @see #invalidate(Rect)
14035     * @see #postInvalidate(int, int, int, int)
14036     */
14037    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
14038            int right, int bottom) {
14039
14040        // We try only with the AttachInfo because there's no point in invalidating
14041        // if we are not attached to our window
14042        final AttachInfo attachInfo = mAttachInfo;
14043        if (attachInfo != null) {
14044            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14045            info.target = this;
14046            info.left = left;
14047            info.top = top;
14048            info.right = right;
14049            info.bottom = bottom;
14050
14051            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
14052        }
14053    }
14054
14055    /**
14056     * <p>Cause an invalidate to happen on the next animation time step, typically the
14057     * next display frame.</p>
14058     *
14059     * <p>This method can be invoked from outside of the UI thread
14060     * only when this View is attached to a window.</p>
14061     *
14062     * @see #invalidate()
14063     */
14064    public void postInvalidateOnAnimation() {
14065        // We try only with the AttachInfo because there's no point in invalidating
14066        // if we are not attached to our window
14067        final AttachInfo attachInfo = mAttachInfo;
14068        if (attachInfo != null) {
14069            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
14070        }
14071    }
14072
14073    /**
14074     * <p>Cause an invalidate of the specified area to happen on the next animation
14075     * time step, typically the next display frame.</p>
14076     *
14077     * <p>This method can be invoked from outside of the UI thread
14078     * only when this View is attached to a window.</p>
14079     *
14080     * @param left The left coordinate of the rectangle to invalidate.
14081     * @param top The top coordinate of the rectangle to invalidate.
14082     * @param right The right coordinate of the rectangle to invalidate.
14083     * @param bottom The bottom coordinate of the rectangle to invalidate.
14084     *
14085     * @see #invalidate(int, int, int, int)
14086     * @see #invalidate(Rect)
14087     */
14088    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
14089        // We try only with the AttachInfo because there's no point in invalidating
14090        // if we are not attached to our window
14091        final AttachInfo attachInfo = mAttachInfo;
14092        if (attachInfo != null) {
14093            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
14094            info.target = this;
14095            info.left = left;
14096            info.top = top;
14097            info.right = right;
14098            info.bottom = bottom;
14099
14100            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
14101        }
14102    }
14103
14104    /**
14105     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
14106     * This event is sent at most once every
14107     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
14108     */
14109    private void postSendViewScrolledAccessibilityEventCallback() {
14110        if (mSendViewScrolledAccessibilityEvent == null) {
14111            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
14112        }
14113        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
14114            mSendViewScrolledAccessibilityEvent.mIsPending = true;
14115            postDelayed(mSendViewScrolledAccessibilityEvent,
14116                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
14117        }
14118    }
14119
14120    /**
14121     * Called by a parent to request that a child update its values for mScrollX
14122     * and mScrollY if necessary. This will typically be done if the child is
14123     * animating a scroll using a {@link android.widget.Scroller Scroller}
14124     * object.
14125     */
14126    public void computeScroll() {
14127    }
14128
14129    /**
14130     * <p>Indicate whether the horizontal edges are faded when the view is
14131     * scrolled horizontally.</p>
14132     *
14133     * @return true if the horizontal edges should are faded on scroll, false
14134     *         otherwise
14135     *
14136     * @see #setHorizontalFadingEdgeEnabled(boolean)
14137     *
14138     * @attr ref android.R.styleable#View_requiresFadingEdge
14139     */
14140    public boolean isHorizontalFadingEdgeEnabled() {
14141        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
14142    }
14143
14144    /**
14145     * <p>Define whether the horizontal edges should be faded when this view
14146     * is scrolled horizontally.</p>
14147     *
14148     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
14149     *                                    be faded when the view is scrolled
14150     *                                    horizontally
14151     *
14152     * @see #isHorizontalFadingEdgeEnabled()
14153     *
14154     * @attr ref android.R.styleable#View_requiresFadingEdge
14155     */
14156    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
14157        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
14158            if (horizontalFadingEdgeEnabled) {
14159                initScrollCache();
14160            }
14161
14162            mViewFlags ^= FADING_EDGE_HORIZONTAL;
14163        }
14164    }
14165
14166    /**
14167     * <p>Indicate whether the vertical edges are faded when the view is
14168     * scrolled horizontally.</p>
14169     *
14170     * @return true if the vertical edges should are faded on scroll, false
14171     *         otherwise
14172     *
14173     * @see #setVerticalFadingEdgeEnabled(boolean)
14174     *
14175     * @attr ref android.R.styleable#View_requiresFadingEdge
14176     */
14177    public boolean isVerticalFadingEdgeEnabled() {
14178        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
14179    }
14180
14181    /**
14182     * <p>Define whether the vertical edges should be faded when this view
14183     * is scrolled vertically.</p>
14184     *
14185     * @param verticalFadingEdgeEnabled true if the vertical edges should
14186     *                                  be faded when the view is scrolled
14187     *                                  vertically
14188     *
14189     * @see #isVerticalFadingEdgeEnabled()
14190     *
14191     * @attr ref android.R.styleable#View_requiresFadingEdge
14192     */
14193    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
14194        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
14195            if (verticalFadingEdgeEnabled) {
14196                initScrollCache();
14197            }
14198
14199            mViewFlags ^= FADING_EDGE_VERTICAL;
14200        }
14201    }
14202
14203    /**
14204     * Returns the strength, or intensity, of the top faded edge. The strength is
14205     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14206     * returns 0.0 or 1.0 but no value in between.
14207     *
14208     * Subclasses should override this method to provide a smoother fade transition
14209     * when scrolling occurs.
14210     *
14211     * @return the intensity of the top fade as a float between 0.0f and 1.0f
14212     */
14213    protected float getTopFadingEdgeStrength() {
14214        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
14215    }
14216
14217    /**
14218     * Returns the strength, or intensity, of the bottom faded edge. The strength is
14219     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14220     * returns 0.0 or 1.0 but no value in between.
14221     *
14222     * Subclasses should override this method to provide a smoother fade transition
14223     * when scrolling occurs.
14224     *
14225     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
14226     */
14227    protected float getBottomFadingEdgeStrength() {
14228        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
14229                computeVerticalScrollRange() ? 1.0f : 0.0f;
14230    }
14231
14232    /**
14233     * Returns the strength, or intensity, of the left faded edge. The strength is
14234     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14235     * returns 0.0 or 1.0 but no value in between.
14236     *
14237     * Subclasses should override this method to provide a smoother fade transition
14238     * when scrolling occurs.
14239     *
14240     * @return the intensity of the left fade as a float between 0.0f and 1.0f
14241     */
14242    protected float getLeftFadingEdgeStrength() {
14243        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
14244    }
14245
14246    /**
14247     * Returns the strength, or intensity, of the right faded edge. The strength is
14248     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
14249     * returns 0.0 or 1.0 but no value in between.
14250     *
14251     * Subclasses should override this method to provide a smoother fade transition
14252     * when scrolling occurs.
14253     *
14254     * @return the intensity of the right fade as a float between 0.0f and 1.0f
14255     */
14256    protected float getRightFadingEdgeStrength() {
14257        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
14258                computeHorizontalScrollRange() ? 1.0f : 0.0f;
14259    }
14260
14261    /**
14262     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
14263     * scrollbar is not drawn by default.</p>
14264     *
14265     * @return true if the horizontal scrollbar should be painted, false
14266     *         otherwise
14267     *
14268     * @see #setHorizontalScrollBarEnabled(boolean)
14269     */
14270    public boolean isHorizontalScrollBarEnabled() {
14271        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
14272    }
14273
14274    /**
14275     * <p>Define whether the horizontal scrollbar should be drawn or not. The
14276     * scrollbar is not drawn by default.</p>
14277     *
14278     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
14279     *                                   be painted
14280     *
14281     * @see #isHorizontalScrollBarEnabled()
14282     */
14283    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
14284        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
14285            mViewFlags ^= SCROLLBARS_HORIZONTAL;
14286            computeOpaqueFlags();
14287            resolvePadding();
14288        }
14289    }
14290
14291    /**
14292     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
14293     * scrollbar is not drawn by default.</p>
14294     *
14295     * @return true if the vertical scrollbar should be painted, false
14296     *         otherwise
14297     *
14298     * @see #setVerticalScrollBarEnabled(boolean)
14299     */
14300    public boolean isVerticalScrollBarEnabled() {
14301        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
14302    }
14303
14304    /**
14305     * <p>Define whether the vertical scrollbar should be drawn or not. The
14306     * scrollbar is not drawn by default.</p>
14307     *
14308     * @param verticalScrollBarEnabled true if the vertical scrollbar should
14309     *                                 be painted
14310     *
14311     * @see #isVerticalScrollBarEnabled()
14312     */
14313    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
14314        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
14315            mViewFlags ^= SCROLLBARS_VERTICAL;
14316            computeOpaqueFlags();
14317            resolvePadding();
14318        }
14319    }
14320
14321    /**
14322     * @hide
14323     */
14324    protected void recomputePadding() {
14325        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
14326    }
14327
14328    /**
14329     * Define whether scrollbars will fade when the view is not scrolling.
14330     *
14331     * @param fadeScrollbars whether to enable fading
14332     *
14333     * @attr ref android.R.styleable#View_fadeScrollbars
14334     */
14335    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
14336        initScrollCache();
14337        final ScrollabilityCache scrollabilityCache = mScrollCache;
14338        scrollabilityCache.fadeScrollBars = fadeScrollbars;
14339        if (fadeScrollbars) {
14340            scrollabilityCache.state = ScrollabilityCache.OFF;
14341        } else {
14342            scrollabilityCache.state = ScrollabilityCache.ON;
14343        }
14344    }
14345
14346    /**
14347     *
14348     * Returns true if scrollbars will fade when this view is not scrolling
14349     *
14350     * @return true if scrollbar fading is enabled
14351     *
14352     * @attr ref android.R.styleable#View_fadeScrollbars
14353     */
14354    public boolean isScrollbarFadingEnabled() {
14355        return mScrollCache != null && mScrollCache.fadeScrollBars;
14356    }
14357
14358    /**
14359     *
14360     * Returns the delay before scrollbars fade.
14361     *
14362     * @return the delay before scrollbars fade
14363     *
14364     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14365     */
14366    public int getScrollBarDefaultDelayBeforeFade() {
14367        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
14368                mScrollCache.scrollBarDefaultDelayBeforeFade;
14369    }
14370
14371    /**
14372     * Define the delay before scrollbars fade.
14373     *
14374     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
14375     *
14376     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
14377     */
14378    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
14379        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
14380    }
14381
14382    /**
14383     *
14384     * Returns the scrollbar fade duration.
14385     *
14386     * @return the scrollbar fade duration
14387     *
14388     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14389     */
14390    public int getScrollBarFadeDuration() {
14391        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
14392                mScrollCache.scrollBarFadeDuration;
14393    }
14394
14395    /**
14396     * Define the scrollbar fade duration.
14397     *
14398     * @param scrollBarFadeDuration - the scrollbar fade duration
14399     *
14400     * @attr ref android.R.styleable#View_scrollbarFadeDuration
14401     */
14402    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
14403        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
14404    }
14405
14406    /**
14407     *
14408     * Returns the scrollbar size.
14409     *
14410     * @return the scrollbar size
14411     *
14412     * @attr ref android.R.styleable#View_scrollbarSize
14413     */
14414    public int getScrollBarSize() {
14415        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
14416                mScrollCache.scrollBarSize;
14417    }
14418
14419    /**
14420     * Define the scrollbar size.
14421     *
14422     * @param scrollBarSize - the scrollbar size
14423     *
14424     * @attr ref android.R.styleable#View_scrollbarSize
14425     */
14426    public void setScrollBarSize(int scrollBarSize) {
14427        getScrollCache().scrollBarSize = scrollBarSize;
14428    }
14429
14430    /**
14431     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
14432     * inset. When inset, they add to the padding of the view. And the scrollbars
14433     * can be drawn inside the padding area or on the edge of the view. For example,
14434     * if a view has a background drawable and you want to draw the scrollbars
14435     * inside the padding specified by the drawable, you can use
14436     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
14437     * appear at the edge of the view, ignoring the padding, then you can use
14438     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
14439     * @param style the style of the scrollbars. Should be one of
14440     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
14441     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
14442     * @see #SCROLLBARS_INSIDE_OVERLAY
14443     * @see #SCROLLBARS_INSIDE_INSET
14444     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14445     * @see #SCROLLBARS_OUTSIDE_INSET
14446     *
14447     * @attr ref android.R.styleable#View_scrollbarStyle
14448     */
14449    public void setScrollBarStyle(@ScrollBarStyle int style) {
14450        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
14451            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
14452            computeOpaqueFlags();
14453            resolvePadding();
14454        }
14455    }
14456
14457    /**
14458     * <p>Returns the current scrollbar style.</p>
14459     * @return the current scrollbar style
14460     * @see #SCROLLBARS_INSIDE_OVERLAY
14461     * @see #SCROLLBARS_INSIDE_INSET
14462     * @see #SCROLLBARS_OUTSIDE_OVERLAY
14463     * @see #SCROLLBARS_OUTSIDE_INSET
14464     *
14465     * @attr ref android.R.styleable#View_scrollbarStyle
14466     */
14467    @ViewDebug.ExportedProperty(mapping = {
14468            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
14469            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
14470            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
14471            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
14472    })
14473    @ScrollBarStyle
14474    public int getScrollBarStyle() {
14475        return mViewFlags & SCROLLBARS_STYLE_MASK;
14476    }
14477
14478    /**
14479     * <p>Compute the horizontal range that the horizontal scrollbar
14480     * represents.</p>
14481     *
14482     * <p>The range is expressed in arbitrary units that must be the same as the
14483     * units used by {@link #computeHorizontalScrollExtent()} and
14484     * {@link #computeHorizontalScrollOffset()}.</p>
14485     *
14486     * <p>The default range is the drawing width of this view.</p>
14487     *
14488     * @return the total horizontal range represented by the horizontal
14489     *         scrollbar
14490     *
14491     * @see #computeHorizontalScrollExtent()
14492     * @see #computeHorizontalScrollOffset()
14493     * @see android.widget.ScrollBarDrawable
14494     */
14495    protected int computeHorizontalScrollRange() {
14496        return getWidth();
14497    }
14498
14499    /**
14500     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
14501     * within the horizontal range. This value is used to compute the position
14502     * of the thumb within the scrollbar's track.</p>
14503     *
14504     * <p>The range is expressed in arbitrary units that must be the same as the
14505     * units used by {@link #computeHorizontalScrollRange()} and
14506     * {@link #computeHorizontalScrollExtent()}.</p>
14507     *
14508     * <p>The default offset is the scroll offset of this view.</p>
14509     *
14510     * @return the horizontal offset of the scrollbar's thumb
14511     *
14512     * @see #computeHorizontalScrollRange()
14513     * @see #computeHorizontalScrollExtent()
14514     * @see android.widget.ScrollBarDrawable
14515     */
14516    protected int computeHorizontalScrollOffset() {
14517        return mScrollX;
14518    }
14519
14520    /**
14521     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
14522     * within the horizontal range. This value is used to compute the length
14523     * of the thumb within the scrollbar's track.</p>
14524     *
14525     * <p>The range is expressed in arbitrary units that must be the same as the
14526     * units used by {@link #computeHorizontalScrollRange()} and
14527     * {@link #computeHorizontalScrollOffset()}.</p>
14528     *
14529     * <p>The default extent is the drawing width of this view.</p>
14530     *
14531     * @return the horizontal extent of the scrollbar's thumb
14532     *
14533     * @see #computeHorizontalScrollRange()
14534     * @see #computeHorizontalScrollOffset()
14535     * @see android.widget.ScrollBarDrawable
14536     */
14537    protected int computeHorizontalScrollExtent() {
14538        return getWidth();
14539    }
14540
14541    /**
14542     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
14543     *
14544     * <p>The range is expressed in arbitrary units that must be the same as the
14545     * units used by {@link #computeVerticalScrollExtent()} and
14546     * {@link #computeVerticalScrollOffset()}.</p>
14547     *
14548     * @return the total vertical range represented by the vertical scrollbar
14549     *
14550     * <p>The default range is the drawing height of this view.</p>
14551     *
14552     * @see #computeVerticalScrollExtent()
14553     * @see #computeVerticalScrollOffset()
14554     * @see android.widget.ScrollBarDrawable
14555     */
14556    protected int computeVerticalScrollRange() {
14557        return getHeight();
14558    }
14559
14560    /**
14561     * <p>Compute the vertical offset of the vertical scrollbar's thumb
14562     * within the horizontal range. This value is used to compute the position
14563     * of the thumb within the scrollbar's track.</p>
14564     *
14565     * <p>The range is expressed in arbitrary units that must be the same as the
14566     * units used by {@link #computeVerticalScrollRange()} and
14567     * {@link #computeVerticalScrollExtent()}.</p>
14568     *
14569     * <p>The default offset is the scroll offset of this view.</p>
14570     *
14571     * @return the vertical offset of the scrollbar's thumb
14572     *
14573     * @see #computeVerticalScrollRange()
14574     * @see #computeVerticalScrollExtent()
14575     * @see android.widget.ScrollBarDrawable
14576     */
14577    protected int computeVerticalScrollOffset() {
14578        return mScrollY;
14579    }
14580
14581    /**
14582     * <p>Compute the vertical extent of the vertical scrollbar's thumb
14583     * within the vertical range. This value is used to compute the length
14584     * of the thumb within the scrollbar's track.</p>
14585     *
14586     * <p>The range is expressed in arbitrary units that must be the same as the
14587     * units used by {@link #computeVerticalScrollRange()} and
14588     * {@link #computeVerticalScrollOffset()}.</p>
14589     *
14590     * <p>The default extent is the drawing height of this view.</p>
14591     *
14592     * @return the vertical extent of the scrollbar's thumb
14593     *
14594     * @see #computeVerticalScrollRange()
14595     * @see #computeVerticalScrollOffset()
14596     * @see android.widget.ScrollBarDrawable
14597     */
14598    protected int computeVerticalScrollExtent() {
14599        return getHeight();
14600    }
14601
14602    /**
14603     * Check if this view can be scrolled horizontally in a certain direction.
14604     *
14605     * @param direction Negative to check scrolling left, positive to check scrolling right.
14606     * @return true if this view can be scrolled in the specified direction, false otherwise.
14607     */
14608    public boolean canScrollHorizontally(int direction) {
14609        final int offset = computeHorizontalScrollOffset();
14610        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
14611        if (range == 0) return false;
14612        if (direction < 0) {
14613            return offset > 0;
14614        } else {
14615            return offset < range - 1;
14616        }
14617    }
14618
14619    /**
14620     * Check if this view can be scrolled vertically in a certain direction.
14621     *
14622     * @param direction Negative to check scrolling up, positive to check scrolling down.
14623     * @return true if this view can be scrolled in the specified direction, false otherwise.
14624     */
14625    public boolean canScrollVertically(int direction) {
14626        final int offset = computeVerticalScrollOffset();
14627        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
14628        if (range == 0) return false;
14629        if (direction < 0) {
14630            return offset > 0;
14631        } else {
14632            return offset < range - 1;
14633        }
14634    }
14635
14636    void getScrollIndicatorBounds(@NonNull Rect out) {
14637        out.left = mScrollX;
14638        out.right = mScrollX + mRight - mLeft;
14639        out.top = mScrollY;
14640        out.bottom = mScrollY + mBottom - mTop;
14641    }
14642
14643    private void onDrawScrollIndicators(Canvas c) {
14644        if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) {
14645            // No scroll indicators enabled.
14646            return;
14647        }
14648
14649        final Drawable dr = mScrollIndicatorDrawable;
14650        if (dr == null) {
14651            // Scroll indicators aren't supported here.
14652            return;
14653        }
14654
14655        final int h = dr.getIntrinsicHeight();
14656        final int w = dr.getIntrinsicWidth();
14657        final Rect rect = mAttachInfo.mTmpInvalRect;
14658        getScrollIndicatorBounds(rect);
14659
14660        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) {
14661            final boolean canScrollUp = canScrollVertically(-1);
14662            if (canScrollUp) {
14663                dr.setBounds(rect.left, rect.top, rect.right, rect.top + h);
14664                dr.draw(c);
14665            }
14666        }
14667
14668        if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) {
14669            final boolean canScrollDown = canScrollVertically(1);
14670            if (canScrollDown) {
14671                dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom);
14672                dr.draw(c);
14673            }
14674        }
14675
14676        final int leftRtl;
14677        final int rightRtl;
14678        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14679            leftRtl = PFLAG3_SCROLL_INDICATOR_END;
14680            rightRtl = PFLAG3_SCROLL_INDICATOR_START;
14681        } else {
14682            leftRtl = PFLAG3_SCROLL_INDICATOR_START;
14683            rightRtl = PFLAG3_SCROLL_INDICATOR_END;
14684        }
14685
14686        final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl;
14687        if ((mPrivateFlags3 & leftMask) != 0) {
14688            final boolean canScrollLeft = canScrollHorizontally(-1);
14689            if (canScrollLeft) {
14690                dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom);
14691                dr.draw(c);
14692            }
14693        }
14694
14695        final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl;
14696        if ((mPrivateFlags3 & rightMask) != 0) {
14697            final boolean canScrollRight = canScrollHorizontally(1);
14698            if (canScrollRight) {
14699                dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom);
14700                dr.draw(c);
14701            }
14702        }
14703    }
14704
14705    private void getHorizontalScrollBarBounds(Rect bounds) {
14706        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14707        final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14708                && !isVerticalScrollBarHidden();
14709        final int size = getHorizontalScrollbarHeight();
14710        final int verticalScrollBarGap = drawVerticalScrollBar ?
14711                getVerticalScrollbarWidth() : 0;
14712        final int width = mRight - mLeft;
14713        final int height = mBottom - mTop;
14714        bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside);
14715        bounds.left = mScrollX + (mPaddingLeft & inside);
14716        bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
14717        bounds.bottom = bounds.top + size;
14718    }
14719
14720    private void getVerticalScrollBarBounds(Rect bounds) {
14721        final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
14722        final int size = getVerticalScrollbarWidth();
14723        int verticalScrollbarPosition = mVerticalScrollbarPosition;
14724        if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
14725            verticalScrollbarPosition = isLayoutRtl() ?
14726                    SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
14727        }
14728        final int width = mRight - mLeft;
14729        final int height = mBottom - mTop;
14730        switch (verticalScrollbarPosition) {
14731            default:
14732            case SCROLLBAR_POSITION_RIGHT:
14733                bounds.left = mScrollX + width - size - (mUserPaddingRight & inside);
14734                break;
14735            case SCROLLBAR_POSITION_LEFT:
14736                bounds.left = mScrollX + (mUserPaddingLeft & inside);
14737                break;
14738        }
14739        bounds.top = mScrollY + (mPaddingTop & inside);
14740        bounds.right = bounds.left + size;
14741        bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside);
14742    }
14743
14744    /**
14745     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
14746     * scrollbars are painted only if they have been awakened first.</p>
14747     *
14748     * @param canvas the canvas on which to draw the scrollbars
14749     *
14750     * @see #awakenScrollBars(int)
14751     */
14752    protected final void onDrawScrollBars(Canvas canvas) {
14753        // scrollbars are drawn only when the animation is running
14754        final ScrollabilityCache cache = mScrollCache;
14755        if (cache != null) {
14756
14757            int state = cache.state;
14758
14759            if (state == ScrollabilityCache.OFF) {
14760                return;
14761            }
14762
14763            boolean invalidate = false;
14764
14765            if (state == ScrollabilityCache.FADING) {
14766                // We're fading -- get our fade interpolation
14767                if (cache.interpolatorValues == null) {
14768                    cache.interpolatorValues = new float[1];
14769                }
14770
14771                float[] values = cache.interpolatorValues;
14772
14773                // Stops the animation if we're done
14774                if (cache.scrollBarInterpolator.timeToValues(values) ==
14775                        Interpolator.Result.FREEZE_END) {
14776                    cache.state = ScrollabilityCache.OFF;
14777                } else {
14778                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
14779                }
14780
14781                // This will make the scroll bars inval themselves after
14782                // drawing. We only want this when we're fading so that
14783                // we prevent excessive redraws
14784                invalidate = true;
14785            } else {
14786                // We're just on -- but we may have been fading before so
14787                // reset alpha
14788                cache.scrollBar.mutate().setAlpha(255);
14789            }
14790
14791            final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled();
14792            final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled()
14793                    && !isVerticalScrollBarHidden();
14794
14795            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
14796                final ScrollBarDrawable scrollBar = cache.scrollBar;
14797
14798                if (drawHorizontalScrollBar) {
14799                    scrollBar.setParameters(computeHorizontalScrollRange(),
14800                                            computeHorizontalScrollOffset(),
14801                                            computeHorizontalScrollExtent(), false);
14802                    final Rect bounds = cache.mScrollBarBounds;
14803                    getHorizontalScrollBarBounds(bounds);
14804                    onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14805                            bounds.right, bounds.bottom);
14806                    if (invalidate) {
14807                        invalidate(bounds);
14808                    }
14809                }
14810
14811                if (drawVerticalScrollBar) {
14812                    scrollBar.setParameters(computeVerticalScrollRange(),
14813                                            computeVerticalScrollOffset(),
14814                                            computeVerticalScrollExtent(), true);
14815                    final Rect bounds = cache.mScrollBarBounds;
14816                    getVerticalScrollBarBounds(bounds);
14817                    onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top,
14818                            bounds.right, bounds.bottom);
14819                    if (invalidate) {
14820                        invalidate(bounds);
14821                    }
14822                }
14823            }
14824        }
14825    }
14826
14827    /**
14828     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
14829     * FastScroller is visible.
14830     * @return whether to temporarily hide the vertical scrollbar
14831     * @hide
14832     */
14833    protected boolean isVerticalScrollBarHidden() {
14834        return false;
14835    }
14836
14837    /**
14838     * <p>Draw the horizontal scrollbar if
14839     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
14840     *
14841     * @param canvas the canvas on which to draw the scrollbar
14842     * @param scrollBar the scrollbar's drawable
14843     *
14844     * @see #isHorizontalScrollBarEnabled()
14845     * @see #computeHorizontalScrollRange()
14846     * @see #computeHorizontalScrollExtent()
14847     * @see #computeHorizontalScrollOffset()
14848     * @see android.widget.ScrollBarDrawable
14849     * @hide
14850     */
14851    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
14852            int l, int t, int r, int b) {
14853        scrollBar.setBounds(l, t, r, b);
14854        scrollBar.draw(canvas);
14855    }
14856
14857    /**
14858     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
14859     * returns true.</p>
14860     *
14861     * @param canvas the canvas on which to draw the scrollbar
14862     * @param scrollBar the scrollbar's drawable
14863     *
14864     * @see #isVerticalScrollBarEnabled()
14865     * @see #computeVerticalScrollRange()
14866     * @see #computeVerticalScrollExtent()
14867     * @see #computeVerticalScrollOffset()
14868     * @see android.widget.ScrollBarDrawable
14869     * @hide
14870     */
14871    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
14872            int l, int t, int r, int b) {
14873        scrollBar.setBounds(l, t, r, b);
14874        scrollBar.draw(canvas);
14875    }
14876
14877    /**
14878     * Implement this to do your drawing.
14879     *
14880     * @param canvas the canvas on which the background will be drawn
14881     */
14882    protected void onDraw(Canvas canvas) {
14883    }
14884
14885    /*
14886     * Caller is responsible for calling requestLayout if necessary.
14887     * (This allows addViewInLayout to not request a new layout.)
14888     */
14889    void assignParent(ViewParent parent) {
14890        if (mParent == null) {
14891            mParent = parent;
14892        } else if (parent == null) {
14893            mParent = null;
14894        } else {
14895            throw new RuntimeException("view " + this + " being added, but"
14896                    + " it already has a parent");
14897        }
14898    }
14899
14900    /**
14901     * This is called when the view is attached to a window.  At this point it
14902     * has a Surface and will start drawing.  Note that this function is
14903     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
14904     * however it may be called any time before the first onDraw -- including
14905     * before or after {@link #onMeasure(int, int)}.
14906     *
14907     * @see #onDetachedFromWindow()
14908     */
14909    @CallSuper
14910    protected void onAttachedToWindow() {
14911        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
14912            mParent.requestTransparentRegion(this);
14913        }
14914
14915        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14916
14917        jumpDrawablesToCurrentState();
14918
14919        resetSubtreeAccessibilityStateChanged();
14920
14921        // rebuild, since Outline not maintained while View is detached
14922        rebuildOutline();
14923
14924        if (isFocused()) {
14925            InputMethodManager imm = InputMethodManager.peekInstance();
14926            if (imm != null) {
14927                imm.focusIn(this);
14928            }
14929        }
14930    }
14931
14932    /**
14933     * Resolve all RTL related properties.
14934     *
14935     * @return true if resolution of RTL properties has been done
14936     *
14937     * @hide
14938     */
14939    public boolean resolveRtlPropertiesIfNeeded() {
14940        if (!needRtlPropertiesResolution()) return false;
14941
14942        // Order is important here: LayoutDirection MUST be resolved first
14943        if (!isLayoutDirectionResolved()) {
14944            resolveLayoutDirection();
14945            resolveLayoutParams();
14946        }
14947        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
14948        if (!isTextDirectionResolved()) {
14949            resolveTextDirection();
14950        }
14951        if (!isTextAlignmentResolved()) {
14952            resolveTextAlignment();
14953        }
14954        // Should resolve Drawables before Padding because we need the layout direction of the
14955        // Drawable to correctly resolve Padding.
14956        if (!areDrawablesResolved()) {
14957            resolveDrawables();
14958        }
14959        if (!isPaddingResolved()) {
14960            resolvePadding();
14961        }
14962        onRtlPropertiesChanged(getLayoutDirection());
14963        return true;
14964    }
14965
14966    /**
14967     * Reset resolution of all RTL related properties.
14968     *
14969     * @hide
14970     */
14971    public void resetRtlProperties() {
14972        resetResolvedLayoutDirection();
14973        resetResolvedTextDirection();
14974        resetResolvedTextAlignment();
14975        resetResolvedPadding();
14976        resetResolvedDrawables();
14977    }
14978
14979    /**
14980     * @see #onScreenStateChanged(int)
14981     */
14982    void dispatchScreenStateChanged(int screenState) {
14983        onScreenStateChanged(screenState);
14984    }
14985
14986    /**
14987     * This method is called whenever the state of the screen this view is
14988     * attached to changes. A state change will usually occurs when the screen
14989     * turns on or off (whether it happens automatically or the user does it
14990     * manually.)
14991     *
14992     * @param screenState The new state of the screen. Can be either
14993     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
14994     */
14995    public void onScreenStateChanged(int screenState) {
14996    }
14997
14998    /**
14999     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
15000     */
15001    private boolean hasRtlSupport() {
15002        return mContext.getApplicationInfo().hasRtlSupport();
15003    }
15004
15005    /**
15006     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
15007     * RTL not supported)
15008     */
15009    private boolean isRtlCompatibilityMode() {
15010        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
15011        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
15012    }
15013
15014    /**
15015     * @return true if RTL properties need resolution.
15016     *
15017     */
15018    private boolean needRtlPropertiesResolution() {
15019        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
15020    }
15021
15022    /**
15023     * Called when any RTL property (layout direction or text direction or text alignment) has
15024     * been changed.
15025     *
15026     * Subclasses need to override this method to take care of cached information that depends on the
15027     * resolved layout direction, or to inform child views that inherit their layout direction.
15028     *
15029     * The default implementation does nothing.
15030     *
15031     * @param layoutDirection the direction of the layout
15032     *
15033     * @see #LAYOUT_DIRECTION_LTR
15034     * @see #LAYOUT_DIRECTION_RTL
15035     */
15036    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
15037    }
15038
15039    /**
15040     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
15041     * that the parent directionality can and will be resolved before its children.
15042     *
15043     * @return true if resolution has been done, false otherwise.
15044     *
15045     * @hide
15046     */
15047    public boolean resolveLayoutDirection() {
15048        // Clear any previous layout direction resolution
15049        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15050
15051        if (hasRtlSupport()) {
15052            // Set resolved depending on layout direction
15053            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
15054                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
15055                case LAYOUT_DIRECTION_INHERIT:
15056                    // We cannot resolve yet. LTR is by default and let the resolution happen again
15057                    // later to get the correct resolved value
15058                    if (!canResolveLayoutDirection()) return false;
15059
15060                    // Parent has not yet resolved, LTR is still the default
15061                    try {
15062                        if (!mParent.isLayoutDirectionResolved()) return false;
15063
15064                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
15065                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15066                        }
15067                    } catch (AbstractMethodError e) {
15068                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15069                                " does not fully implement ViewParent", e);
15070                    }
15071                    break;
15072                case LAYOUT_DIRECTION_RTL:
15073                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15074                    break;
15075                case LAYOUT_DIRECTION_LOCALE:
15076                    if((LAYOUT_DIRECTION_RTL ==
15077                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
15078                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
15079                    }
15080                    break;
15081                default:
15082                    // Nothing to do, LTR by default
15083            }
15084        }
15085
15086        // Set to resolved
15087        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15088        return true;
15089    }
15090
15091    /**
15092     * Check if layout direction resolution can be done.
15093     *
15094     * @return true if layout direction resolution can be done otherwise return false.
15095     */
15096    public boolean canResolveLayoutDirection() {
15097        switch (getRawLayoutDirection()) {
15098            case LAYOUT_DIRECTION_INHERIT:
15099                if (mParent != null) {
15100                    try {
15101                        return mParent.canResolveLayoutDirection();
15102                    } catch (AbstractMethodError e) {
15103                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
15104                                " does not fully implement ViewParent", e);
15105                    }
15106                }
15107                return false;
15108
15109            default:
15110                return true;
15111        }
15112    }
15113
15114    /**
15115     * Reset the resolved layout direction. Layout direction will be resolved during a call to
15116     * {@link #onMeasure(int, int)}.
15117     *
15118     * @hide
15119     */
15120    public void resetResolvedLayoutDirection() {
15121        // Reset the current resolved bits
15122        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
15123    }
15124
15125    /**
15126     * @return true if the layout direction is inherited.
15127     *
15128     * @hide
15129     */
15130    public boolean isLayoutDirectionInherited() {
15131        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
15132    }
15133
15134    /**
15135     * @return true if layout direction has been resolved.
15136     */
15137    public boolean isLayoutDirectionResolved() {
15138        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
15139    }
15140
15141    /**
15142     * Return if padding has been resolved
15143     *
15144     * @hide
15145     */
15146    boolean isPaddingResolved() {
15147        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
15148    }
15149
15150    /**
15151     * Resolves padding depending on layout direction, if applicable, and
15152     * recomputes internal padding values to adjust for scroll bars.
15153     *
15154     * @hide
15155     */
15156    public void resolvePadding() {
15157        final int resolvedLayoutDirection = getLayoutDirection();
15158
15159        if (!isRtlCompatibilityMode()) {
15160            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
15161            // If start / end padding are defined, they will be resolved (hence overriding) to
15162            // left / right or right / left depending on the resolved layout direction.
15163            // If start / end padding are not defined, use the left / right ones.
15164            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
15165                Rect padding = sThreadLocal.get();
15166                if (padding == null) {
15167                    padding = new Rect();
15168                    sThreadLocal.set(padding);
15169                }
15170                mBackground.getPadding(padding);
15171                if (!mLeftPaddingDefined) {
15172                    mUserPaddingLeftInitial = padding.left;
15173                }
15174                if (!mRightPaddingDefined) {
15175                    mUserPaddingRightInitial = padding.right;
15176                }
15177            }
15178            switch (resolvedLayoutDirection) {
15179                case LAYOUT_DIRECTION_RTL:
15180                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15181                        mUserPaddingRight = mUserPaddingStart;
15182                    } else {
15183                        mUserPaddingRight = mUserPaddingRightInitial;
15184                    }
15185                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15186                        mUserPaddingLeft = mUserPaddingEnd;
15187                    } else {
15188                        mUserPaddingLeft = mUserPaddingLeftInitial;
15189                    }
15190                    break;
15191                case LAYOUT_DIRECTION_LTR:
15192                default:
15193                    if (mUserPaddingStart != UNDEFINED_PADDING) {
15194                        mUserPaddingLeft = mUserPaddingStart;
15195                    } else {
15196                        mUserPaddingLeft = mUserPaddingLeftInitial;
15197                    }
15198                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
15199                        mUserPaddingRight = mUserPaddingEnd;
15200                    } else {
15201                        mUserPaddingRight = mUserPaddingRightInitial;
15202                    }
15203            }
15204
15205            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
15206        }
15207
15208        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
15209        onRtlPropertiesChanged(resolvedLayoutDirection);
15210
15211        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
15212    }
15213
15214    /**
15215     * Reset the resolved layout direction.
15216     *
15217     * @hide
15218     */
15219    public void resetResolvedPadding() {
15220        resetResolvedPaddingInternal();
15221    }
15222
15223    /**
15224     * Used when we only want to reset *this* view's padding and not trigger overrides
15225     * in ViewGroup that reset children too.
15226     */
15227    void resetResolvedPaddingInternal() {
15228        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
15229    }
15230
15231    /**
15232     * This is called when the view is detached from a window.  At this point it
15233     * no longer has a surface for drawing.
15234     *
15235     * @see #onAttachedToWindow()
15236     */
15237    @CallSuper
15238    protected void onDetachedFromWindow() {
15239    }
15240
15241    /**
15242     * This is a framework-internal mirror of onDetachedFromWindow() that's called
15243     * after onDetachedFromWindow().
15244     *
15245     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
15246     * The super method should be called at the end of the overridden method to ensure
15247     * subclasses are destroyed first
15248     *
15249     * @hide
15250     */
15251    @CallSuper
15252    protected void onDetachedFromWindowInternal() {
15253        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
15254        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
15255        mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH;
15256
15257        removeUnsetPressCallback();
15258        removeLongPressCallback();
15259        removePerformClickCallback();
15260        removeSendViewScrolledAccessibilityEventCallback();
15261        stopNestedScroll();
15262
15263        // Anything that started animating right before detach should already
15264        // be in its final state when re-attached.
15265        jumpDrawablesToCurrentState();
15266
15267        destroyDrawingCache();
15268
15269        cleanupDraw();
15270        mCurrentAnimation = null;
15271    }
15272
15273    private void cleanupDraw() {
15274        resetDisplayList();
15275        if (mAttachInfo != null) {
15276            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
15277        }
15278    }
15279
15280    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
15281    }
15282
15283    /**
15284     * @return The number of times this view has been attached to a window
15285     */
15286    protected int getWindowAttachCount() {
15287        return mWindowAttachCount;
15288    }
15289
15290    /**
15291     * Retrieve a unique token identifying the window this view is attached to.
15292     * @return Return the window's token for use in
15293     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
15294     */
15295    public IBinder getWindowToken() {
15296        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
15297    }
15298
15299    /**
15300     * Retrieve the {@link WindowId} for the window this view is
15301     * currently attached to.
15302     */
15303    public WindowId getWindowId() {
15304        if (mAttachInfo == null) {
15305            return null;
15306        }
15307        if (mAttachInfo.mWindowId == null) {
15308            try {
15309                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
15310                        mAttachInfo.mWindowToken);
15311                mAttachInfo.mWindowId = new WindowId(
15312                        mAttachInfo.mIWindowId);
15313            } catch (RemoteException e) {
15314            }
15315        }
15316        return mAttachInfo.mWindowId;
15317    }
15318
15319    /**
15320     * Retrieve a unique token identifying the top-level "real" window of
15321     * the window that this view is attached to.  That is, this is like
15322     * {@link #getWindowToken}, except if the window this view in is a panel
15323     * window (attached to another containing window), then the token of
15324     * the containing window is returned instead.
15325     *
15326     * @return Returns the associated window token, either
15327     * {@link #getWindowToken()} or the containing window's token.
15328     */
15329    public IBinder getApplicationWindowToken() {
15330        AttachInfo ai = mAttachInfo;
15331        if (ai != null) {
15332            IBinder appWindowToken = ai.mPanelParentWindowToken;
15333            if (appWindowToken == null) {
15334                appWindowToken = ai.mWindowToken;
15335            }
15336            return appWindowToken;
15337        }
15338        return null;
15339    }
15340
15341    /**
15342     * Gets the logical display to which the view's window has been attached.
15343     *
15344     * @return The logical display, or null if the view is not currently attached to a window.
15345     */
15346    public Display getDisplay() {
15347        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
15348    }
15349
15350    /**
15351     * Retrieve private session object this view hierarchy is using to
15352     * communicate with the window manager.
15353     * @return the session object to communicate with the window manager
15354     */
15355    /*package*/ IWindowSession getWindowSession() {
15356        return mAttachInfo != null ? mAttachInfo.mSession : null;
15357    }
15358
15359    /**
15360     * Return the visibility value of the least visible component passed.
15361     */
15362    int combineVisibility(int vis1, int vis2) {
15363        // This works because VISIBLE < INVISIBLE < GONE.
15364        return Math.max(vis1, vis2);
15365    }
15366
15367    /**
15368     * @param info the {@link android.view.View.AttachInfo} to associated with
15369     *        this view
15370     */
15371    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
15372        mAttachInfo = info;
15373        if (mOverlay != null) {
15374            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
15375        }
15376        mWindowAttachCount++;
15377        // We will need to evaluate the drawable state at least once.
15378        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15379        if (mFloatingTreeObserver != null) {
15380            info.mTreeObserver.merge(mFloatingTreeObserver);
15381            mFloatingTreeObserver = null;
15382        }
15383
15384        registerPendingFrameMetricsObservers();
15385
15386        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
15387            mAttachInfo.mScrollContainers.add(this);
15388            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
15389        }
15390        // Transfer all pending runnables.
15391        if (mRunQueue != null) {
15392            mRunQueue.executeActions(info.mHandler);
15393            mRunQueue = null;
15394        }
15395        performCollectViewAttributes(mAttachInfo, visibility);
15396        onAttachedToWindow();
15397
15398        ListenerInfo li = mListenerInfo;
15399        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15400                li != null ? li.mOnAttachStateChangeListeners : null;
15401        if (listeners != null && listeners.size() > 0) {
15402            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15403            // perform the dispatching. The iterator is a safe guard against listeners that
15404            // could mutate the list by calling the various add/remove methods. This prevents
15405            // the array from being modified while we iterate it.
15406            for (OnAttachStateChangeListener listener : listeners) {
15407                listener.onViewAttachedToWindow(this);
15408            }
15409        }
15410
15411        int vis = info.mWindowVisibility;
15412        if (vis != GONE) {
15413            onWindowVisibilityChanged(vis);
15414            if (isShown()) {
15415                // Calling onVisibilityChanged directly here since the subtree will also
15416                // receive dispatchAttachedToWindow and this same call
15417                onVisibilityAggregated(vis == VISIBLE);
15418            }
15419        }
15420
15421        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
15422        // As all views in the subtree will already receive dispatchAttachedToWindow
15423        // traversing the subtree again here is not desired.
15424        onVisibilityChanged(this, visibility);
15425
15426        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
15427            // If nobody has evaluated the drawable state yet, then do it now.
15428            refreshDrawableState();
15429        }
15430        needGlobalAttributesUpdate(false);
15431    }
15432
15433    void dispatchDetachedFromWindow() {
15434        AttachInfo info = mAttachInfo;
15435        if (info != null) {
15436            int vis = info.mWindowVisibility;
15437            if (vis != GONE) {
15438                onWindowVisibilityChanged(GONE);
15439                if (isShown()) {
15440                    // Invoking onVisibilityAggregated directly here since the subtree
15441                    // will also receive detached from window
15442                    onVisibilityAggregated(false);
15443                }
15444            }
15445        }
15446
15447        onDetachedFromWindow();
15448        onDetachedFromWindowInternal();
15449
15450        InputMethodManager imm = InputMethodManager.peekInstance();
15451        if (imm != null) {
15452            imm.onViewDetachedFromWindow(this);
15453        }
15454
15455        ListenerInfo li = mListenerInfo;
15456        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
15457                li != null ? li.mOnAttachStateChangeListeners : null;
15458        if (listeners != null && listeners.size() > 0) {
15459            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
15460            // perform the dispatching. The iterator is a safe guard against listeners that
15461            // could mutate the list by calling the various add/remove methods. This prevents
15462            // the array from being modified while we iterate it.
15463            for (OnAttachStateChangeListener listener : listeners) {
15464                listener.onViewDetachedFromWindow(this);
15465            }
15466        }
15467
15468        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
15469            mAttachInfo.mScrollContainers.remove(this);
15470            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
15471        }
15472
15473        mAttachInfo = null;
15474        if (mOverlay != null) {
15475            mOverlay.getOverlayView().dispatchDetachedFromWindow();
15476        }
15477    }
15478
15479    /**
15480     * Cancel any deferred high-level input events that were previously posted to the event queue.
15481     *
15482     * <p>Many views post high-level events such as click handlers to the event queue
15483     * to run deferred in order to preserve a desired user experience - clearing visible
15484     * pressed states before executing, etc. This method will abort any events of this nature
15485     * that are currently in flight.</p>
15486     *
15487     * <p>Custom views that generate their own high-level deferred input events should override
15488     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
15489     *
15490     * <p>This will also cancel pending input events for any child views.</p>
15491     *
15492     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
15493     * This will not impact newer events posted after this call that may occur as a result of
15494     * lower-level input events still waiting in the queue. If you are trying to prevent
15495     * double-submitted  events for the duration of some sort of asynchronous transaction
15496     * you should also take other steps to protect against unexpected double inputs e.g. calling
15497     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
15498     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
15499     */
15500    public final void cancelPendingInputEvents() {
15501        dispatchCancelPendingInputEvents();
15502    }
15503
15504    /**
15505     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
15506     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
15507     */
15508    void dispatchCancelPendingInputEvents() {
15509        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
15510        onCancelPendingInputEvents();
15511        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
15512            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
15513                    " did not call through to super.onCancelPendingInputEvents()");
15514        }
15515    }
15516
15517    /**
15518     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
15519     * a parent view.
15520     *
15521     * <p>This method is responsible for removing any pending high-level input events that were
15522     * posted to the event queue to run later. Custom view classes that post their own deferred
15523     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
15524     * {@link android.os.Handler} should override this method, call
15525     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
15526     * </p>
15527     */
15528    public void onCancelPendingInputEvents() {
15529        removePerformClickCallback();
15530        cancelLongPress();
15531        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
15532    }
15533
15534    /**
15535     * Store this view hierarchy's frozen state into the given container.
15536     *
15537     * @param container The SparseArray in which to save the view's state.
15538     *
15539     * @see #restoreHierarchyState(android.util.SparseArray)
15540     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15541     * @see #onSaveInstanceState()
15542     */
15543    public void saveHierarchyState(SparseArray<Parcelable> container) {
15544        dispatchSaveInstanceState(container);
15545    }
15546
15547    /**
15548     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
15549     * this view and its children. May be overridden to modify how freezing happens to a
15550     * view's children; for example, some views may want to not store state for their children.
15551     *
15552     * @param container The SparseArray in which to save the view's state.
15553     *
15554     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15555     * @see #saveHierarchyState(android.util.SparseArray)
15556     * @see #onSaveInstanceState()
15557     */
15558    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
15559        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
15560            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15561            Parcelable state = onSaveInstanceState();
15562            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15563                throw new IllegalStateException(
15564                        "Derived class did not call super.onSaveInstanceState()");
15565            }
15566            if (state != null) {
15567                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
15568                // + ": " + state);
15569                container.put(mID, state);
15570            }
15571        }
15572    }
15573
15574    /**
15575     * Hook allowing a view to generate a representation of its internal state
15576     * that can later be used to create a new instance with that same state.
15577     * This state should only contain information that is not persistent or can
15578     * not be reconstructed later. For example, you will never store your
15579     * current position on screen because that will be computed again when a
15580     * new instance of the view is placed in its view hierarchy.
15581     * <p>
15582     * Some examples of things you may store here: the current cursor position
15583     * in a text view (but usually not the text itself since that is stored in a
15584     * content provider or other persistent storage), the currently selected
15585     * item in a list view.
15586     *
15587     * @return Returns a Parcelable object containing the view's current dynamic
15588     *         state, or null if there is nothing interesting to save. The
15589     *         default implementation returns null.
15590     * @see #onRestoreInstanceState(android.os.Parcelable)
15591     * @see #saveHierarchyState(android.util.SparseArray)
15592     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15593     * @see #setSaveEnabled(boolean)
15594     */
15595    @CallSuper
15596    protected Parcelable onSaveInstanceState() {
15597        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15598        if (mStartActivityRequestWho != null) {
15599            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
15600            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
15601            return state;
15602        }
15603        return BaseSavedState.EMPTY_STATE;
15604    }
15605
15606    /**
15607     * Restore this view hierarchy's frozen state from the given container.
15608     *
15609     * @param container The SparseArray which holds previously frozen states.
15610     *
15611     * @see #saveHierarchyState(android.util.SparseArray)
15612     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15613     * @see #onRestoreInstanceState(android.os.Parcelable)
15614     */
15615    public void restoreHierarchyState(SparseArray<Parcelable> container) {
15616        dispatchRestoreInstanceState(container);
15617    }
15618
15619    /**
15620     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
15621     * state for this view and its children. May be overridden to modify how restoring
15622     * happens to a view's children; for example, some views may want to not store state
15623     * for their children.
15624     *
15625     * @param container The SparseArray which holds previously saved state.
15626     *
15627     * @see #dispatchSaveInstanceState(android.util.SparseArray)
15628     * @see #restoreHierarchyState(android.util.SparseArray)
15629     * @see #onRestoreInstanceState(android.os.Parcelable)
15630     */
15631    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
15632        if (mID != NO_ID) {
15633            Parcelable state = container.get(mID);
15634            if (state != null) {
15635                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
15636                // + ": " + state);
15637                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
15638                onRestoreInstanceState(state);
15639                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
15640                    throw new IllegalStateException(
15641                            "Derived class did not call super.onRestoreInstanceState()");
15642                }
15643            }
15644        }
15645    }
15646
15647    /**
15648     * Hook allowing a view to re-apply a representation of its internal state that had previously
15649     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
15650     * null state.
15651     *
15652     * @param state The frozen state that had previously been returned by
15653     *        {@link #onSaveInstanceState}.
15654     *
15655     * @see #onSaveInstanceState()
15656     * @see #restoreHierarchyState(android.util.SparseArray)
15657     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
15658     */
15659    @CallSuper
15660    protected void onRestoreInstanceState(Parcelable state) {
15661        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
15662        if (state != null && !(state instanceof AbsSavedState)) {
15663            throw new IllegalArgumentException("Wrong state class, expecting View State but "
15664                    + "received " + state.getClass().toString() + " instead. This usually happens "
15665                    + "when two views of different type have the same id in the same hierarchy. "
15666                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
15667                    + "other views do not use the same id.");
15668        }
15669        if (state != null && state instanceof BaseSavedState) {
15670            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
15671        }
15672    }
15673
15674    /**
15675     * <p>Return the time at which the drawing of the view hierarchy started.</p>
15676     *
15677     * @return the drawing start time in milliseconds
15678     */
15679    public long getDrawingTime() {
15680        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
15681    }
15682
15683    /**
15684     * <p>Enables or disables the duplication of the parent's state into this view. When
15685     * duplication is enabled, this view gets its drawable state from its parent rather
15686     * than from its own internal properties.</p>
15687     *
15688     * <p>Note: in the current implementation, setting this property to true after the
15689     * view was added to a ViewGroup might have no effect at all. This property should
15690     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
15691     *
15692     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
15693     * property is enabled, an exception will be thrown.</p>
15694     *
15695     * <p>Note: if the child view uses and updates additional states which are unknown to the
15696     * parent, these states should not be affected by this method.</p>
15697     *
15698     * @param enabled True to enable duplication of the parent's drawable state, false
15699     *                to disable it.
15700     *
15701     * @see #getDrawableState()
15702     * @see #isDuplicateParentStateEnabled()
15703     */
15704    public void setDuplicateParentStateEnabled(boolean enabled) {
15705        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
15706    }
15707
15708    /**
15709     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
15710     *
15711     * @return True if this view's drawable state is duplicated from the parent,
15712     *         false otherwise
15713     *
15714     * @see #getDrawableState()
15715     * @see #setDuplicateParentStateEnabled(boolean)
15716     */
15717    public boolean isDuplicateParentStateEnabled() {
15718        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
15719    }
15720
15721    /**
15722     * <p>Specifies the type of layer backing this view. The layer can be
15723     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15724     * {@link #LAYER_TYPE_HARDWARE}.</p>
15725     *
15726     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15727     * instance that controls how the layer is composed on screen. The following
15728     * properties of the paint are taken into account when composing the layer:</p>
15729     * <ul>
15730     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15731     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15732     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15733     * </ul>
15734     *
15735     * <p>If this view has an alpha value set to < 1.0 by calling
15736     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
15737     * by this view's alpha value.</p>
15738     *
15739     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
15740     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
15741     * for more information on when and how to use layers.</p>
15742     *
15743     * @param layerType The type of layer to use with this view, must be one of
15744     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15745     *        {@link #LAYER_TYPE_HARDWARE}
15746     * @param paint The paint used to compose the layer. This argument is optional
15747     *        and can be null. It is ignored when the layer type is
15748     *        {@link #LAYER_TYPE_NONE}
15749     *
15750     * @see #getLayerType()
15751     * @see #LAYER_TYPE_NONE
15752     * @see #LAYER_TYPE_SOFTWARE
15753     * @see #LAYER_TYPE_HARDWARE
15754     * @see #setAlpha(float)
15755     *
15756     * @attr ref android.R.styleable#View_layerType
15757     */
15758    public void setLayerType(int layerType, @Nullable Paint paint) {
15759        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
15760            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
15761                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
15762        }
15763
15764        boolean typeChanged = mRenderNode.setLayerType(layerType);
15765
15766        if (!typeChanged) {
15767            setLayerPaint(paint);
15768            return;
15769        }
15770
15771        if (layerType != LAYER_TYPE_SOFTWARE) {
15772            // Destroy any previous software drawing cache if present
15773            // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up
15774            // drawing cache created in View#draw when drawing to a SW canvas.
15775            destroyDrawingCache();
15776        }
15777
15778        mLayerType = layerType;
15779        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
15780        mRenderNode.setLayerPaint(mLayerPaint);
15781
15782        // draw() behaves differently if we are on a layer, so we need to
15783        // invalidate() here
15784        invalidateParentCaches();
15785        invalidate(true);
15786    }
15787
15788    /**
15789     * Updates the {@link Paint} object used with the current layer (used only if the current
15790     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
15791     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
15792     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
15793     * ensure that the view gets redrawn immediately.
15794     *
15795     * <p>A layer is associated with an optional {@link android.graphics.Paint}
15796     * instance that controls how the layer is composed on screen. The following
15797     * properties of the paint are taken into account when composing the layer:</p>
15798     * <ul>
15799     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
15800     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
15801     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
15802     * </ul>
15803     *
15804     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
15805     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
15806     *
15807     * @param paint The paint used to compose the layer. This argument is optional
15808     *        and can be null. It is ignored when the layer type is
15809     *        {@link #LAYER_TYPE_NONE}
15810     *
15811     * @see #setLayerType(int, android.graphics.Paint)
15812     */
15813    public void setLayerPaint(@Nullable Paint paint) {
15814        int layerType = getLayerType();
15815        if (layerType != LAYER_TYPE_NONE) {
15816            mLayerPaint = paint;
15817            if (layerType == LAYER_TYPE_HARDWARE) {
15818                if (mRenderNode.setLayerPaint(paint)) {
15819                    invalidateViewProperty(false, false);
15820                }
15821            } else {
15822                invalidate();
15823            }
15824        }
15825    }
15826
15827    /**
15828     * Indicates what type of layer is currently associated with this view. By default
15829     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
15830     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
15831     * for more information on the different types of layers.
15832     *
15833     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
15834     *         {@link #LAYER_TYPE_HARDWARE}
15835     *
15836     * @see #setLayerType(int, android.graphics.Paint)
15837     * @see #buildLayer()
15838     * @see #LAYER_TYPE_NONE
15839     * @see #LAYER_TYPE_SOFTWARE
15840     * @see #LAYER_TYPE_HARDWARE
15841     */
15842    public int getLayerType() {
15843        return mLayerType;
15844    }
15845
15846    /**
15847     * Forces this view's layer to be created and this view to be rendered
15848     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
15849     * invoking this method will have no effect.
15850     *
15851     * This method can for instance be used to render a view into its layer before
15852     * starting an animation. If this view is complex, rendering into the layer
15853     * before starting the animation will avoid skipping frames.
15854     *
15855     * @throws IllegalStateException If this view is not attached to a window
15856     *
15857     * @see #setLayerType(int, android.graphics.Paint)
15858     */
15859    public void buildLayer() {
15860        if (mLayerType == LAYER_TYPE_NONE) return;
15861
15862        final AttachInfo attachInfo = mAttachInfo;
15863        if (attachInfo == null) {
15864            throw new IllegalStateException("This view must be attached to a window first");
15865        }
15866
15867        if (getWidth() == 0 || getHeight() == 0) {
15868            return;
15869        }
15870
15871        switch (mLayerType) {
15872            case LAYER_TYPE_HARDWARE:
15873                updateDisplayListIfDirty();
15874                if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) {
15875                    attachInfo.mThreadedRenderer.buildLayer(mRenderNode);
15876                }
15877                break;
15878            case LAYER_TYPE_SOFTWARE:
15879                buildDrawingCache(true);
15880                break;
15881        }
15882    }
15883
15884    /**
15885     * Destroys all hardware rendering resources. This method is invoked
15886     * when the system needs to reclaim resources. Upon execution of this
15887     * method, you should free any OpenGL resources created by the view.
15888     *
15889     * Note: you <strong>must</strong> call
15890     * <code>super.destroyHardwareResources()</code> when overriding
15891     * this method.
15892     *
15893     * @hide
15894     */
15895    @CallSuper
15896    protected void destroyHardwareResources() {
15897        // Although the Layer will be destroyed by RenderNode, we want to release
15898        // the staging display list, which is also a signal to RenderNode that it's
15899        // safe to free its copy of the display list as it knows that we will
15900        // push an updated DisplayList if we try to draw again
15901        resetDisplayList();
15902    }
15903
15904    /**
15905     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
15906     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
15907     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
15908     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
15909     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
15910     * null.</p>
15911     *
15912     * <p>Enabling the drawing cache is similar to
15913     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
15914     * acceleration is turned off. When hardware acceleration is turned on, enabling the
15915     * drawing cache has no effect on rendering because the system uses a different mechanism
15916     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
15917     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
15918     * for information on how to enable software and hardware layers.</p>
15919     *
15920     * <p>This API can be used to manually generate
15921     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
15922     * {@link #getDrawingCache()}.</p>
15923     *
15924     * @param enabled true to enable the drawing cache, false otherwise
15925     *
15926     * @see #isDrawingCacheEnabled()
15927     * @see #getDrawingCache()
15928     * @see #buildDrawingCache()
15929     * @see #setLayerType(int, android.graphics.Paint)
15930     */
15931    public void setDrawingCacheEnabled(boolean enabled) {
15932        mCachingFailed = false;
15933        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
15934    }
15935
15936    /**
15937     * <p>Indicates whether the drawing cache is enabled for this view.</p>
15938     *
15939     * @return true if the drawing cache is enabled
15940     *
15941     * @see #setDrawingCacheEnabled(boolean)
15942     * @see #getDrawingCache()
15943     */
15944    @ViewDebug.ExportedProperty(category = "drawing")
15945    public boolean isDrawingCacheEnabled() {
15946        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
15947    }
15948
15949    /**
15950     * Debugging utility which recursively outputs the dirty state of a view and its
15951     * descendants.
15952     *
15953     * @hide
15954     */
15955    @SuppressWarnings({"UnusedDeclaration"})
15956    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
15957        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
15958                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
15959                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
15960                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
15961        if (clear) {
15962            mPrivateFlags &= clearMask;
15963        }
15964        if (this instanceof ViewGroup) {
15965            ViewGroup parent = (ViewGroup) this;
15966            final int count = parent.getChildCount();
15967            for (int i = 0; i < count; i++) {
15968                final View child = parent.getChildAt(i);
15969                child.outputDirtyFlags(indent + "  ", clear, clearMask);
15970            }
15971        }
15972    }
15973
15974    /**
15975     * This method is used by ViewGroup to cause its children to restore or recreate their
15976     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
15977     * to recreate its own display list, which would happen if it went through the normal
15978     * draw/dispatchDraw mechanisms.
15979     *
15980     * @hide
15981     */
15982    protected void dispatchGetDisplayList() {}
15983
15984    /**
15985     * A view that is not attached or hardware accelerated cannot create a display list.
15986     * This method checks these conditions and returns the appropriate result.
15987     *
15988     * @return true if view has the ability to create a display list, false otherwise.
15989     *
15990     * @hide
15991     */
15992    public boolean canHaveDisplayList() {
15993        return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null);
15994    }
15995
15996    /**
15997     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
15998     * @hide
15999     */
16000    @NonNull
16001    public RenderNode updateDisplayListIfDirty() {
16002        final RenderNode renderNode = mRenderNode;
16003        if (!canHaveDisplayList()) {
16004            // can't populate RenderNode, don't try
16005            return renderNode;
16006        }
16007
16008        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
16009                || !renderNode.isValid()
16010                || (mRecreateDisplayList)) {
16011            // Don't need to recreate the display list, just need to tell our
16012            // children to restore/recreate theirs
16013            if (renderNode.isValid()
16014                    && !mRecreateDisplayList) {
16015                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16016                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16017                dispatchGetDisplayList();
16018
16019                return renderNode; // no work needed
16020            }
16021
16022            // If we got here, we're recreating it. Mark it as such to ensure that
16023            // we copy in child display lists into ours in drawChild()
16024            mRecreateDisplayList = true;
16025
16026            int width = mRight - mLeft;
16027            int height = mBottom - mTop;
16028            int layerType = getLayerType();
16029
16030            final DisplayListCanvas canvas = renderNode.start(width, height);
16031            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
16032
16033            try {
16034                if (layerType == LAYER_TYPE_SOFTWARE) {
16035                    buildDrawingCache(true);
16036                    Bitmap cache = getDrawingCache(true);
16037                    if (cache != null) {
16038                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
16039                    }
16040                } else {
16041                    computeScroll();
16042
16043                    canvas.translate(-mScrollX, -mScrollY);
16044                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16045                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16046
16047                    // Fast path for layouts with no backgrounds
16048                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16049                        dispatchDraw(canvas);
16050                        if (mOverlay != null && !mOverlay.isEmpty()) {
16051                            mOverlay.getOverlayView().draw(canvas);
16052                        }
16053                    } else {
16054                        draw(canvas);
16055                    }
16056                }
16057            } finally {
16058                renderNode.end(canvas);
16059                setDisplayListProperties(renderNode);
16060            }
16061        } else {
16062            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
16063            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16064        }
16065        return renderNode;
16066    }
16067
16068    private void resetDisplayList() {
16069        if (mRenderNode.isValid()) {
16070            mRenderNode.discardDisplayList();
16071        }
16072
16073        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
16074            mBackgroundRenderNode.discardDisplayList();
16075        }
16076    }
16077
16078    /**
16079     * Called when the passed RenderNode is removed from the draw tree
16080     * @hide
16081     */
16082    public void onRenderNodeDetached(RenderNode renderNode) {
16083    }
16084
16085    /**
16086     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
16087     *
16088     * @return A non-scaled bitmap representing this view or null if cache is disabled.
16089     *
16090     * @see #getDrawingCache(boolean)
16091     */
16092    public Bitmap getDrawingCache() {
16093        return getDrawingCache(false);
16094    }
16095
16096    /**
16097     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
16098     * is null when caching is disabled. If caching is enabled and the cache is not ready,
16099     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
16100     * draw from the cache when the cache is enabled. To benefit from the cache, you must
16101     * request the drawing cache by calling this method and draw it on screen if the
16102     * returned bitmap is not null.</p>
16103     *
16104     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16105     * this method will create a bitmap of the same size as this view. Because this bitmap
16106     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16107     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16108     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16109     * size than the view. This implies that your application must be able to handle this
16110     * size.</p>
16111     *
16112     * @param autoScale Indicates whether the generated bitmap should be scaled based on
16113     *        the current density of the screen when the application is in compatibility
16114     *        mode.
16115     *
16116     * @return A bitmap representing this view or null if cache is disabled.
16117     *
16118     * @see #setDrawingCacheEnabled(boolean)
16119     * @see #isDrawingCacheEnabled()
16120     * @see #buildDrawingCache(boolean)
16121     * @see #destroyDrawingCache()
16122     */
16123    public Bitmap getDrawingCache(boolean autoScale) {
16124        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
16125            return null;
16126        }
16127        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
16128            buildDrawingCache(autoScale);
16129        }
16130        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
16131    }
16132
16133    /**
16134     * <p>Frees the resources used by the drawing cache. If you call
16135     * {@link #buildDrawingCache()} manually without calling
16136     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16137     * should cleanup the cache with this method afterwards.</p>
16138     *
16139     * @see #setDrawingCacheEnabled(boolean)
16140     * @see #buildDrawingCache()
16141     * @see #getDrawingCache()
16142     */
16143    public void destroyDrawingCache() {
16144        if (mDrawingCache != null) {
16145            mDrawingCache.recycle();
16146            mDrawingCache = null;
16147        }
16148        if (mUnscaledDrawingCache != null) {
16149            mUnscaledDrawingCache.recycle();
16150            mUnscaledDrawingCache = null;
16151        }
16152    }
16153
16154    /**
16155     * Setting a solid background color for the drawing cache's bitmaps will improve
16156     * performance and memory usage. Note, though that this should only be used if this
16157     * view will always be drawn on top of a solid color.
16158     *
16159     * @param color The background color to use for the drawing cache's bitmap
16160     *
16161     * @see #setDrawingCacheEnabled(boolean)
16162     * @see #buildDrawingCache()
16163     * @see #getDrawingCache()
16164     */
16165    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
16166        if (color != mDrawingCacheBackgroundColor) {
16167            mDrawingCacheBackgroundColor = color;
16168            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
16169        }
16170    }
16171
16172    /**
16173     * @see #setDrawingCacheBackgroundColor(int)
16174     *
16175     * @return The background color to used for the drawing cache's bitmap
16176     */
16177    @ColorInt
16178    public int getDrawingCacheBackgroundColor() {
16179        return mDrawingCacheBackgroundColor;
16180    }
16181
16182    /**
16183     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
16184     *
16185     * @see #buildDrawingCache(boolean)
16186     */
16187    public void buildDrawingCache() {
16188        buildDrawingCache(false);
16189    }
16190
16191    /**
16192     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
16193     *
16194     * <p>If you call {@link #buildDrawingCache()} manually without calling
16195     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
16196     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
16197     *
16198     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
16199     * this method will create a bitmap of the same size as this view. Because this bitmap
16200     * will be drawn scaled by the parent ViewGroup, the result on screen might show
16201     * scaling artifacts. To avoid such artifacts, you should call this method by setting
16202     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
16203     * size than the view. This implies that your application must be able to handle this
16204     * size.</p>
16205     *
16206     * <p>You should avoid calling this method when hardware acceleration is enabled. If
16207     * you do not need the drawing cache bitmap, calling this method will increase memory
16208     * usage and cause the view to be rendered in software once, thus negatively impacting
16209     * performance.</p>
16210     *
16211     * @see #getDrawingCache()
16212     * @see #destroyDrawingCache()
16213     */
16214    public void buildDrawingCache(boolean autoScale) {
16215        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
16216                mDrawingCache == null : mUnscaledDrawingCache == null)) {
16217            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
16218                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
16219                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
16220            }
16221            try {
16222                buildDrawingCacheImpl(autoScale);
16223            } finally {
16224                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
16225            }
16226        }
16227    }
16228
16229    /**
16230     * private, internal implementation of buildDrawingCache, used to enable tracing
16231     */
16232    private void buildDrawingCacheImpl(boolean autoScale) {
16233        mCachingFailed = false;
16234
16235        int width = mRight - mLeft;
16236        int height = mBottom - mTop;
16237
16238        final AttachInfo attachInfo = mAttachInfo;
16239        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
16240
16241        if (autoScale && scalingRequired) {
16242            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
16243            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
16244        }
16245
16246        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
16247        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
16248        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
16249
16250        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
16251        final long drawingCacheSize =
16252                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
16253        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
16254            if (width > 0 && height > 0) {
16255                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
16256                        + " too large to fit into a software layer (or drawing cache), needs "
16257                        + projectedBitmapSize + " bytes, only "
16258                        + drawingCacheSize + " available");
16259            }
16260            destroyDrawingCache();
16261            mCachingFailed = true;
16262            return;
16263        }
16264
16265        boolean clear = true;
16266        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
16267
16268        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
16269            Bitmap.Config quality;
16270            if (!opaque) {
16271                // Never pick ARGB_4444 because it looks awful
16272                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
16273                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
16274                    case DRAWING_CACHE_QUALITY_AUTO:
16275                    case DRAWING_CACHE_QUALITY_LOW:
16276                    case DRAWING_CACHE_QUALITY_HIGH:
16277                    default:
16278                        quality = Bitmap.Config.ARGB_8888;
16279                        break;
16280                }
16281            } else {
16282                // Optimization for translucent windows
16283                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
16284                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
16285            }
16286
16287            // Try to cleanup memory
16288            if (bitmap != null) bitmap.recycle();
16289
16290            try {
16291                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16292                        width, height, quality);
16293                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
16294                if (autoScale) {
16295                    mDrawingCache = bitmap;
16296                } else {
16297                    mUnscaledDrawingCache = bitmap;
16298                }
16299                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
16300            } catch (OutOfMemoryError e) {
16301                // If there is not enough memory to create the bitmap cache, just
16302                // ignore the issue as bitmap caches are not required to draw the
16303                // view hierarchy
16304                if (autoScale) {
16305                    mDrawingCache = null;
16306                } else {
16307                    mUnscaledDrawingCache = null;
16308                }
16309                mCachingFailed = true;
16310                return;
16311            }
16312
16313            clear = drawingCacheBackgroundColor != 0;
16314        }
16315
16316        Canvas canvas;
16317        if (attachInfo != null) {
16318            canvas = attachInfo.mCanvas;
16319            if (canvas == null) {
16320                canvas = new Canvas();
16321            }
16322            canvas.setBitmap(bitmap);
16323            // Temporarily clobber the cached Canvas in case one of our children
16324            // is also using a drawing cache. Without this, the children would
16325            // steal the canvas by attaching their own bitmap to it and bad, bad
16326            // thing would happen (invisible views, corrupted drawings, etc.)
16327            attachInfo.mCanvas = null;
16328        } else {
16329            // This case should hopefully never or seldom happen
16330            canvas = new Canvas(bitmap);
16331        }
16332
16333        if (clear) {
16334            bitmap.eraseColor(drawingCacheBackgroundColor);
16335        }
16336
16337        computeScroll();
16338        final int restoreCount = canvas.save();
16339
16340        if (autoScale && scalingRequired) {
16341            final float scale = attachInfo.mApplicationScale;
16342            canvas.scale(scale, scale);
16343        }
16344
16345        canvas.translate(-mScrollX, -mScrollY);
16346
16347        mPrivateFlags |= PFLAG_DRAWN;
16348        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
16349                mLayerType != LAYER_TYPE_NONE) {
16350            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
16351        }
16352
16353        // Fast path for layouts with no backgrounds
16354        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16355            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16356            dispatchDraw(canvas);
16357            if (mOverlay != null && !mOverlay.isEmpty()) {
16358                mOverlay.getOverlayView().draw(canvas);
16359            }
16360        } else {
16361            draw(canvas);
16362        }
16363
16364        canvas.restoreToCount(restoreCount);
16365        canvas.setBitmap(null);
16366
16367        if (attachInfo != null) {
16368            // Restore the cached Canvas for our siblings
16369            attachInfo.mCanvas = canvas;
16370        }
16371    }
16372
16373    /**
16374     * Create a snapshot of the view into a bitmap.  We should probably make
16375     * some form of this public, but should think about the API.
16376     *
16377     * @hide
16378     */
16379    public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
16380        int width = mRight - mLeft;
16381        int height = mBottom - mTop;
16382
16383        final AttachInfo attachInfo = mAttachInfo;
16384        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
16385        width = (int) ((width * scale) + 0.5f);
16386        height = (int) ((height * scale) + 0.5f);
16387
16388        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
16389                width > 0 ? width : 1, height > 0 ? height : 1, quality);
16390        if (bitmap == null) {
16391            throw new OutOfMemoryError();
16392        }
16393
16394        Resources resources = getResources();
16395        if (resources != null) {
16396            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
16397        }
16398
16399        Canvas canvas;
16400        if (attachInfo != null) {
16401            canvas = attachInfo.mCanvas;
16402            if (canvas == null) {
16403                canvas = new Canvas();
16404            }
16405            canvas.setBitmap(bitmap);
16406            // Temporarily clobber the cached Canvas in case one of our children
16407            // is also using a drawing cache. Without this, the children would
16408            // steal the canvas by attaching their own bitmap to it and bad, bad
16409            // things would happen (invisible views, corrupted drawings, etc.)
16410            attachInfo.mCanvas = null;
16411        } else {
16412            // This case should hopefully never or seldom happen
16413            canvas = new Canvas(bitmap);
16414        }
16415
16416        if ((backgroundColor & 0xff000000) != 0) {
16417            bitmap.eraseColor(backgroundColor);
16418        }
16419
16420        computeScroll();
16421        final int restoreCount = canvas.save();
16422        canvas.scale(scale, scale);
16423        canvas.translate(-mScrollX, -mScrollY);
16424
16425        // Temporarily remove the dirty mask
16426        int flags = mPrivateFlags;
16427        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16428
16429        // Fast path for layouts with no backgrounds
16430        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16431            dispatchDraw(canvas);
16432            if (mOverlay != null && !mOverlay.isEmpty()) {
16433                mOverlay.getOverlayView().draw(canvas);
16434            }
16435        } else {
16436            draw(canvas);
16437        }
16438
16439        mPrivateFlags = flags;
16440
16441        canvas.restoreToCount(restoreCount);
16442        canvas.setBitmap(null);
16443
16444        if (attachInfo != null) {
16445            // Restore the cached Canvas for our siblings
16446            attachInfo.mCanvas = canvas;
16447        }
16448
16449        return bitmap;
16450    }
16451
16452    /**
16453     * Indicates whether this View is currently in edit mode. A View is usually
16454     * in edit mode when displayed within a developer tool. For instance, if
16455     * this View is being drawn by a visual user interface builder, this method
16456     * should return true.
16457     *
16458     * Subclasses should check the return value of this method to provide
16459     * different behaviors if their normal behavior might interfere with the
16460     * host environment. For instance: the class spawns a thread in its
16461     * constructor, the drawing code relies on device-specific features, etc.
16462     *
16463     * This method is usually checked in the drawing code of custom widgets.
16464     *
16465     * @return True if this View is in edit mode, false otherwise.
16466     */
16467    public boolean isInEditMode() {
16468        return false;
16469    }
16470
16471    /**
16472     * If the View draws content inside its padding and enables fading edges,
16473     * it needs to support padding offsets. Padding offsets are added to the
16474     * fading edges to extend the length of the fade so that it covers pixels
16475     * drawn inside the padding.
16476     *
16477     * Subclasses of this class should override this method if they need
16478     * to draw content inside the padding.
16479     *
16480     * @return True if padding offset must be applied, false otherwise.
16481     *
16482     * @see #getLeftPaddingOffset()
16483     * @see #getRightPaddingOffset()
16484     * @see #getTopPaddingOffset()
16485     * @see #getBottomPaddingOffset()
16486     *
16487     * @since CURRENT
16488     */
16489    protected boolean isPaddingOffsetRequired() {
16490        return false;
16491    }
16492
16493    /**
16494     * Amount by which to extend the left fading region. Called only when
16495     * {@link #isPaddingOffsetRequired()} returns true.
16496     *
16497     * @return The left padding offset in pixels.
16498     *
16499     * @see #isPaddingOffsetRequired()
16500     *
16501     * @since CURRENT
16502     */
16503    protected int getLeftPaddingOffset() {
16504        return 0;
16505    }
16506
16507    /**
16508     * Amount by which to extend the right fading region. Called only when
16509     * {@link #isPaddingOffsetRequired()} returns true.
16510     *
16511     * @return The right padding offset in pixels.
16512     *
16513     * @see #isPaddingOffsetRequired()
16514     *
16515     * @since CURRENT
16516     */
16517    protected int getRightPaddingOffset() {
16518        return 0;
16519    }
16520
16521    /**
16522     * Amount by which to extend the top fading region. Called only when
16523     * {@link #isPaddingOffsetRequired()} returns true.
16524     *
16525     * @return The top padding offset in pixels.
16526     *
16527     * @see #isPaddingOffsetRequired()
16528     *
16529     * @since CURRENT
16530     */
16531    protected int getTopPaddingOffset() {
16532        return 0;
16533    }
16534
16535    /**
16536     * Amount by which to extend the bottom fading region. Called only when
16537     * {@link #isPaddingOffsetRequired()} returns true.
16538     *
16539     * @return The bottom padding offset in pixels.
16540     *
16541     * @see #isPaddingOffsetRequired()
16542     *
16543     * @since CURRENT
16544     */
16545    protected int getBottomPaddingOffset() {
16546        return 0;
16547    }
16548
16549    /**
16550     * @hide
16551     * @param offsetRequired
16552     */
16553    protected int getFadeTop(boolean offsetRequired) {
16554        int top = mPaddingTop;
16555        if (offsetRequired) top += getTopPaddingOffset();
16556        return top;
16557    }
16558
16559    /**
16560     * @hide
16561     * @param offsetRequired
16562     */
16563    protected int getFadeHeight(boolean offsetRequired) {
16564        int padding = mPaddingTop;
16565        if (offsetRequired) padding += getTopPaddingOffset();
16566        return mBottom - mTop - mPaddingBottom - padding;
16567    }
16568
16569    /**
16570     * <p>Indicates whether this view is attached to a hardware accelerated
16571     * window or not.</p>
16572     *
16573     * <p>Even if this method returns true, it does not mean that every call
16574     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
16575     * accelerated {@link android.graphics.Canvas}. For instance, if this view
16576     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
16577     * window is hardware accelerated,
16578     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
16579     * return false, and this method will return true.</p>
16580     *
16581     * @return True if the view is attached to a window and the window is
16582     *         hardware accelerated; false in any other case.
16583     */
16584    @ViewDebug.ExportedProperty(category = "drawing")
16585    public boolean isHardwareAccelerated() {
16586        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
16587    }
16588
16589    /**
16590     * Sets a rectangular area on this view to which the view will be clipped
16591     * when it is drawn. Setting the value to null will remove the clip bounds
16592     * and the view will draw normally, using its full bounds.
16593     *
16594     * @param clipBounds The rectangular area, in the local coordinates of
16595     * this view, to which future drawing operations will be clipped.
16596     */
16597    public void setClipBounds(Rect clipBounds) {
16598        if (clipBounds == mClipBounds
16599                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
16600            return;
16601        }
16602        if (clipBounds != null) {
16603            if (mClipBounds == null) {
16604                mClipBounds = new Rect(clipBounds);
16605            } else {
16606                mClipBounds.set(clipBounds);
16607            }
16608        } else {
16609            mClipBounds = null;
16610        }
16611        mRenderNode.setClipBounds(mClipBounds);
16612        invalidateViewProperty(false, false);
16613    }
16614
16615    /**
16616     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
16617     *
16618     * @return A copy of the current clip bounds if clip bounds are set,
16619     * otherwise null.
16620     */
16621    public Rect getClipBounds() {
16622        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
16623    }
16624
16625
16626    /**
16627     * Populates an output rectangle with the clip bounds of the view,
16628     * returning {@code true} if successful or {@code false} if the view's
16629     * clip bounds are {@code null}.
16630     *
16631     * @param outRect rectangle in which to place the clip bounds of the view
16632     * @return {@code true} if successful or {@code false} if the view's
16633     *         clip bounds are {@code null}
16634     */
16635    public boolean getClipBounds(Rect outRect) {
16636        if (mClipBounds != null) {
16637            outRect.set(mClipBounds);
16638            return true;
16639        }
16640        return false;
16641    }
16642
16643    /**
16644     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
16645     * case of an active Animation being run on the view.
16646     */
16647    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
16648            Animation a, boolean scalingRequired) {
16649        Transformation invalidationTransform;
16650        final int flags = parent.mGroupFlags;
16651        final boolean initialized = a.isInitialized();
16652        if (!initialized) {
16653            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
16654            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
16655            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
16656            onAnimationStart();
16657        }
16658
16659        final Transformation t = parent.getChildTransformation();
16660        boolean more = a.getTransformation(drawingTime, t, 1f);
16661        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
16662            if (parent.mInvalidationTransformation == null) {
16663                parent.mInvalidationTransformation = new Transformation();
16664            }
16665            invalidationTransform = parent.mInvalidationTransformation;
16666            a.getTransformation(drawingTime, invalidationTransform, 1f);
16667        } else {
16668            invalidationTransform = t;
16669        }
16670
16671        if (more) {
16672            if (!a.willChangeBounds()) {
16673                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
16674                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
16675                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
16676                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
16677                    // The child need to draw an animation, potentially offscreen, so
16678                    // make sure we do not cancel invalidate requests
16679                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16680                    parent.invalidate(mLeft, mTop, mRight, mBottom);
16681                }
16682            } else {
16683                if (parent.mInvalidateRegion == null) {
16684                    parent.mInvalidateRegion = new RectF();
16685                }
16686                final RectF region = parent.mInvalidateRegion;
16687                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
16688                        invalidationTransform);
16689
16690                // The child need to draw an animation, potentially offscreen, so
16691                // make sure we do not cancel invalidate requests
16692                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
16693
16694                final int left = mLeft + (int) region.left;
16695                final int top = mTop + (int) region.top;
16696                parent.invalidate(left, top, left + (int) (region.width() + .5f),
16697                        top + (int) (region.height() + .5f));
16698            }
16699        }
16700        return more;
16701    }
16702
16703    /**
16704     * This method is called by getDisplayList() when a display list is recorded for a View.
16705     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
16706     */
16707    void setDisplayListProperties(RenderNode renderNode) {
16708        if (renderNode != null) {
16709            renderNode.setHasOverlappingRendering(getHasOverlappingRendering());
16710            renderNode.setClipToBounds(mParent instanceof ViewGroup
16711                    && ((ViewGroup) mParent).getClipChildren());
16712
16713            float alpha = 1;
16714            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
16715                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16716                ViewGroup parentVG = (ViewGroup) mParent;
16717                final Transformation t = parentVG.getChildTransformation();
16718                if (parentVG.getChildStaticTransformation(this, t)) {
16719                    final int transformType = t.getTransformationType();
16720                    if (transformType != Transformation.TYPE_IDENTITY) {
16721                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
16722                            alpha = t.getAlpha();
16723                        }
16724                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
16725                            renderNode.setStaticMatrix(t.getMatrix());
16726                        }
16727                    }
16728                }
16729            }
16730            if (mTransformationInfo != null) {
16731                alpha *= getFinalAlpha();
16732                if (alpha < 1) {
16733                    final int multipliedAlpha = (int) (255 * alpha);
16734                    if (onSetAlpha(multipliedAlpha)) {
16735                        alpha = 1;
16736                    }
16737                }
16738                renderNode.setAlpha(alpha);
16739            } else if (alpha < 1) {
16740                renderNode.setAlpha(alpha);
16741            }
16742        }
16743    }
16744
16745    /**
16746     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
16747     *
16748     * This is where the View specializes rendering behavior based on layer type,
16749     * and hardware acceleration.
16750     */
16751    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
16752        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
16753        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
16754         *
16755         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
16756         * HW accelerated, it can't handle drawing RenderNodes.
16757         */
16758        boolean drawingWithRenderNode = mAttachInfo != null
16759                && mAttachInfo.mHardwareAccelerated
16760                && hardwareAcceleratedCanvas;
16761
16762        boolean more = false;
16763        final boolean childHasIdentityMatrix = hasIdentityMatrix();
16764        final int parentFlags = parent.mGroupFlags;
16765
16766        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
16767            parent.getChildTransformation().clear();
16768            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16769        }
16770
16771        Transformation transformToApply = null;
16772        boolean concatMatrix = false;
16773        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
16774        final Animation a = getAnimation();
16775        if (a != null) {
16776            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
16777            concatMatrix = a.willChangeTransformationMatrix();
16778            if (concatMatrix) {
16779                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16780            }
16781            transformToApply = parent.getChildTransformation();
16782        } else {
16783            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
16784                // No longer animating: clear out old animation matrix
16785                mRenderNode.setAnimationMatrix(null);
16786                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
16787            }
16788            if (!drawingWithRenderNode
16789                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
16790                final Transformation t = parent.getChildTransformation();
16791                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
16792                if (hasTransform) {
16793                    final int transformType = t.getTransformationType();
16794                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
16795                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
16796                }
16797            }
16798        }
16799
16800        concatMatrix |= !childHasIdentityMatrix;
16801
16802        // Sets the flag as early as possible to allow draw() implementations
16803        // to call invalidate() successfully when doing animations
16804        mPrivateFlags |= PFLAG_DRAWN;
16805
16806        if (!concatMatrix &&
16807                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
16808                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
16809                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
16810                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
16811            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
16812            return more;
16813        }
16814        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
16815
16816        if (hardwareAcceleratedCanvas) {
16817            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
16818            // retain the flag's value temporarily in the mRecreateDisplayList flag
16819            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
16820            mPrivateFlags &= ~PFLAG_INVALIDATED;
16821        }
16822
16823        RenderNode renderNode = null;
16824        Bitmap cache = null;
16825        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
16826        if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) {
16827             if (layerType != LAYER_TYPE_NONE) {
16828                 // If not drawing with RenderNode, treat HW layers as SW
16829                 layerType = LAYER_TYPE_SOFTWARE;
16830                 buildDrawingCache(true);
16831            }
16832            cache = getDrawingCache(true);
16833        }
16834
16835        if (drawingWithRenderNode) {
16836            // Delay getting the display list until animation-driven alpha values are
16837            // set up and possibly passed on to the view
16838            renderNode = updateDisplayListIfDirty();
16839            if (!renderNode.isValid()) {
16840                // Uncommon, but possible. If a view is removed from the hierarchy during the call
16841                // to getDisplayList(), the display list will be marked invalid and we should not
16842                // try to use it again.
16843                renderNode = null;
16844                drawingWithRenderNode = false;
16845            }
16846        }
16847
16848        int sx = 0;
16849        int sy = 0;
16850        if (!drawingWithRenderNode) {
16851            computeScroll();
16852            sx = mScrollX;
16853            sy = mScrollY;
16854        }
16855
16856        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
16857        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
16858
16859        int restoreTo = -1;
16860        if (!drawingWithRenderNode || transformToApply != null) {
16861            restoreTo = canvas.save();
16862        }
16863        if (offsetForScroll) {
16864            canvas.translate(mLeft - sx, mTop - sy);
16865        } else {
16866            if (!drawingWithRenderNode) {
16867                canvas.translate(mLeft, mTop);
16868            }
16869            if (scalingRequired) {
16870                if (drawingWithRenderNode) {
16871                    // TODO: Might not need this if we put everything inside the DL
16872                    restoreTo = canvas.save();
16873                }
16874                // mAttachInfo cannot be null, otherwise scalingRequired == false
16875                final float scale = 1.0f / mAttachInfo.mApplicationScale;
16876                canvas.scale(scale, scale);
16877            }
16878        }
16879
16880        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
16881        if (transformToApply != null
16882                || alpha < 1
16883                || !hasIdentityMatrix()
16884                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16885            if (transformToApply != null || !childHasIdentityMatrix) {
16886                int transX = 0;
16887                int transY = 0;
16888
16889                if (offsetForScroll) {
16890                    transX = -sx;
16891                    transY = -sy;
16892                }
16893
16894                if (transformToApply != null) {
16895                    if (concatMatrix) {
16896                        if (drawingWithRenderNode) {
16897                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
16898                        } else {
16899                            // Undo the scroll translation, apply the transformation matrix,
16900                            // then redo the scroll translate to get the correct result.
16901                            canvas.translate(-transX, -transY);
16902                            canvas.concat(transformToApply.getMatrix());
16903                            canvas.translate(transX, transY);
16904                        }
16905                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16906                    }
16907
16908                    float transformAlpha = transformToApply.getAlpha();
16909                    if (transformAlpha < 1) {
16910                        alpha *= transformAlpha;
16911                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16912                    }
16913                }
16914
16915                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
16916                    canvas.translate(-transX, -transY);
16917                    canvas.concat(getMatrix());
16918                    canvas.translate(transX, transY);
16919                }
16920            }
16921
16922            // Deal with alpha if it is or used to be <1
16923            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
16924                if (alpha < 1) {
16925                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16926                } else {
16927                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
16928                }
16929                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
16930                if (!drawingWithDrawingCache) {
16931                    final int multipliedAlpha = (int) (255 * alpha);
16932                    if (!onSetAlpha(multipliedAlpha)) {
16933                        if (drawingWithRenderNode) {
16934                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
16935                        } else if (layerType == LAYER_TYPE_NONE) {
16936                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
16937                                    multipliedAlpha);
16938                        }
16939                    } else {
16940                        // Alpha is handled by the child directly, clobber the layer's alpha
16941                        mPrivateFlags |= PFLAG_ALPHA_SET;
16942                    }
16943                }
16944            }
16945        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
16946            onSetAlpha(255);
16947            mPrivateFlags &= ~PFLAG_ALPHA_SET;
16948        }
16949
16950        if (!drawingWithRenderNode) {
16951            // apply clips directly, since RenderNode won't do it for this draw
16952            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
16953                if (offsetForScroll) {
16954                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
16955                } else {
16956                    if (!scalingRequired || cache == null) {
16957                        canvas.clipRect(0, 0, getWidth(), getHeight());
16958                    } else {
16959                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
16960                    }
16961                }
16962            }
16963
16964            if (mClipBounds != null) {
16965                // clip bounds ignore scroll
16966                canvas.clipRect(mClipBounds);
16967            }
16968        }
16969
16970        if (!drawingWithDrawingCache) {
16971            if (drawingWithRenderNode) {
16972                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16973                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
16974            } else {
16975                // Fast path for layouts with no backgrounds
16976                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
16977                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16978                    dispatchDraw(canvas);
16979                } else {
16980                    draw(canvas);
16981                }
16982            }
16983        } else if (cache != null) {
16984            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
16985            if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) {
16986                // no layer paint, use temporary paint to draw bitmap
16987                Paint cachePaint = parent.mCachePaint;
16988                if (cachePaint == null) {
16989                    cachePaint = new Paint();
16990                    cachePaint.setDither(false);
16991                    parent.mCachePaint = cachePaint;
16992                }
16993                cachePaint.setAlpha((int) (alpha * 255));
16994                canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
16995            } else {
16996                // use layer paint to draw the bitmap, merging the two alphas, but also restore
16997                int layerPaintAlpha = mLayerPaint.getAlpha();
16998                if (alpha < 1) {
16999                    mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha));
17000                }
17001                canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint);
17002                if (alpha < 1) {
17003                    mLayerPaint.setAlpha(layerPaintAlpha);
17004                }
17005            }
17006        }
17007
17008        if (restoreTo >= 0) {
17009            canvas.restoreToCount(restoreTo);
17010        }
17011
17012        if (a != null && !more) {
17013            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
17014                onSetAlpha(255);
17015            }
17016            parent.finishAnimatingView(this, a);
17017        }
17018
17019        if (more && hardwareAcceleratedCanvas) {
17020            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
17021                // alpha animations should cause the child to recreate its display list
17022                invalidate(true);
17023            }
17024        }
17025
17026        mRecreateDisplayList = false;
17027
17028        return more;
17029    }
17030
17031    /**
17032     * Manually render this view (and all of its children) to the given Canvas.
17033     * The view must have already done a full layout before this function is
17034     * called.  When implementing a view, implement
17035     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
17036     * If you do need to override this method, call the superclass version.
17037     *
17038     * @param canvas The Canvas to which the View is rendered.
17039     */
17040    @CallSuper
17041    public void draw(Canvas canvas) {
17042        final int privateFlags = mPrivateFlags;
17043        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
17044                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
17045        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
17046
17047        /*
17048         * Draw traversal performs several drawing steps which must be executed
17049         * in the appropriate order:
17050         *
17051         *      1. Draw the background
17052         *      2. If necessary, save the canvas' layers to prepare for fading
17053         *      3. Draw view's content
17054         *      4. Draw children
17055         *      5. If necessary, draw the fading edges and restore layers
17056         *      6. Draw decorations (scrollbars for instance)
17057         */
17058
17059        // Step 1, draw the background, if needed
17060        int saveCount;
17061
17062        if (!dirtyOpaque) {
17063            drawBackground(canvas);
17064        }
17065
17066        // skip step 2 & 5 if possible (common case)
17067        final int viewFlags = mViewFlags;
17068        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
17069        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
17070        if (!verticalEdges && !horizontalEdges) {
17071            // Step 3, draw the content
17072            if (!dirtyOpaque) onDraw(canvas);
17073
17074            // Step 4, draw the children
17075            dispatchDraw(canvas);
17076
17077            // Overlay is part of the content and draws beneath Foreground
17078            if (mOverlay != null && !mOverlay.isEmpty()) {
17079                mOverlay.getOverlayView().dispatchDraw(canvas);
17080            }
17081
17082            // Step 6, draw decorations (foreground, scrollbars)
17083            onDrawForeground(canvas);
17084
17085            // we're done...
17086            return;
17087        }
17088
17089        /*
17090         * Here we do the full fledged routine...
17091         * (this is an uncommon case where speed matters less,
17092         * this is why we repeat some of the tests that have been
17093         * done above)
17094         */
17095
17096        boolean drawTop = false;
17097        boolean drawBottom = false;
17098        boolean drawLeft = false;
17099        boolean drawRight = false;
17100
17101        float topFadeStrength = 0.0f;
17102        float bottomFadeStrength = 0.0f;
17103        float leftFadeStrength = 0.0f;
17104        float rightFadeStrength = 0.0f;
17105
17106        // Step 2, save the canvas' layers
17107        int paddingLeft = mPaddingLeft;
17108
17109        final boolean offsetRequired = isPaddingOffsetRequired();
17110        if (offsetRequired) {
17111            paddingLeft += getLeftPaddingOffset();
17112        }
17113
17114        int left = mScrollX + paddingLeft;
17115        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
17116        int top = mScrollY + getFadeTop(offsetRequired);
17117        int bottom = top + getFadeHeight(offsetRequired);
17118
17119        if (offsetRequired) {
17120            right += getRightPaddingOffset();
17121            bottom += getBottomPaddingOffset();
17122        }
17123
17124        final ScrollabilityCache scrollabilityCache = mScrollCache;
17125        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
17126        int length = (int) fadeHeight;
17127
17128        // clip the fade length if top and bottom fades overlap
17129        // overlapping fades produce odd-looking artifacts
17130        if (verticalEdges && (top + length > bottom - length)) {
17131            length = (bottom - top) / 2;
17132        }
17133
17134        // also clip horizontal fades if necessary
17135        if (horizontalEdges && (left + length > right - length)) {
17136            length = (right - left) / 2;
17137        }
17138
17139        if (verticalEdges) {
17140            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
17141            drawTop = topFadeStrength * fadeHeight > 1.0f;
17142            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
17143            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
17144        }
17145
17146        if (horizontalEdges) {
17147            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
17148            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
17149            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
17150            drawRight = rightFadeStrength * fadeHeight > 1.0f;
17151        }
17152
17153        saveCount = canvas.getSaveCount();
17154
17155        int solidColor = getSolidColor();
17156        if (solidColor == 0) {
17157            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
17158
17159            if (drawTop) {
17160                canvas.saveLayer(left, top, right, top + length, null, flags);
17161            }
17162
17163            if (drawBottom) {
17164                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
17165            }
17166
17167            if (drawLeft) {
17168                canvas.saveLayer(left, top, left + length, bottom, null, flags);
17169            }
17170
17171            if (drawRight) {
17172                canvas.saveLayer(right - length, top, right, bottom, null, flags);
17173            }
17174        } else {
17175            scrollabilityCache.setFadeColor(solidColor);
17176        }
17177
17178        // Step 3, draw the content
17179        if (!dirtyOpaque) onDraw(canvas);
17180
17181        // Step 4, draw the children
17182        dispatchDraw(canvas);
17183
17184        // Step 5, draw the fade effect and restore layers
17185        final Paint p = scrollabilityCache.paint;
17186        final Matrix matrix = scrollabilityCache.matrix;
17187        final Shader fade = scrollabilityCache.shader;
17188
17189        if (drawTop) {
17190            matrix.setScale(1, fadeHeight * topFadeStrength);
17191            matrix.postTranslate(left, top);
17192            fade.setLocalMatrix(matrix);
17193            p.setShader(fade);
17194            canvas.drawRect(left, top, right, top + length, p);
17195        }
17196
17197        if (drawBottom) {
17198            matrix.setScale(1, fadeHeight * bottomFadeStrength);
17199            matrix.postRotate(180);
17200            matrix.postTranslate(left, bottom);
17201            fade.setLocalMatrix(matrix);
17202            p.setShader(fade);
17203            canvas.drawRect(left, bottom - length, right, bottom, p);
17204        }
17205
17206        if (drawLeft) {
17207            matrix.setScale(1, fadeHeight * leftFadeStrength);
17208            matrix.postRotate(-90);
17209            matrix.postTranslate(left, top);
17210            fade.setLocalMatrix(matrix);
17211            p.setShader(fade);
17212            canvas.drawRect(left, top, left + length, bottom, p);
17213        }
17214
17215        if (drawRight) {
17216            matrix.setScale(1, fadeHeight * rightFadeStrength);
17217            matrix.postRotate(90);
17218            matrix.postTranslate(right, top);
17219            fade.setLocalMatrix(matrix);
17220            p.setShader(fade);
17221            canvas.drawRect(right - length, top, right, bottom, p);
17222        }
17223
17224        canvas.restoreToCount(saveCount);
17225
17226        // Overlay is part of the content and draws beneath Foreground
17227        if (mOverlay != null && !mOverlay.isEmpty()) {
17228            mOverlay.getOverlayView().dispatchDraw(canvas);
17229        }
17230
17231        // Step 6, draw decorations (foreground, scrollbars)
17232        onDrawForeground(canvas);
17233    }
17234
17235    /**
17236     * Draws the background onto the specified canvas.
17237     *
17238     * @param canvas Canvas on which to draw the background
17239     */
17240    private void drawBackground(Canvas canvas) {
17241        final Drawable background = mBackground;
17242        if (background == null) {
17243            return;
17244        }
17245
17246        setBackgroundBounds();
17247
17248        // Attempt to use a display list if requested.
17249        if (canvas.isHardwareAccelerated() && mAttachInfo != null
17250                && mAttachInfo.mThreadedRenderer != null) {
17251            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
17252
17253            final RenderNode renderNode = mBackgroundRenderNode;
17254            if (renderNode != null && renderNode.isValid()) {
17255                setBackgroundRenderNodeProperties(renderNode);
17256                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
17257                return;
17258            }
17259        }
17260
17261        final int scrollX = mScrollX;
17262        final int scrollY = mScrollY;
17263        if ((scrollX | scrollY) == 0) {
17264            background.draw(canvas);
17265        } else {
17266            canvas.translate(scrollX, scrollY);
17267            background.draw(canvas);
17268            canvas.translate(-scrollX, -scrollY);
17269        }
17270    }
17271
17272    /**
17273     * Sets the correct background bounds and rebuilds the outline, if needed.
17274     * <p/>
17275     * This is called by LayoutLib.
17276     */
17277    void setBackgroundBounds() {
17278        if (mBackgroundSizeChanged && mBackground != null) {
17279            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
17280            mBackgroundSizeChanged = false;
17281            rebuildOutline();
17282        }
17283    }
17284
17285    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
17286        renderNode.setTranslationX(mScrollX);
17287        renderNode.setTranslationY(mScrollY);
17288    }
17289
17290    /**
17291     * Creates a new display list or updates the existing display list for the
17292     * specified Drawable.
17293     *
17294     * @param drawable Drawable for which to create a display list
17295     * @param renderNode Existing RenderNode, or {@code null}
17296     * @return A valid display list for the specified drawable
17297     */
17298    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
17299        if (renderNode == null) {
17300            renderNode = RenderNode.create(drawable.getClass().getName(), this);
17301        }
17302
17303        final Rect bounds = drawable.getBounds();
17304        final int width = bounds.width();
17305        final int height = bounds.height();
17306        final DisplayListCanvas canvas = renderNode.start(width, height);
17307
17308        // Reverse left/top translation done by drawable canvas, which will
17309        // instead be applied by rendernode's LTRB bounds below. This way, the
17310        // drawable's bounds match with its rendernode bounds and its content
17311        // will lie within those bounds in the rendernode tree.
17312        canvas.translate(-bounds.left, -bounds.top);
17313
17314        try {
17315            drawable.draw(canvas);
17316        } finally {
17317            renderNode.end(canvas);
17318        }
17319
17320        // Set up drawable properties that are view-independent.
17321        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
17322        renderNode.setProjectBackwards(drawable.isProjected());
17323        renderNode.setProjectionReceiver(true);
17324        renderNode.setClipToBounds(false);
17325        return renderNode;
17326    }
17327
17328    /**
17329     * Returns the overlay for this view, creating it if it does not yet exist.
17330     * Adding drawables to the overlay will cause them to be displayed whenever
17331     * the view itself is redrawn. Objects in the overlay should be actively
17332     * managed: remove them when they should not be displayed anymore. The
17333     * overlay will always have the same size as its host view.
17334     *
17335     * <p>Note: Overlays do not currently work correctly with {@link
17336     * SurfaceView} or {@link TextureView}; contents in overlays for these
17337     * types of views may not display correctly.</p>
17338     *
17339     * @return The ViewOverlay object for this view.
17340     * @see ViewOverlay
17341     */
17342    public ViewOverlay getOverlay() {
17343        if (mOverlay == null) {
17344            mOverlay = new ViewOverlay(mContext, this);
17345        }
17346        return mOverlay;
17347    }
17348
17349    /**
17350     * Override this if your view is known to always be drawn on top of a solid color background,
17351     * and needs to draw fading edges. Returning a non-zero color enables the view system to
17352     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
17353     * should be set to 0xFF.
17354     *
17355     * @see #setVerticalFadingEdgeEnabled(boolean)
17356     * @see #setHorizontalFadingEdgeEnabled(boolean)
17357     *
17358     * @return The known solid color background for this view, or 0 if the color may vary
17359     */
17360    @ViewDebug.ExportedProperty(category = "drawing")
17361    @ColorInt
17362    public int getSolidColor() {
17363        return 0;
17364    }
17365
17366    /**
17367     * Build a human readable string representation of the specified view flags.
17368     *
17369     * @param flags the view flags to convert to a string
17370     * @return a String representing the supplied flags
17371     */
17372    private static String printFlags(int flags) {
17373        String output = "";
17374        int numFlags = 0;
17375        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
17376            output += "TAKES_FOCUS";
17377            numFlags++;
17378        }
17379
17380        switch (flags & VISIBILITY_MASK) {
17381        case INVISIBLE:
17382            if (numFlags > 0) {
17383                output += " ";
17384            }
17385            output += "INVISIBLE";
17386            // USELESS HERE numFlags++;
17387            break;
17388        case GONE:
17389            if (numFlags > 0) {
17390                output += " ";
17391            }
17392            output += "GONE";
17393            // USELESS HERE numFlags++;
17394            break;
17395        default:
17396            break;
17397        }
17398        return output;
17399    }
17400
17401    /**
17402     * Build a human readable string representation of the specified private
17403     * view flags.
17404     *
17405     * @param privateFlags the private view flags to convert to a string
17406     * @return a String representing the supplied flags
17407     */
17408    private static String printPrivateFlags(int privateFlags) {
17409        String output = "";
17410        int numFlags = 0;
17411
17412        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
17413            output += "WANTS_FOCUS";
17414            numFlags++;
17415        }
17416
17417        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
17418            if (numFlags > 0) {
17419                output += " ";
17420            }
17421            output += "FOCUSED";
17422            numFlags++;
17423        }
17424
17425        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
17426            if (numFlags > 0) {
17427                output += " ";
17428            }
17429            output += "SELECTED";
17430            numFlags++;
17431        }
17432
17433        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
17434            if (numFlags > 0) {
17435                output += " ";
17436            }
17437            output += "IS_ROOT_NAMESPACE";
17438            numFlags++;
17439        }
17440
17441        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
17442            if (numFlags > 0) {
17443                output += " ";
17444            }
17445            output += "HAS_BOUNDS";
17446            numFlags++;
17447        }
17448
17449        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
17450            if (numFlags > 0) {
17451                output += " ";
17452            }
17453            output += "DRAWN";
17454            // USELESS HERE numFlags++;
17455        }
17456        return output;
17457    }
17458
17459    /**
17460     * <p>Indicates whether or not this view's layout will be requested during
17461     * the next hierarchy layout pass.</p>
17462     *
17463     * @return true if the layout will be forced during next layout pass
17464     */
17465    public boolean isLayoutRequested() {
17466        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
17467    }
17468
17469    /**
17470     * Return true if o is a ViewGroup that is laying out using optical bounds.
17471     * @hide
17472     */
17473    public static boolean isLayoutModeOptical(Object o) {
17474        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
17475    }
17476
17477    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
17478        Insets parentInsets = mParent instanceof View ?
17479                ((View) mParent).getOpticalInsets() : Insets.NONE;
17480        Insets childInsets = getOpticalInsets();
17481        return setFrame(
17482                left   + parentInsets.left - childInsets.left,
17483                top    + parentInsets.top  - childInsets.top,
17484                right  + parentInsets.left + childInsets.right,
17485                bottom + parentInsets.top  + childInsets.bottom);
17486    }
17487
17488    /**
17489     * Assign a size and position to a view and all of its
17490     * descendants
17491     *
17492     * <p>This is the second phase of the layout mechanism.
17493     * (The first is measuring). In this phase, each parent calls
17494     * layout on all of its children to position them.
17495     * This is typically done using the child measurements
17496     * that were stored in the measure pass().</p>
17497     *
17498     * <p>Derived classes should not override this method.
17499     * Derived classes with children should override
17500     * onLayout. In that method, they should
17501     * call layout on each of their children.</p>
17502     *
17503     * @param l Left position, relative to parent
17504     * @param t Top position, relative to parent
17505     * @param r Right position, relative to parent
17506     * @param b Bottom position, relative to parent
17507     */
17508    @SuppressWarnings({"unchecked"})
17509    public void layout(int l, int t, int r, int b) {
17510        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
17511            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
17512            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17513        }
17514
17515        int oldL = mLeft;
17516        int oldT = mTop;
17517        int oldB = mBottom;
17518        int oldR = mRight;
17519
17520        boolean changed = isLayoutModeOptical(mParent) ?
17521                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
17522
17523        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
17524            onLayout(changed, l, t, r, b);
17525            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
17526
17527            ListenerInfo li = mListenerInfo;
17528            if (li != null && li.mOnLayoutChangeListeners != null) {
17529                ArrayList<OnLayoutChangeListener> listenersCopy =
17530                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
17531                int numListeners = listenersCopy.size();
17532                for (int i = 0; i < numListeners; ++i) {
17533                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
17534                }
17535            }
17536        }
17537
17538        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
17539        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
17540    }
17541
17542    /**
17543     * Called from layout when this view should
17544     * assign a size and position to each of its children.
17545     *
17546     * Derived classes with children should override
17547     * this method and call layout on each of
17548     * their children.
17549     * @param changed This is a new size or position for this view
17550     * @param left Left position, relative to parent
17551     * @param top Top position, relative to parent
17552     * @param right Right position, relative to parent
17553     * @param bottom Bottom position, relative to parent
17554     */
17555    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
17556    }
17557
17558    /**
17559     * Assign a size and position to this view.
17560     *
17561     * This is called from layout.
17562     *
17563     * @param left Left position, relative to parent
17564     * @param top Top position, relative to parent
17565     * @param right Right position, relative to parent
17566     * @param bottom Bottom position, relative to parent
17567     * @return true if the new size and position are different than the
17568     *         previous ones
17569     * {@hide}
17570     */
17571    protected boolean setFrame(int left, int top, int right, int bottom) {
17572        boolean changed = false;
17573
17574        if (DBG) {
17575            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
17576                    + right + "," + bottom + ")");
17577        }
17578
17579        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
17580            changed = true;
17581
17582            // Remember our drawn bit
17583            int drawn = mPrivateFlags & PFLAG_DRAWN;
17584
17585            int oldWidth = mRight - mLeft;
17586            int oldHeight = mBottom - mTop;
17587            int newWidth = right - left;
17588            int newHeight = bottom - top;
17589            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
17590
17591            // Invalidate our old position
17592            invalidate(sizeChanged);
17593
17594            mLeft = left;
17595            mTop = top;
17596            mRight = right;
17597            mBottom = bottom;
17598            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
17599
17600            mPrivateFlags |= PFLAG_HAS_BOUNDS;
17601
17602
17603            if (sizeChanged) {
17604                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
17605            }
17606
17607            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
17608                // If we are visible, force the DRAWN bit to on so that
17609                // this invalidate will go through (at least to our parent).
17610                // This is because someone may have invalidated this view
17611                // before this call to setFrame came in, thereby clearing
17612                // the DRAWN bit.
17613                mPrivateFlags |= PFLAG_DRAWN;
17614                invalidate(sizeChanged);
17615                // parent display list may need to be recreated based on a change in the bounds
17616                // of any child
17617                invalidateParentCaches();
17618            }
17619
17620            // Reset drawn bit to original value (invalidate turns it off)
17621            mPrivateFlags |= drawn;
17622
17623            mBackgroundSizeChanged = true;
17624            if (mForegroundInfo != null) {
17625                mForegroundInfo.mBoundsChanged = true;
17626            }
17627
17628            notifySubtreeAccessibilityStateChangedIfNeeded();
17629        }
17630        return changed;
17631    }
17632
17633    /**
17634     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
17635     * @hide
17636     */
17637    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
17638        setFrame(left, top, right, bottom);
17639    }
17640
17641    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
17642        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
17643        if (mOverlay != null) {
17644            mOverlay.getOverlayView().setRight(newWidth);
17645            mOverlay.getOverlayView().setBottom(newHeight);
17646        }
17647        rebuildOutline();
17648    }
17649
17650    /**
17651     * Finalize inflating a view from XML.  This is called as the last phase
17652     * of inflation, after all child views have been added.
17653     *
17654     * <p>Even if the subclass overrides onFinishInflate, they should always be
17655     * sure to call the super method, so that we get called.
17656     */
17657    @CallSuper
17658    protected void onFinishInflate() {
17659    }
17660
17661    /**
17662     * Returns the resources associated with this view.
17663     *
17664     * @return Resources object.
17665     */
17666    public Resources getResources() {
17667        return mResources;
17668    }
17669
17670    /**
17671     * Invalidates the specified Drawable.
17672     *
17673     * @param drawable the drawable to invalidate
17674     */
17675    @Override
17676    public void invalidateDrawable(@NonNull Drawable drawable) {
17677        if (verifyDrawable(drawable)) {
17678            final Rect dirty = drawable.getDirtyBounds();
17679            final int scrollX = mScrollX;
17680            final int scrollY = mScrollY;
17681
17682            invalidate(dirty.left + scrollX, dirty.top + scrollY,
17683                    dirty.right + scrollX, dirty.bottom + scrollY);
17684            rebuildOutline();
17685        }
17686    }
17687
17688    /**
17689     * Schedules an action on a drawable to occur at a specified time.
17690     *
17691     * @param who the recipient of the action
17692     * @param what the action to run on the drawable
17693     * @param when the time at which the action must occur. Uses the
17694     *        {@link SystemClock#uptimeMillis} timebase.
17695     */
17696    @Override
17697    public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
17698        if (verifyDrawable(who) && what != null) {
17699            final long delay = when - SystemClock.uptimeMillis();
17700            if (mAttachInfo != null) {
17701                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
17702                        Choreographer.CALLBACK_ANIMATION, what, who,
17703                        Choreographer.subtractFrameDelay(delay));
17704            } else {
17705                // Postpone the runnable until we know
17706                // on which thread it needs to run.
17707                getRunQueue().postDelayed(what, delay);
17708            }
17709        }
17710    }
17711
17712    /**
17713     * Cancels a scheduled action on a drawable.
17714     *
17715     * @param who the recipient of the action
17716     * @param what the action to cancel
17717     */
17718    @Override
17719    public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
17720        if (verifyDrawable(who) && what != null) {
17721            if (mAttachInfo != null) {
17722                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17723                        Choreographer.CALLBACK_ANIMATION, what, who);
17724            }
17725            getRunQueue().removeCallbacks(what);
17726        }
17727    }
17728
17729    /**
17730     * Unschedule any events associated with the given Drawable.  This can be
17731     * used when selecting a new Drawable into a view, so that the previous
17732     * one is completely unscheduled.
17733     *
17734     * @param who The Drawable to unschedule.
17735     *
17736     * @see #drawableStateChanged
17737     */
17738    public void unscheduleDrawable(Drawable who) {
17739        if (mAttachInfo != null && who != null) {
17740            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
17741                    Choreographer.CALLBACK_ANIMATION, null, who);
17742        }
17743    }
17744
17745    /**
17746     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
17747     * that the View directionality can and will be resolved before its Drawables.
17748     *
17749     * Will call {@link View#onResolveDrawables} when resolution is done.
17750     *
17751     * @hide
17752     */
17753    protected void resolveDrawables() {
17754        // Drawables resolution may need to happen before resolving the layout direction (which is
17755        // done only during the measure() call).
17756        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
17757        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
17758        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
17759        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
17760        // direction to be resolved as its resolved value will be the same as its raw value.
17761        if (!isLayoutDirectionResolved() &&
17762                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
17763            return;
17764        }
17765
17766        final int layoutDirection = isLayoutDirectionResolved() ?
17767                getLayoutDirection() : getRawLayoutDirection();
17768
17769        if (mBackground != null) {
17770            mBackground.setLayoutDirection(layoutDirection);
17771        }
17772        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17773            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
17774        }
17775        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
17776        onResolveDrawables(layoutDirection);
17777    }
17778
17779    boolean areDrawablesResolved() {
17780        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
17781    }
17782
17783    /**
17784     * Called when layout direction has been resolved.
17785     *
17786     * The default implementation does nothing.
17787     *
17788     * @param layoutDirection The resolved layout direction.
17789     *
17790     * @see #LAYOUT_DIRECTION_LTR
17791     * @see #LAYOUT_DIRECTION_RTL
17792     *
17793     * @hide
17794     */
17795    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
17796    }
17797
17798    /**
17799     * @hide
17800     */
17801    protected void resetResolvedDrawables() {
17802        resetResolvedDrawablesInternal();
17803    }
17804
17805    void resetResolvedDrawablesInternal() {
17806        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
17807    }
17808
17809    /**
17810     * If your view subclass is displaying its own Drawable objects, it should
17811     * override this function and return true for any Drawable it is
17812     * displaying.  This allows animations for those drawables to be
17813     * scheduled.
17814     *
17815     * <p>Be sure to call through to the super class when overriding this
17816     * function.
17817     *
17818     * @param who The Drawable to verify.  Return true if it is one you are
17819     *            displaying, else return the result of calling through to the
17820     *            super class.
17821     *
17822     * @return boolean If true than the Drawable is being displayed in the
17823     *         view; else false and it is not allowed to animate.
17824     *
17825     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
17826     * @see #drawableStateChanged()
17827     */
17828    @CallSuper
17829    protected boolean verifyDrawable(@NonNull Drawable who) {
17830        // Avoid verifying the scroll bar drawable so that we don't end up in
17831        // an invalidation loop. This effectively prevents the scroll bar
17832        // drawable from triggering invalidations and scheduling runnables.
17833        return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
17834    }
17835
17836    /**
17837     * This function is called whenever the state of the view changes in such
17838     * a way that it impacts the state of drawables being shown.
17839     * <p>
17840     * If the View has a StateListAnimator, it will also be called to run necessary state
17841     * change animations.
17842     * <p>
17843     * Be sure to call through to the superclass when overriding this function.
17844     *
17845     * @see Drawable#setState(int[])
17846     */
17847    @CallSuper
17848    protected void drawableStateChanged() {
17849        final int[] state = getDrawableState();
17850        boolean changed = false;
17851
17852        final Drawable bg = mBackground;
17853        if (bg != null && bg.isStateful()) {
17854            changed |= bg.setState(state);
17855        }
17856
17857        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17858        if (fg != null && fg.isStateful()) {
17859            changed |= fg.setState(state);
17860        }
17861
17862        if (mScrollCache != null) {
17863            final Drawable scrollBar = mScrollCache.scrollBar;
17864            if (scrollBar != null && scrollBar.isStateful()) {
17865                changed |= scrollBar.setState(state)
17866                        && mScrollCache.state != ScrollabilityCache.OFF;
17867            }
17868        }
17869
17870        if (mStateListAnimator != null) {
17871            mStateListAnimator.setState(state);
17872        }
17873
17874        if (changed) {
17875            invalidate();
17876        }
17877    }
17878
17879    /**
17880     * This function is called whenever the view hotspot changes and needs to
17881     * be propagated to drawables or child views managed by the view.
17882     * <p>
17883     * Dispatching to child views is handled by
17884     * {@link #dispatchDrawableHotspotChanged(float, float)}.
17885     * <p>
17886     * Be sure to call through to the superclass when overriding this function.
17887     *
17888     * @param x hotspot x coordinate
17889     * @param y hotspot y coordinate
17890     */
17891    @CallSuper
17892    public void drawableHotspotChanged(float x, float y) {
17893        if (mBackground != null) {
17894            mBackground.setHotspot(x, y);
17895        }
17896        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
17897            mForegroundInfo.mDrawable.setHotspot(x, y);
17898        }
17899
17900        dispatchDrawableHotspotChanged(x, y);
17901    }
17902
17903    /**
17904     * Dispatches drawableHotspotChanged to all of this View's children.
17905     *
17906     * @param x hotspot x coordinate
17907     * @param y hotspot y coordinate
17908     * @see #drawableHotspotChanged(float, float)
17909     */
17910    public void dispatchDrawableHotspotChanged(float x, float y) {
17911    }
17912
17913    /**
17914     * Call this to force a view to update its drawable state. This will cause
17915     * drawableStateChanged to be called on this view. Views that are interested
17916     * in the new state should call getDrawableState.
17917     *
17918     * @see #drawableStateChanged
17919     * @see #getDrawableState
17920     */
17921    public void refreshDrawableState() {
17922        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
17923        drawableStateChanged();
17924
17925        ViewParent parent = mParent;
17926        if (parent != null) {
17927            parent.childDrawableStateChanged(this);
17928        }
17929    }
17930
17931    /**
17932     * Return an array of resource IDs of the drawable states representing the
17933     * current state of the view.
17934     *
17935     * @return The current drawable state
17936     *
17937     * @see Drawable#setState(int[])
17938     * @see #drawableStateChanged()
17939     * @see #onCreateDrawableState(int)
17940     */
17941    public final int[] getDrawableState() {
17942        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
17943            return mDrawableState;
17944        } else {
17945            mDrawableState = onCreateDrawableState(0);
17946            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
17947            return mDrawableState;
17948        }
17949    }
17950
17951    /**
17952     * Generate the new {@link android.graphics.drawable.Drawable} state for
17953     * this view. This is called by the view
17954     * system when the cached Drawable state is determined to be invalid.  To
17955     * retrieve the current state, you should use {@link #getDrawableState}.
17956     *
17957     * @param extraSpace if non-zero, this is the number of extra entries you
17958     * would like in the returned array in which you can place your own
17959     * states.
17960     *
17961     * @return Returns an array holding the current {@link Drawable} state of
17962     * the view.
17963     *
17964     * @see #mergeDrawableStates(int[], int[])
17965     */
17966    protected int[] onCreateDrawableState(int extraSpace) {
17967        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
17968                mParent instanceof View) {
17969            return ((View) mParent).onCreateDrawableState(extraSpace);
17970        }
17971
17972        int[] drawableState;
17973
17974        int privateFlags = mPrivateFlags;
17975
17976        int viewStateIndex = 0;
17977        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
17978        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
17979        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
17980        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
17981        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
17982        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
17983        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
17984                ThreadedRenderer.isAvailable()) {
17985            // This is set if HW acceleration is requested, even if the current
17986            // process doesn't allow it.  This is just to allow app preview
17987            // windows to better match their app.
17988            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
17989        }
17990        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
17991
17992        final int privateFlags2 = mPrivateFlags2;
17993        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
17994            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
17995        }
17996        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
17997            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
17998        }
17999
18000        drawableState = StateSet.get(viewStateIndex);
18001
18002        //noinspection ConstantIfStatement
18003        if (false) {
18004            Log.i("View", "drawableStateIndex=" + viewStateIndex);
18005            Log.i("View", toString()
18006                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
18007                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
18008                    + " fo=" + hasFocus()
18009                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
18010                    + " wf=" + hasWindowFocus()
18011                    + ": " + Arrays.toString(drawableState));
18012        }
18013
18014        if (extraSpace == 0) {
18015            return drawableState;
18016        }
18017
18018        final int[] fullState;
18019        if (drawableState != null) {
18020            fullState = new int[drawableState.length + extraSpace];
18021            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
18022        } else {
18023            fullState = new int[extraSpace];
18024        }
18025
18026        return fullState;
18027    }
18028
18029    /**
18030     * Merge your own state values in <var>additionalState</var> into the base
18031     * state values <var>baseState</var> that were returned by
18032     * {@link #onCreateDrawableState(int)}.
18033     *
18034     * @param baseState The base state values returned by
18035     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
18036     * own additional state values.
18037     *
18038     * @param additionalState The additional state values you would like
18039     * added to <var>baseState</var>; this array is not modified.
18040     *
18041     * @return As a convenience, the <var>baseState</var> array you originally
18042     * passed into the function is returned.
18043     *
18044     * @see #onCreateDrawableState(int)
18045     */
18046    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
18047        final int N = baseState.length;
18048        int i = N - 1;
18049        while (i >= 0 && baseState[i] == 0) {
18050            i--;
18051        }
18052        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
18053        return baseState;
18054    }
18055
18056    /**
18057     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
18058     * on all Drawable objects associated with this view.
18059     * <p>
18060     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
18061     * attached to this view.
18062     */
18063    @CallSuper
18064    public void jumpDrawablesToCurrentState() {
18065        if (mBackground != null) {
18066            mBackground.jumpToCurrentState();
18067        }
18068        if (mStateListAnimator != null) {
18069            mStateListAnimator.jumpToCurrentState();
18070        }
18071        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
18072            mForegroundInfo.mDrawable.jumpToCurrentState();
18073        }
18074    }
18075
18076    /**
18077     * Sets the background color for this view.
18078     * @param color the color of the background
18079     */
18080    @RemotableViewMethod
18081    public void setBackgroundColor(@ColorInt int color) {
18082        if (mBackground instanceof ColorDrawable) {
18083            ((ColorDrawable) mBackground.mutate()).setColor(color);
18084            computeOpaqueFlags();
18085            mBackgroundResource = 0;
18086        } else {
18087            setBackground(new ColorDrawable(color));
18088        }
18089    }
18090
18091    /**
18092     * Set the background to a given resource. The resource should refer to
18093     * a Drawable object or 0 to remove the background.
18094     * @param resid The identifier of the resource.
18095     *
18096     * @attr ref android.R.styleable#View_background
18097     */
18098    @RemotableViewMethod
18099    public void setBackgroundResource(@DrawableRes int resid) {
18100        if (resid != 0 && resid == mBackgroundResource) {
18101            return;
18102        }
18103
18104        Drawable d = null;
18105        if (resid != 0) {
18106            d = mContext.getDrawable(resid);
18107        }
18108        setBackground(d);
18109
18110        mBackgroundResource = resid;
18111    }
18112
18113    /**
18114     * Set the background to a given Drawable, or remove the background. If the
18115     * background has padding, this View's padding is set to the background's
18116     * padding. However, when a background is removed, this View's padding isn't
18117     * touched. If setting the padding is desired, please use
18118     * {@link #setPadding(int, int, int, int)}.
18119     *
18120     * @param background The Drawable to use as the background, or null to remove the
18121     *        background
18122     */
18123    public void setBackground(Drawable background) {
18124        //noinspection deprecation
18125        setBackgroundDrawable(background);
18126    }
18127
18128    /**
18129     * @deprecated use {@link #setBackground(Drawable)} instead
18130     */
18131    @Deprecated
18132    public void setBackgroundDrawable(Drawable background) {
18133        computeOpaqueFlags();
18134
18135        if (background == mBackground) {
18136            return;
18137        }
18138
18139        boolean requestLayout = false;
18140
18141        mBackgroundResource = 0;
18142
18143        /*
18144         * Regardless of whether we're setting a new background or not, we want
18145         * to clear the previous drawable. setVisible first while we still have the callback set.
18146         */
18147        if (mBackground != null) {
18148            if (isAttachedToWindow()) {
18149                mBackground.setVisible(false, false);
18150            }
18151            mBackground.setCallback(null);
18152            unscheduleDrawable(mBackground);
18153        }
18154
18155        if (background != null) {
18156            Rect padding = sThreadLocal.get();
18157            if (padding == null) {
18158                padding = new Rect();
18159                sThreadLocal.set(padding);
18160            }
18161            resetResolvedDrawablesInternal();
18162            background.setLayoutDirection(getLayoutDirection());
18163            if (background.getPadding(padding)) {
18164                resetResolvedPaddingInternal();
18165                switch (background.getLayoutDirection()) {
18166                    case LAYOUT_DIRECTION_RTL:
18167                        mUserPaddingLeftInitial = padding.right;
18168                        mUserPaddingRightInitial = padding.left;
18169                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
18170                        break;
18171                    case LAYOUT_DIRECTION_LTR:
18172                    default:
18173                        mUserPaddingLeftInitial = padding.left;
18174                        mUserPaddingRightInitial = padding.right;
18175                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
18176                }
18177                mLeftPaddingDefined = false;
18178                mRightPaddingDefined = false;
18179            }
18180
18181            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
18182            // if it has a different minimum size, we should layout again
18183            if (mBackground == null
18184                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
18185                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
18186                requestLayout = true;
18187            }
18188
18189            // Set mBackground before we set this as the callback and start making other
18190            // background drawable state change calls. In particular, the setVisible call below
18191            // can result in drawables attempting to start animations or otherwise invalidate,
18192            // which requires the view set as the callback (us) to recognize the drawable as
18193            // belonging to it as per verifyDrawable.
18194            mBackground = background;
18195            if (background.isStateful()) {
18196                background.setState(getDrawableState());
18197            }
18198            if (isAttachedToWindow()) {
18199                background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18200            }
18201
18202            applyBackgroundTint();
18203
18204            // Set callback last, since the view may still be initializing.
18205            background.setCallback(this);
18206
18207            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18208                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18209                requestLayout = true;
18210            }
18211        } else {
18212            /* Remove the background */
18213            mBackground = null;
18214            if ((mViewFlags & WILL_NOT_DRAW) != 0
18215                    && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {
18216                mPrivateFlags |= PFLAG_SKIP_DRAW;
18217            }
18218
18219            /*
18220             * When the background is set, we try to apply its padding to this
18221             * View. When the background is removed, we don't touch this View's
18222             * padding. This is noted in the Javadocs. Hence, we don't need to
18223             * requestLayout(), the invalidate() below is sufficient.
18224             */
18225
18226            // The old background's minimum size could have affected this
18227            // View's layout, so let's requestLayout
18228            requestLayout = true;
18229        }
18230
18231        computeOpaqueFlags();
18232
18233        if (requestLayout) {
18234            requestLayout();
18235        }
18236
18237        mBackgroundSizeChanged = true;
18238        invalidate(true);
18239        invalidateOutline();
18240    }
18241
18242    /**
18243     * Gets the background drawable
18244     *
18245     * @return The drawable used as the background for this view, if any.
18246     *
18247     * @see #setBackground(Drawable)
18248     *
18249     * @attr ref android.R.styleable#View_background
18250     */
18251    public Drawable getBackground() {
18252        return mBackground;
18253    }
18254
18255    /**
18256     * Applies a tint to the background drawable. Does not modify the current tint
18257     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18258     * <p>
18259     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
18260     * mutate the drawable and apply the specified tint and tint mode using
18261     * {@link Drawable#setTintList(ColorStateList)}.
18262     *
18263     * @param tint the tint to apply, may be {@code null} to clear tint
18264     *
18265     * @attr ref android.R.styleable#View_backgroundTint
18266     * @see #getBackgroundTintList()
18267     * @see Drawable#setTintList(ColorStateList)
18268     */
18269    public void setBackgroundTintList(@Nullable ColorStateList tint) {
18270        if (mBackgroundTint == null) {
18271            mBackgroundTint = new TintInfo();
18272        }
18273        mBackgroundTint.mTintList = tint;
18274        mBackgroundTint.mHasTintList = true;
18275
18276        applyBackgroundTint();
18277    }
18278
18279    /**
18280     * Return the tint applied to the background drawable, if specified.
18281     *
18282     * @return the tint applied to the background drawable
18283     * @attr ref android.R.styleable#View_backgroundTint
18284     * @see #setBackgroundTintList(ColorStateList)
18285     */
18286    @Nullable
18287    public ColorStateList getBackgroundTintList() {
18288        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
18289    }
18290
18291    /**
18292     * Specifies the blending mode used to apply the tint specified by
18293     * {@link #setBackgroundTintList(ColorStateList)}} to the background
18294     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18295     *
18296     * @param tintMode the blending mode used to apply the tint, may be
18297     *                 {@code null} to clear tint
18298     * @attr ref android.R.styleable#View_backgroundTintMode
18299     * @see #getBackgroundTintMode()
18300     * @see Drawable#setTintMode(PorterDuff.Mode)
18301     */
18302    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18303        if (mBackgroundTint == null) {
18304            mBackgroundTint = new TintInfo();
18305        }
18306        mBackgroundTint.mTintMode = tintMode;
18307        mBackgroundTint.mHasTintMode = true;
18308
18309        applyBackgroundTint();
18310    }
18311
18312    /**
18313     * Return the blending mode used to apply the tint to the background
18314     * drawable, if specified.
18315     *
18316     * @return the blending mode used to apply the tint to the background
18317     *         drawable
18318     * @attr ref android.R.styleable#View_backgroundTintMode
18319     * @see #setBackgroundTintMode(PorterDuff.Mode)
18320     */
18321    @Nullable
18322    public PorterDuff.Mode getBackgroundTintMode() {
18323        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
18324    }
18325
18326    private void applyBackgroundTint() {
18327        if (mBackground != null && mBackgroundTint != null) {
18328            final TintInfo tintInfo = mBackgroundTint;
18329            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18330                mBackground = mBackground.mutate();
18331
18332                if (tintInfo.mHasTintList) {
18333                    mBackground.setTintList(tintInfo.mTintList);
18334                }
18335
18336                if (tintInfo.mHasTintMode) {
18337                    mBackground.setTintMode(tintInfo.mTintMode);
18338                }
18339
18340                // The drawable (or one of its children) may not have been
18341                // stateful before applying the tint, so let's try again.
18342                if (mBackground.isStateful()) {
18343                    mBackground.setState(getDrawableState());
18344                }
18345            }
18346        }
18347    }
18348
18349    /**
18350     * Returns the drawable used as the foreground of this View. The
18351     * foreground drawable, if non-null, is always drawn on top of the view's content.
18352     *
18353     * @return a Drawable or null if no foreground was set
18354     *
18355     * @see #onDrawForeground(Canvas)
18356     */
18357    public Drawable getForeground() {
18358        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18359    }
18360
18361    /**
18362     * Supply a Drawable that is to be rendered on top of all of the content in the view.
18363     *
18364     * @param foreground the Drawable to be drawn on top of the children
18365     *
18366     * @attr ref android.R.styleable#View_foreground
18367     */
18368    public void setForeground(Drawable foreground) {
18369        if (mForegroundInfo == null) {
18370            if (foreground == null) {
18371                // Nothing to do.
18372                return;
18373            }
18374            mForegroundInfo = new ForegroundInfo();
18375        }
18376
18377        if (foreground == mForegroundInfo.mDrawable) {
18378            // Nothing to do
18379            return;
18380        }
18381
18382        if (mForegroundInfo.mDrawable != null) {
18383            if (isAttachedToWindow()) {
18384                mForegroundInfo.mDrawable.setVisible(false, false);
18385            }
18386            mForegroundInfo.mDrawable.setCallback(null);
18387            unscheduleDrawable(mForegroundInfo.mDrawable);
18388        }
18389
18390        mForegroundInfo.mDrawable = foreground;
18391        mForegroundInfo.mBoundsChanged = true;
18392        if (foreground != null) {
18393            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
18394                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
18395            }
18396            foreground.setLayoutDirection(getLayoutDirection());
18397            if (foreground.isStateful()) {
18398                foreground.setState(getDrawableState());
18399            }
18400            applyForegroundTint();
18401            if (isAttachedToWindow()) {
18402                foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);
18403            }
18404            // Set callback last, since the view may still be initializing.
18405            foreground.setCallback(this);
18406        } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) {
18407            mPrivateFlags |= PFLAG_SKIP_DRAW;
18408        }
18409        requestLayout();
18410        invalidate();
18411    }
18412
18413    /**
18414     * Magic bit used to support features of framework-internal window decor implementation details.
18415     * This used to live exclusively in FrameLayout.
18416     *
18417     * @return true if the foreground should draw inside the padding region or false
18418     *         if it should draw inset by the view's padding
18419     * @hide internal use only; only used by FrameLayout and internal screen layouts.
18420     */
18421    public boolean isForegroundInsidePadding() {
18422        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
18423    }
18424
18425    /**
18426     * Describes how the foreground is positioned.
18427     *
18428     * @return foreground gravity.
18429     *
18430     * @see #setForegroundGravity(int)
18431     *
18432     * @attr ref android.R.styleable#View_foregroundGravity
18433     */
18434    public int getForegroundGravity() {
18435        return mForegroundInfo != null ? mForegroundInfo.mGravity
18436                : Gravity.START | Gravity.TOP;
18437    }
18438
18439    /**
18440     * Describes how the foreground is positioned. Defaults to START and TOP.
18441     *
18442     * @param gravity see {@link android.view.Gravity}
18443     *
18444     * @see #getForegroundGravity()
18445     *
18446     * @attr ref android.R.styleable#View_foregroundGravity
18447     */
18448    public void setForegroundGravity(int gravity) {
18449        if (mForegroundInfo == null) {
18450            mForegroundInfo = new ForegroundInfo();
18451        }
18452
18453        if (mForegroundInfo.mGravity != gravity) {
18454            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
18455                gravity |= Gravity.START;
18456            }
18457
18458            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
18459                gravity |= Gravity.TOP;
18460            }
18461
18462            mForegroundInfo.mGravity = gravity;
18463            requestLayout();
18464        }
18465    }
18466
18467    /**
18468     * Applies a tint to the foreground drawable. Does not modify the current tint
18469     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
18470     * <p>
18471     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
18472     * mutate the drawable and apply the specified tint and tint mode using
18473     * {@link Drawable#setTintList(ColorStateList)}.
18474     *
18475     * @param tint the tint to apply, may be {@code null} to clear tint
18476     *
18477     * @attr ref android.R.styleable#View_foregroundTint
18478     * @see #getForegroundTintList()
18479     * @see Drawable#setTintList(ColorStateList)
18480     */
18481    public void setForegroundTintList(@Nullable ColorStateList tint) {
18482        if (mForegroundInfo == null) {
18483            mForegroundInfo = new ForegroundInfo();
18484        }
18485        if (mForegroundInfo.mTintInfo == null) {
18486            mForegroundInfo.mTintInfo = new TintInfo();
18487        }
18488        mForegroundInfo.mTintInfo.mTintList = tint;
18489        mForegroundInfo.mTintInfo.mHasTintList = true;
18490
18491        applyForegroundTint();
18492    }
18493
18494    /**
18495     * Return the tint applied to the foreground drawable, if specified.
18496     *
18497     * @return the tint applied to the foreground drawable
18498     * @attr ref android.R.styleable#View_foregroundTint
18499     * @see #setForegroundTintList(ColorStateList)
18500     */
18501    @Nullable
18502    public ColorStateList getForegroundTintList() {
18503        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18504                ? mForegroundInfo.mTintInfo.mTintList : null;
18505    }
18506
18507    /**
18508     * Specifies the blending mode used to apply the tint specified by
18509     * {@link #setForegroundTintList(ColorStateList)}} to the background
18510     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
18511     *
18512     * @param tintMode the blending mode used to apply the tint, may be
18513     *                 {@code null} to clear tint
18514     * @attr ref android.R.styleable#View_foregroundTintMode
18515     * @see #getForegroundTintMode()
18516     * @see Drawable#setTintMode(PorterDuff.Mode)
18517     */
18518    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
18519        if (mForegroundInfo == null) {
18520            mForegroundInfo = new ForegroundInfo();
18521        }
18522        if (mForegroundInfo.mTintInfo == null) {
18523            mForegroundInfo.mTintInfo = new TintInfo();
18524        }
18525        mForegroundInfo.mTintInfo.mTintMode = tintMode;
18526        mForegroundInfo.mTintInfo.mHasTintMode = true;
18527
18528        applyForegroundTint();
18529    }
18530
18531    /**
18532     * Return the blending mode used to apply the tint to the foreground
18533     * drawable, if specified.
18534     *
18535     * @return the blending mode used to apply the tint to the foreground
18536     *         drawable
18537     * @attr ref android.R.styleable#View_foregroundTintMode
18538     * @see #setForegroundTintMode(PorterDuff.Mode)
18539     */
18540    @Nullable
18541    public PorterDuff.Mode getForegroundTintMode() {
18542        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
18543                ? mForegroundInfo.mTintInfo.mTintMode : null;
18544    }
18545
18546    private void applyForegroundTint() {
18547        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
18548                && mForegroundInfo.mTintInfo != null) {
18549            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
18550            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
18551                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
18552
18553                if (tintInfo.mHasTintList) {
18554                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
18555                }
18556
18557                if (tintInfo.mHasTintMode) {
18558                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
18559                }
18560
18561                // The drawable (or one of its children) may not have been
18562                // stateful before applying the tint, so let's try again.
18563                if (mForegroundInfo.mDrawable.isStateful()) {
18564                    mForegroundInfo.mDrawable.setState(getDrawableState());
18565                }
18566            }
18567        }
18568    }
18569
18570    /**
18571     * Draw any foreground content for this view.
18572     *
18573     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
18574     * drawable or other view-specific decorations. The foreground is drawn on top of the
18575     * primary view content.</p>
18576     *
18577     * @param canvas canvas to draw into
18578     */
18579    public void onDrawForeground(Canvas canvas) {
18580        onDrawScrollIndicators(canvas);
18581        onDrawScrollBars(canvas);
18582
18583        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18584        if (foreground != null) {
18585            if (mForegroundInfo.mBoundsChanged) {
18586                mForegroundInfo.mBoundsChanged = false;
18587                final Rect selfBounds = mForegroundInfo.mSelfBounds;
18588                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
18589
18590                if (mForegroundInfo.mInsidePadding) {
18591                    selfBounds.set(0, 0, getWidth(), getHeight());
18592                } else {
18593                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
18594                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
18595                }
18596
18597                final int ld = getLayoutDirection();
18598                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
18599                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
18600                foreground.setBounds(overlayBounds);
18601            }
18602
18603            foreground.draw(canvas);
18604        }
18605    }
18606
18607    /**
18608     * Sets the padding. The view may add on the space required to display
18609     * the scrollbars, depending on the style and visibility of the scrollbars.
18610     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
18611     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
18612     * from the values set in this call.
18613     *
18614     * @attr ref android.R.styleable#View_padding
18615     * @attr ref android.R.styleable#View_paddingBottom
18616     * @attr ref android.R.styleable#View_paddingLeft
18617     * @attr ref android.R.styleable#View_paddingRight
18618     * @attr ref android.R.styleable#View_paddingTop
18619     * @param left the left padding in pixels
18620     * @param top the top padding in pixels
18621     * @param right the right padding in pixels
18622     * @param bottom the bottom padding in pixels
18623     */
18624    public void setPadding(int left, int top, int right, int bottom) {
18625        resetResolvedPaddingInternal();
18626
18627        mUserPaddingStart = UNDEFINED_PADDING;
18628        mUserPaddingEnd = UNDEFINED_PADDING;
18629
18630        mUserPaddingLeftInitial = left;
18631        mUserPaddingRightInitial = right;
18632
18633        mLeftPaddingDefined = true;
18634        mRightPaddingDefined = true;
18635
18636        internalSetPadding(left, top, right, bottom);
18637    }
18638
18639    /**
18640     * @hide
18641     */
18642    protected void internalSetPadding(int left, int top, int right, int bottom) {
18643        mUserPaddingLeft = left;
18644        mUserPaddingRight = right;
18645        mUserPaddingBottom = bottom;
18646
18647        final int viewFlags = mViewFlags;
18648        boolean changed = false;
18649
18650        // Common case is there are no scroll bars.
18651        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
18652            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
18653                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
18654                        ? 0 : getVerticalScrollbarWidth();
18655                switch (mVerticalScrollbarPosition) {
18656                    case SCROLLBAR_POSITION_DEFAULT:
18657                        if (isLayoutRtl()) {
18658                            left += offset;
18659                        } else {
18660                            right += offset;
18661                        }
18662                        break;
18663                    case SCROLLBAR_POSITION_RIGHT:
18664                        right += offset;
18665                        break;
18666                    case SCROLLBAR_POSITION_LEFT:
18667                        left += offset;
18668                        break;
18669                }
18670            }
18671            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
18672                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
18673                        ? 0 : getHorizontalScrollbarHeight();
18674            }
18675        }
18676
18677        if (mPaddingLeft != left) {
18678            changed = true;
18679            mPaddingLeft = left;
18680        }
18681        if (mPaddingTop != top) {
18682            changed = true;
18683            mPaddingTop = top;
18684        }
18685        if (mPaddingRight != right) {
18686            changed = true;
18687            mPaddingRight = right;
18688        }
18689        if (mPaddingBottom != bottom) {
18690            changed = true;
18691            mPaddingBottom = bottom;
18692        }
18693
18694        if (changed) {
18695            requestLayout();
18696            invalidateOutline();
18697        }
18698    }
18699
18700    /**
18701     * Sets the relative padding. The view may add on the space required to display
18702     * the scrollbars, depending on the style and visibility of the scrollbars.
18703     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
18704     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
18705     * from the values set in this call.
18706     *
18707     * @attr ref android.R.styleable#View_padding
18708     * @attr ref android.R.styleable#View_paddingBottom
18709     * @attr ref android.R.styleable#View_paddingStart
18710     * @attr ref android.R.styleable#View_paddingEnd
18711     * @attr ref android.R.styleable#View_paddingTop
18712     * @param start the start padding in pixels
18713     * @param top the top padding in pixels
18714     * @param end the end padding in pixels
18715     * @param bottom the bottom padding in pixels
18716     */
18717    public void setPaddingRelative(int start, int top, int end, int bottom) {
18718        resetResolvedPaddingInternal();
18719
18720        mUserPaddingStart = start;
18721        mUserPaddingEnd = end;
18722        mLeftPaddingDefined = true;
18723        mRightPaddingDefined = true;
18724
18725        switch(getLayoutDirection()) {
18726            case LAYOUT_DIRECTION_RTL:
18727                mUserPaddingLeftInitial = end;
18728                mUserPaddingRightInitial = start;
18729                internalSetPadding(end, top, start, bottom);
18730                break;
18731            case LAYOUT_DIRECTION_LTR:
18732            default:
18733                mUserPaddingLeftInitial = start;
18734                mUserPaddingRightInitial = end;
18735                internalSetPadding(start, top, end, bottom);
18736        }
18737    }
18738
18739    /**
18740     * Returns the top padding of this view.
18741     *
18742     * @return the top padding in pixels
18743     */
18744    public int getPaddingTop() {
18745        return mPaddingTop;
18746    }
18747
18748    /**
18749     * Returns the bottom padding of this view. If there are inset and enabled
18750     * scrollbars, this value may include the space required to display the
18751     * scrollbars as well.
18752     *
18753     * @return the bottom padding in pixels
18754     */
18755    public int getPaddingBottom() {
18756        return mPaddingBottom;
18757    }
18758
18759    /**
18760     * Returns the left padding of this view. If there are inset and enabled
18761     * scrollbars, this value may include the space required to display the
18762     * scrollbars as well.
18763     *
18764     * @return the left padding in pixels
18765     */
18766    public int getPaddingLeft() {
18767        if (!isPaddingResolved()) {
18768            resolvePadding();
18769        }
18770        return mPaddingLeft;
18771    }
18772
18773    /**
18774     * Returns the start padding of this view depending on its resolved layout direction.
18775     * If there are inset and enabled scrollbars, this value may include the space
18776     * required to display the scrollbars as well.
18777     *
18778     * @return the start padding in pixels
18779     */
18780    public int getPaddingStart() {
18781        if (!isPaddingResolved()) {
18782            resolvePadding();
18783        }
18784        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18785                mPaddingRight : mPaddingLeft;
18786    }
18787
18788    /**
18789     * Returns the right padding of this view. If there are inset and enabled
18790     * scrollbars, this value may include the space required to display the
18791     * scrollbars as well.
18792     *
18793     * @return the right padding in pixels
18794     */
18795    public int getPaddingRight() {
18796        if (!isPaddingResolved()) {
18797            resolvePadding();
18798        }
18799        return mPaddingRight;
18800    }
18801
18802    /**
18803     * Returns the end padding of this view depending on its resolved layout direction.
18804     * If there are inset and enabled scrollbars, this value may include the space
18805     * required to display the scrollbars as well.
18806     *
18807     * @return the end padding in pixels
18808     */
18809    public int getPaddingEnd() {
18810        if (!isPaddingResolved()) {
18811            resolvePadding();
18812        }
18813        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
18814                mPaddingLeft : mPaddingRight;
18815    }
18816
18817    /**
18818     * Return if the padding has been set through relative values
18819     * {@link #setPaddingRelative(int, int, int, int)} or through
18820     * @attr ref android.R.styleable#View_paddingStart or
18821     * @attr ref android.R.styleable#View_paddingEnd
18822     *
18823     * @return true if the padding is relative or false if it is not.
18824     */
18825    public boolean isPaddingRelative() {
18826        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
18827    }
18828
18829    Insets computeOpticalInsets() {
18830        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
18831    }
18832
18833    /**
18834     * @hide
18835     */
18836    public void resetPaddingToInitialValues() {
18837        if (isRtlCompatibilityMode()) {
18838            mPaddingLeft = mUserPaddingLeftInitial;
18839            mPaddingRight = mUserPaddingRightInitial;
18840            return;
18841        }
18842        if (isLayoutRtl()) {
18843            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
18844            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
18845        } else {
18846            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
18847            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
18848        }
18849    }
18850
18851    /**
18852     * @hide
18853     */
18854    public Insets getOpticalInsets() {
18855        if (mLayoutInsets == null) {
18856            mLayoutInsets = computeOpticalInsets();
18857        }
18858        return mLayoutInsets;
18859    }
18860
18861    /**
18862     * Set this view's optical insets.
18863     *
18864     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
18865     * property. Views that compute their own optical insets should call it as part of measurement.
18866     * This method does not request layout. If you are setting optical insets outside of
18867     * measure/layout itself you will want to call requestLayout() yourself.
18868     * </p>
18869     * @hide
18870     */
18871    public void setOpticalInsets(Insets insets) {
18872        mLayoutInsets = insets;
18873    }
18874
18875    /**
18876     * Changes the selection state of this view. A view can be selected or not.
18877     * Note that selection is not the same as focus. Views are typically
18878     * selected in the context of an AdapterView like ListView or GridView;
18879     * the selected view is the view that is highlighted.
18880     *
18881     * @param selected true if the view must be selected, false otherwise
18882     */
18883    public void setSelected(boolean selected) {
18884        //noinspection DoubleNegation
18885        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
18886            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
18887            if (!selected) resetPressedState();
18888            invalidate(true);
18889            refreshDrawableState();
18890            dispatchSetSelected(selected);
18891            if (selected) {
18892                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
18893            } else {
18894                notifyViewAccessibilityStateChangedIfNeeded(
18895                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
18896            }
18897        }
18898    }
18899
18900    /**
18901     * Dispatch setSelected to all of this View's children.
18902     *
18903     * @see #setSelected(boolean)
18904     *
18905     * @param selected The new selected state
18906     */
18907    protected void dispatchSetSelected(boolean selected) {
18908    }
18909
18910    /**
18911     * Indicates the selection state of this view.
18912     *
18913     * @return true if the view is selected, false otherwise
18914     */
18915    @ViewDebug.ExportedProperty
18916    public boolean isSelected() {
18917        return (mPrivateFlags & PFLAG_SELECTED) != 0;
18918    }
18919
18920    /**
18921     * Changes the activated state of this view. A view can be activated or not.
18922     * Note that activation is not the same as selection.  Selection is
18923     * a transient property, representing the view (hierarchy) the user is
18924     * currently interacting with.  Activation is a longer-term state that the
18925     * user can move views in and out of.  For example, in a list view with
18926     * single or multiple selection enabled, the views in the current selection
18927     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
18928     * here.)  The activated state is propagated down to children of the view it
18929     * is set on.
18930     *
18931     * @param activated true if the view must be activated, false otherwise
18932     */
18933    public void setActivated(boolean activated) {
18934        //noinspection DoubleNegation
18935        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
18936            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
18937            invalidate(true);
18938            refreshDrawableState();
18939            dispatchSetActivated(activated);
18940        }
18941    }
18942
18943    /**
18944     * Dispatch setActivated to all of this View's children.
18945     *
18946     * @see #setActivated(boolean)
18947     *
18948     * @param activated The new activated state
18949     */
18950    protected void dispatchSetActivated(boolean activated) {
18951    }
18952
18953    /**
18954     * Indicates the activation state of this view.
18955     *
18956     * @return true if the view is activated, false otherwise
18957     */
18958    @ViewDebug.ExportedProperty
18959    public boolean isActivated() {
18960        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
18961    }
18962
18963    /**
18964     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
18965     * observer can be used to get notifications when global events, like
18966     * layout, happen.
18967     *
18968     * The returned ViewTreeObserver observer is not guaranteed to remain
18969     * valid for the lifetime of this View. If the caller of this method keeps
18970     * a long-lived reference to ViewTreeObserver, it should always check for
18971     * the return value of {@link ViewTreeObserver#isAlive()}.
18972     *
18973     * @return The ViewTreeObserver for this view's hierarchy.
18974     */
18975    public ViewTreeObserver getViewTreeObserver() {
18976        if (mAttachInfo != null) {
18977            return mAttachInfo.mTreeObserver;
18978        }
18979        if (mFloatingTreeObserver == null) {
18980            mFloatingTreeObserver = new ViewTreeObserver();
18981        }
18982        return mFloatingTreeObserver;
18983    }
18984
18985    /**
18986     * <p>Finds the topmost view in the current view hierarchy.</p>
18987     *
18988     * @return the topmost view containing this view
18989     */
18990    public View getRootView() {
18991        if (mAttachInfo != null) {
18992            final View v = mAttachInfo.mRootView;
18993            if (v != null) {
18994                return v;
18995            }
18996        }
18997
18998        View parent = this;
18999
19000        while (parent.mParent != null && parent.mParent instanceof View) {
19001            parent = (View) parent.mParent;
19002        }
19003
19004        return parent;
19005    }
19006
19007    /**
19008     * Transforms a motion event from view-local coordinates to on-screen
19009     * coordinates.
19010     *
19011     * @param ev the view-local motion event
19012     * @return false if the transformation could not be applied
19013     * @hide
19014     */
19015    public boolean toGlobalMotionEvent(MotionEvent ev) {
19016        final AttachInfo info = mAttachInfo;
19017        if (info == null) {
19018            return false;
19019        }
19020
19021        final Matrix m = info.mTmpMatrix;
19022        m.set(Matrix.IDENTITY_MATRIX);
19023        transformMatrixToGlobal(m);
19024        ev.transform(m);
19025        return true;
19026    }
19027
19028    /**
19029     * Transforms a motion event from on-screen coordinates to view-local
19030     * coordinates.
19031     *
19032     * @param ev the on-screen motion event
19033     * @return false if the transformation could not be applied
19034     * @hide
19035     */
19036    public boolean toLocalMotionEvent(MotionEvent ev) {
19037        final AttachInfo info = mAttachInfo;
19038        if (info == null) {
19039            return false;
19040        }
19041
19042        final Matrix m = info.mTmpMatrix;
19043        m.set(Matrix.IDENTITY_MATRIX);
19044        transformMatrixToLocal(m);
19045        ev.transform(m);
19046        return true;
19047    }
19048
19049    /**
19050     * Modifies the input matrix such that it maps view-local coordinates to
19051     * on-screen coordinates.
19052     *
19053     * @param m input matrix to modify
19054     * @hide
19055     */
19056    public void transformMatrixToGlobal(Matrix m) {
19057        final ViewParent parent = mParent;
19058        if (parent instanceof View) {
19059            final View vp = (View) parent;
19060            vp.transformMatrixToGlobal(m);
19061            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
19062        } else if (parent instanceof ViewRootImpl) {
19063            final ViewRootImpl vr = (ViewRootImpl) parent;
19064            vr.transformMatrixToGlobal(m);
19065            m.preTranslate(0, -vr.mCurScrollY);
19066        }
19067
19068        m.preTranslate(mLeft, mTop);
19069
19070        if (!hasIdentityMatrix()) {
19071            m.preConcat(getMatrix());
19072        }
19073    }
19074
19075    /**
19076     * Modifies the input matrix such that it maps on-screen coordinates to
19077     * view-local coordinates.
19078     *
19079     * @param m input matrix to modify
19080     * @hide
19081     */
19082    public void transformMatrixToLocal(Matrix m) {
19083        final ViewParent parent = mParent;
19084        if (parent instanceof View) {
19085            final View vp = (View) parent;
19086            vp.transformMatrixToLocal(m);
19087            m.postTranslate(vp.mScrollX, vp.mScrollY);
19088        } else if (parent instanceof ViewRootImpl) {
19089            final ViewRootImpl vr = (ViewRootImpl) parent;
19090            vr.transformMatrixToLocal(m);
19091            m.postTranslate(0, vr.mCurScrollY);
19092        }
19093
19094        m.postTranslate(-mLeft, -mTop);
19095
19096        if (!hasIdentityMatrix()) {
19097            m.postConcat(getInverseMatrix());
19098        }
19099    }
19100
19101    /**
19102     * @hide
19103     */
19104    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
19105            @ViewDebug.IntToString(from = 0, to = "x"),
19106            @ViewDebug.IntToString(from = 1, to = "y")
19107    })
19108    public int[] getLocationOnScreen() {
19109        int[] location = new int[2];
19110        getLocationOnScreen(location);
19111        return location;
19112    }
19113
19114    /**
19115     * <p>Computes the coordinates of this view on the screen. The argument
19116     * must be an array of two integers. After the method returns, the array
19117     * contains the x and y location in that order.</p>
19118     *
19119     * @param outLocation an array of two integers in which to hold the coordinates
19120     */
19121    public void getLocationOnScreen(@Size(2) int[] outLocation) {
19122        getLocationInWindow(outLocation);
19123
19124        final AttachInfo info = mAttachInfo;
19125        if (info != null) {
19126            outLocation[0] += info.mWindowLeft;
19127            outLocation[1] += info.mWindowTop;
19128        }
19129    }
19130
19131    /**
19132     * <p>Computes the coordinates of this view in its window. The argument
19133     * must be an array of two integers. After the method returns, the array
19134     * contains the x and y location in that order.</p>
19135     *
19136     * @param outLocation an array of two integers in which to hold the coordinates
19137     */
19138    public void getLocationInWindow(@Size(2) int[] outLocation) {
19139        if (outLocation == null || outLocation.length < 2) {
19140            throw new IllegalArgumentException("outLocation must be an array of two integers");
19141        }
19142
19143        outLocation[0] = 0;
19144        outLocation[1] = 0;
19145
19146        transformFromViewToWindowSpace(outLocation);
19147    }
19148
19149    /** @hide */
19150    public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) {
19151        if (inOutLocation == null || inOutLocation.length < 2) {
19152            throw new IllegalArgumentException("inOutLocation must be an array of two integers");
19153        }
19154
19155        if (mAttachInfo == null) {
19156            // When the view is not attached to a window, this method does not make sense
19157            inOutLocation[0] = inOutLocation[1] = 0;
19158            return;
19159        }
19160
19161        float position[] = mAttachInfo.mTmpTransformLocation;
19162        position[0] = inOutLocation[0];
19163        position[1] = inOutLocation[1];
19164
19165        if (!hasIdentityMatrix()) {
19166            getMatrix().mapPoints(position);
19167        }
19168
19169        position[0] += mLeft;
19170        position[1] += mTop;
19171
19172        ViewParent viewParent = mParent;
19173        while (viewParent instanceof View) {
19174            final View view = (View) viewParent;
19175
19176            position[0] -= view.mScrollX;
19177            position[1] -= view.mScrollY;
19178
19179            if (!view.hasIdentityMatrix()) {
19180                view.getMatrix().mapPoints(position);
19181            }
19182
19183            position[0] += view.mLeft;
19184            position[1] += view.mTop;
19185
19186            viewParent = view.mParent;
19187         }
19188
19189        if (viewParent instanceof ViewRootImpl) {
19190            // *cough*
19191            final ViewRootImpl vr = (ViewRootImpl) viewParent;
19192            position[1] -= vr.mCurScrollY;
19193        }
19194
19195        inOutLocation[0] = Math.round(position[0]);
19196        inOutLocation[1] = Math.round(position[1]);
19197    }
19198
19199    /**
19200     * {@hide}
19201     * @param id the id of the view to be found
19202     * @return the view of the specified id, null if cannot be found
19203     */
19204    protected View findViewTraversal(@IdRes int id) {
19205        if (id == mID) {
19206            return this;
19207        }
19208        return null;
19209    }
19210
19211    /**
19212     * {@hide}
19213     * @param tag the tag of the view to be found
19214     * @return the view of specified tag, null if cannot be found
19215     */
19216    protected View findViewWithTagTraversal(Object tag) {
19217        if (tag != null && tag.equals(mTag)) {
19218            return this;
19219        }
19220        return null;
19221    }
19222
19223    /**
19224     * {@hide}
19225     * @param predicate The predicate to evaluate.
19226     * @param childToSkip If not null, ignores this child during the recursive traversal.
19227     * @return The first view that matches the predicate or null.
19228     */
19229    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
19230        if (predicate.apply(this)) {
19231            return this;
19232        }
19233        return null;
19234    }
19235
19236    /**
19237     * Look for a child view with the given id.  If this view has the given
19238     * id, return this view.
19239     *
19240     * @param id The id to search for.
19241     * @return The view that has the given id in the hierarchy or null
19242     */
19243    @Nullable
19244    public final View findViewById(@IdRes int id) {
19245        if (id < 0) {
19246            return null;
19247        }
19248        return findViewTraversal(id);
19249    }
19250
19251    /**
19252     * Finds a view by its unuque and stable accessibility id.
19253     *
19254     * @param accessibilityId The searched accessibility id.
19255     * @return The found view.
19256     */
19257    final View findViewByAccessibilityId(int accessibilityId) {
19258        if (accessibilityId < 0) {
19259            return null;
19260        }
19261        View view = findViewByAccessibilityIdTraversal(accessibilityId);
19262        if (view != null) {
19263            return view.includeForAccessibility() ? view : null;
19264        }
19265        return null;
19266    }
19267
19268    /**
19269     * Performs the traversal to find a view by its unuque and stable accessibility id.
19270     *
19271     * <strong>Note:</strong>This method does not stop at the root namespace
19272     * boundary since the user can touch the screen at an arbitrary location
19273     * potentially crossing the root namespace bounday which will send an
19274     * accessibility event to accessibility services and they should be able
19275     * to obtain the event source. Also accessibility ids are guaranteed to be
19276     * unique in the window.
19277     *
19278     * @param accessibilityId The accessibility id.
19279     * @return The found view.
19280     *
19281     * @hide
19282     */
19283    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
19284        if (getAccessibilityViewId() == accessibilityId) {
19285            return this;
19286        }
19287        return null;
19288    }
19289
19290    /**
19291     * Look for a child view with the given tag.  If this view has the given
19292     * tag, return this view.
19293     *
19294     * @param tag The tag to search for, using "tag.equals(getTag())".
19295     * @return The View that has the given tag in the hierarchy or null
19296     */
19297    public final View findViewWithTag(Object tag) {
19298        if (tag == null) {
19299            return null;
19300        }
19301        return findViewWithTagTraversal(tag);
19302    }
19303
19304    /**
19305     * {@hide}
19306     * Look for a child view that matches the specified predicate.
19307     * If this view matches the predicate, return this view.
19308     *
19309     * @param predicate The predicate to evaluate.
19310     * @return The first view that matches the predicate or null.
19311     */
19312    public final View findViewByPredicate(Predicate<View> predicate) {
19313        return findViewByPredicateTraversal(predicate, null);
19314    }
19315
19316    /**
19317     * {@hide}
19318     * Look for a child view that matches the specified predicate,
19319     * starting with the specified view and its descendents and then
19320     * recusively searching the ancestors and siblings of that view
19321     * until this view is reached.
19322     *
19323     * This method is useful in cases where the predicate does not match
19324     * a single unique view (perhaps multiple views use the same id)
19325     * and we are trying to find the view that is "closest" in scope to the
19326     * starting view.
19327     *
19328     * @param start The view to start from.
19329     * @param predicate The predicate to evaluate.
19330     * @return The first view that matches the predicate or null.
19331     */
19332    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
19333        View childToSkip = null;
19334        for (;;) {
19335            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
19336            if (view != null || start == this) {
19337                return view;
19338            }
19339
19340            ViewParent parent = start.getParent();
19341            if (parent == null || !(parent instanceof View)) {
19342                return null;
19343            }
19344
19345            childToSkip = start;
19346            start = (View) parent;
19347        }
19348    }
19349
19350    /**
19351     * Sets the identifier for this view. The identifier does not have to be
19352     * unique in this view's hierarchy. The identifier should be a positive
19353     * number.
19354     *
19355     * @see #NO_ID
19356     * @see #getId()
19357     * @see #findViewById(int)
19358     *
19359     * @param id a number used to identify the view
19360     *
19361     * @attr ref android.R.styleable#View_id
19362     */
19363    public void setId(@IdRes int id) {
19364        mID = id;
19365        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
19366            mID = generateViewId();
19367        }
19368    }
19369
19370    /**
19371     * {@hide}
19372     *
19373     * @param isRoot true if the view belongs to the root namespace, false
19374     *        otherwise
19375     */
19376    public void setIsRootNamespace(boolean isRoot) {
19377        if (isRoot) {
19378            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
19379        } else {
19380            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
19381        }
19382    }
19383
19384    /**
19385     * {@hide}
19386     *
19387     * @return true if the view belongs to the root namespace, false otherwise
19388     */
19389    public boolean isRootNamespace() {
19390        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
19391    }
19392
19393    /**
19394     * Returns this view's identifier.
19395     *
19396     * @return a positive integer used to identify the view or {@link #NO_ID}
19397     *         if the view has no ID
19398     *
19399     * @see #setId(int)
19400     * @see #findViewById(int)
19401     * @attr ref android.R.styleable#View_id
19402     */
19403    @IdRes
19404    @ViewDebug.CapturedViewProperty
19405    public int getId() {
19406        return mID;
19407    }
19408
19409    /**
19410     * Returns this view's tag.
19411     *
19412     * @return the Object stored in this view as a tag, or {@code null} if not
19413     *         set
19414     *
19415     * @see #setTag(Object)
19416     * @see #getTag(int)
19417     */
19418    @ViewDebug.ExportedProperty
19419    public Object getTag() {
19420        return mTag;
19421    }
19422
19423    /**
19424     * Sets the tag associated with this view. A tag can be used to mark
19425     * a view in its hierarchy and does not have to be unique within the
19426     * hierarchy. Tags can also be used to store data within a view without
19427     * resorting to another data structure.
19428     *
19429     * @param tag an Object to tag the view with
19430     *
19431     * @see #getTag()
19432     * @see #setTag(int, Object)
19433     */
19434    public void setTag(final Object tag) {
19435        mTag = tag;
19436    }
19437
19438    /**
19439     * Returns the tag associated with this view and the specified key.
19440     *
19441     * @param key The key identifying the tag
19442     *
19443     * @return the Object stored in this view as a tag, or {@code null} if not
19444     *         set
19445     *
19446     * @see #setTag(int, Object)
19447     * @see #getTag()
19448     */
19449    public Object getTag(int key) {
19450        if (mKeyedTags != null) return mKeyedTags.get(key);
19451        return null;
19452    }
19453
19454    /**
19455     * Sets a tag associated with this view and a key. A tag can be used
19456     * to mark a view in its hierarchy and does not have to be unique within
19457     * the hierarchy. Tags can also be used to store data within a view
19458     * without resorting to another data structure.
19459     *
19460     * The specified key should be an id declared in the resources of the
19461     * application to ensure it is unique (see the <a
19462     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
19463     * Keys identified as belonging to
19464     * the Android framework or not associated with any package will cause
19465     * an {@link IllegalArgumentException} to be thrown.
19466     *
19467     * @param key The key identifying the tag
19468     * @param tag An Object to tag the view with
19469     *
19470     * @throws IllegalArgumentException If they specified key is not valid
19471     *
19472     * @see #setTag(Object)
19473     * @see #getTag(int)
19474     */
19475    public void setTag(int key, final Object tag) {
19476        // If the package id is 0x00 or 0x01, it's either an undefined package
19477        // or a framework id
19478        if ((key >>> 24) < 2) {
19479            throw new IllegalArgumentException("The key must be an application-specific "
19480                    + "resource id.");
19481        }
19482
19483        setKeyedTag(key, tag);
19484    }
19485
19486    /**
19487     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
19488     * framework id.
19489     *
19490     * @hide
19491     */
19492    public void setTagInternal(int key, Object tag) {
19493        if ((key >>> 24) != 0x1) {
19494            throw new IllegalArgumentException("The key must be a framework-specific "
19495                    + "resource id.");
19496        }
19497
19498        setKeyedTag(key, tag);
19499    }
19500
19501    private void setKeyedTag(int key, Object tag) {
19502        if (mKeyedTags == null) {
19503            mKeyedTags = new SparseArray<Object>(2);
19504        }
19505
19506        mKeyedTags.put(key, tag);
19507    }
19508
19509    /**
19510     * Prints information about this view in the log output, with the tag
19511     * {@link #VIEW_LOG_TAG}.
19512     *
19513     * @hide
19514     */
19515    public void debug() {
19516        debug(0);
19517    }
19518
19519    /**
19520     * Prints information about this view in the log output, with the tag
19521     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
19522     * indentation defined by the <code>depth</code>.
19523     *
19524     * @param depth the indentation level
19525     *
19526     * @hide
19527     */
19528    protected void debug(int depth) {
19529        String output = debugIndent(depth - 1);
19530
19531        output += "+ " + this;
19532        int id = getId();
19533        if (id != -1) {
19534            output += " (id=" + id + ")";
19535        }
19536        Object tag = getTag();
19537        if (tag != null) {
19538            output += " (tag=" + tag + ")";
19539        }
19540        Log.d(VIEW_LOG_TAG, output);
19541
19542        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
19543            output = debugIndent(depth) + " FOCUSED";
19544            Log.d(VIEW_LOG_TAG, output);
19545        }
19546
19547        output = debugIndent(depth);
19548        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
19549                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
19550                + "} ";
19551        Log.d(VIEW_LOG_TAG, output);
19552
19553        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
19554                || mPaddingBottom != 0) {
19555            output = debugIndent(depth);
19556            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
19557                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
19558            Log.d(VIEW_LOG_TAG, output);
19559        }
19560
19561        output = debugIndent(depth);
19562        output += "mMeasureWidth=" + mMeasuredWidth +
19563                " mMeasureHeight=" + mMeasuredHeight;
19564        Log.d(VIEW_LOG_TAG, output);
19565
19566        output = debugIndent(depth);
19567        if (mLayoutParams == null) {
19568            output += "BAD! no layout params";
19569        } else {
19570            output = mLayoutParams.debug(output);
19571        }
19572        Log.d(VIEW_LOG_TAG, output);
19573
19574        output = debugIndent(depth);
19575        output += "flags={";
19576        output += View.printFlags(mViewFlags);
19577        output += "}";
19578        Log.d(VIEW_LOG_TAG, output);
19579
19580        output = debugIndent(depth);
19581        output += "privateFlags={";
19582        output += View.printPrivateFlags(mPrivateFlags);
19583        output += "}";
19584        Log.d(VIEW_LOG_TAG, output);
19585    }
19586
19587    /**
19588     * Creates a string of whitespaces used for indentation.
19589     *
19590     * @param depth the indentation level
19591     * @return a String containing (depth * 2 + 3) * 2 white spaces
19592     *
19593     * @hide
19594     */
19595    protected static String debugIndent(int depth) {
19596        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
19597        for (int i = 0; i < (depth * 2) + 3; i++) {
19598            spaces.append(' ').append(' ');
19599        }
19600        return spaces.toString();
19601    }
19602
19603    /**
19604     * <p>Return the offset of the widget's text baseline from the widget's top
19605     * boundary. If this widget does not support baseline alignment, this
19606     * method returns -1. </p>
19607     *
19608     * @return the offset of the baseline within the widget's bounds or -1
19609     *         if baseline alignment is not supported
19610     */
19611    @ViewDebug.ExportedProperty(category = "layout")
19612    public int getBaseline() {
19613        return -1;
19614    }
19615
19616    /**
19617     * Returns whether the view hierarchy is currently undergoing a layout pass. This
19618     * information is useful to avoid situations such as calling {@link #requestLayout()} during
19619     * a layout pass.
19620     *
19621     * @return whether the view hierarchy is currently undergoing a layout pass
19622     */
19623    public boolean isInLayout() {
19624        ViewRootImpl viewRoot = getViewRootImpl();
19625        return (viewRoot != null && viewRoot.isInLayout());
19626    }
19627
19628    /**
19629     * Call this when something has changed which has invalidated the
19630     * layout of this view. This will schedule a layout pass of the view
19631     * tree. This should not be called while the view hierarchy is currently in a layout
19632     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
19633     * end of the current layout pass (and then layout will run again) or after the current
19634     * frame is drawn and the next layout occurs.
19635     *
19636     * <p>Subclasses which override this method should call the superclass method to
19637     * handle possible request-during-layout errors correctly.</p>
19638     */
19639    @CallSuper
19640    public void requestLayout() {
19641        if (mMeasureCache != null) mMeasureCache.clear();
19642
19643        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
19644            // Only trigger request-during-layout logic if this is the view requesting it,
19645            // not the views in its parent hierarchy
19646            ViewRootImpl viewRoot = getViewRootImpl();
19647            if (viewRoot != null && viewRoot.isInLayout()) {
19648                if (!viewRoot.requestLayoutDuringLayout(this)) {
19649                    return;
19650                }
19651            }
19652            mAttachInfo.mViewRequestingLayout = this;
19653        }
19654
19655        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19656        mPrivateFlags |= PFLAG_INVALIDATED;
19657
19658        if (mParent != null && !mParent.isLayoutRequested()) {
19659            mParent.requestLayout();
19660        }
19661        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
19662            mAttachInfo.mViewRequestingLayout = null;
19663        }
19664    }
19665
19666    /**
19667     * Forces this view to be laid out during the next layout pass.
19668     * This method does not call requestLayout() or forceLayout()
19669     * on the parent.
19670     */
19671    public void forceLayout() {
19672        if (mMeasureCache != null) mMeasureCache.clear();
19673
19674        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
19675        mPrivateFlags |= PFLAG_INVALIDATED;
19676    }
19677
19678    /**
19679     * <p>
19680     * This is called to find out how big a view should be. The parent
19681     * supplies constraint information in the width and height parameters.
19682     * </p>
19683     *
19684     * <p>
19685     * The actual measurement work of a view is performed in
19686     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
19687     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
19688     * </p>
19689     *
19690     *
19691     * @param widthMeasureSpec Horizontal space requirements as imposed by the
19692     *        parent
19693     * @param heightMeasureSpec Vertical space requirements as imposed by the
19694     *        parent
19695     *
19696     * @see #onMeasure(int, int)
19697     */
19698    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
19699        boolean optical = isLayoutModeOptical(this);
19700        if (optical != isLayoutModeOptical(mParent)) {
19701            Insets insets = getOpticalInsets();
19702            int oWidth  = insets.left + insets.right;
19703            int oHeight = insets.top  + insets.bottom;
19704            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
19705            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
19706        }
19707
19708        // Suppress sign extension for the low bytes
19709        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
19710        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
19711
19712        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
19713
19714        // Optimize layout by avoiding an extra EXACTLY pass when the view is
19715        // already measured as the correct size. In API 23 and below, this
19716        // extra pass is required to make LinearLayout re-distribute weight.
19717        final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
19718                || heightMeasureSpec != mOldHeightMeasureSpec;
19719        final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
19720                && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
19721        final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
19722                && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
19723        final boolean needsLayout = specChanged
19724                && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
19725
19726        if (forceLayout || needsLayout) {
19727            // first clears the measured dimension flag
19728            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
19729
19730            resolveRtlPropertiesIfNeeded();
19731
19732            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
19733            if (cacheIndex < 0 || sIgnoreMeasureCache) {
19734                // measure ourselves, this should set the measured dimension flag back
19735                onMeasure(widthMeasureSpec, heightMeasureSpec);
19736                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19737            } else {
19738                long value = mMeasureCache.valueAt(cacheIndex);
19739                // Casting a long to int drops the high 32 bits, no mask needed
19740                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
19741                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
19742            }
19743
19744            // flag not set, setMeasuredDimension() was not invoked, we raise
19745            // an exception to warn the developer
19746            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
19747                throw new IllegalStateException("View with id " + getId() + ": "
19748                        + getClass().getName() + "#onMeasure() did not set the"
19749                        + " measured dimension by calling"
19750                        + " setMeasuredDimension()");
19751            }
19752
19753            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
19754        }
19755
19756        mOldWidthMeasureSpec = widthMeasureSpec;
19757        mOldHeightMeasureSpec = heightMeasureSpec;
19758
19759        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
19760                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
19761    }
19762
19763    /**
19764     * <p>
19765     * Measure the view and its content to determine the measured width and the
19766     * measured height. This method is invoked by {@link #measure(int, int)} and
19767     * should be overridden by subclasses to provide accurate and efficient
19768     * measurement of their contents.
19769     * </p>
19770     *
19771     * <p>
19772     * <strong>CONTRACT:</strong> When overriding this method, you
19773     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
19774     * measured width and height of this view. Failure to do so will trigger an
19775     * <code>IllegalStateException</code>, thrown by
19776     * {@link #measure(int, int)}. Calling the superclass'
19777     * {@link #onMeasure(int, int)} is a valid use.
19778     * </p>
19779     *
19780     * <p>
19781     * The base class implementation of measure defaults to the background size,
19782     * unless a larger size is allowed by the MeasureSpec. Subclasses should
19783     * override {@link #onMeasure(int, int)} to provide better measurements of
19784     * their content.
19785     * </p>
19786     *
19787     * <p>
19788     * If this method is overridden, it is the subclass's responsibility to make
19789     * sure the measured height and width are at least the view's minimum height
19790     * and width ({@link #getSuggestedMinimumHeight()} and
19791     * {@link #getSuggestedMinimumWidth()}).
19792     * </p>
19793     *
19794     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
19795     *                         The requirements are encoded with
19796     *                         {@link android.view.View.MeasureSpec}.
19797     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
19798     *                         The requirements are encoded with
19799     *                         {@link android.view.View.MeasureSpec}.
19800     *
19801     * @see #getMeasuredWidth()
19802     * @see #getMeasuredHeight()
19803     * @see #setMeasuredDimension(int, int)
19804     * @see #getSuggestedMinimumHeight()
19805     * @see #getSuggestedMinimumWidth()
19806     * @see android.view.View.MeasureSpec#getMode(int)
19807     * @see android.view.View.MeasureSpec#getSize(int)
19808     */
19809    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
19810        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
19811                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
19812    }
19813
19814    /**
19815     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
19816     * measured width and measured height. Failing to do so will trigger an
19817     * exception at measurement time.</p>
19818     *
19819     * @param measuredWidth The measured width of this view.  May be a complex
19820     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19821     * {@link #MEASURED_STATE_TOO_SMALL}.
19822     * @param measuredHeight The measured height of this view.  May be a complex
19823     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19824     * {@link #MEASURED_STATE_TOO_SMALL}.
19825     */
19826    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
19827        boolean optical = isLayoutModeOptical(this);
19828        if (optical != isLayoutModeOptical(mParent)) {
19829            Insets insets = getOpticalInsets();
19830            int opticalWidth  = insets.left + insets.right;
19831            int opticalHeight = insets.top  + insets.bottom;
19832
19833            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
19834            measuredHeight += optical ? opticalHeight : -opticalHeight;
19835        }
19836        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
19837    }
19838
19839    /**
19840     * Sets the measured dimension without extra processing for things like optical bounds.
19841     * Useful for reapplying consistent values that have already been cooked with adjustments
19842     * for optical bounds, etc. such as those from the measurement cache.
19843     *
19844     * @param measuredWidth The measured width of this view.  May be a complex
19845     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19846     * {@link #MEASURED_STATE_TOO_SMALL}.
19847     * @param measuredHeight The measured height of this view.  May be a complex
19848     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
19849     * {@link #MEASURED_STATE_TOO_SMALL}.
19850     */
19851    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
19852        mMeasuredWidth = measuredWidth;
19853        mMeasuredHeight = measuredHeight;
19854
19855        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
19856    }
19857
19858    /**
19859     * Merge two states as returned by {@link #getMeasuredState()}.
19860     * @param curState The current state as returned from a view or the result
19861     * of combining multiple views.
19862     * @param newState The new view state to combine.
19863     * @return Returns a new integer reflecting the combination of the two
19864     * states.
19865     */
19866    public static int combineMeasuredStates(int curState, int newState) {
19867        return curState | newState;
19868    }
19869
19870    /**
19871     * Version of {@link #resolveSizeAndState(int, int, int)}
19872     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
19873     */
19874    public static int resolveSize(int size, int measureSpec) {
19875        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
19876    }
19877
19878    /**
19879     * Utility to reconcile a desired size and state, with constraints imposed
19880     * by a MeasureSpec. Will take the desired size, unless a different size
19881     * is imposed by the constraints. The returned value is a compound integer,
19882     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
19883     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
19884     * resulting size is smaller than the size the view wants to be.
19885     *
19886     * @param size How big the view wants to be.
19887     * @param measureSpec Constraints imposed by the parent.
19888     * @param childMeasuredState Size information bit mask for the view's
19889     *                           children.
19890     * @return Size information bit mask as defined by
19891     *         {@link #MEASURED_SIZE_MASK} and
19892     *         {@link #MEASURED_STATE_TOO_SMALL}.
19893     */
19894    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
19895        final int specMode = MeasureSpec.getMode(measureSpec);
19896        final int specSize = MeasureSpec.getSize(measureSpec);
19897        final int result;
19898        switch (specMode) {
19899            case MeasureSpec.AT_MOST:
19900                if (specSize < size) {
19901                    result = specSize | MEASURED_STATE_TOO_SMALL;
19902                } else {
19903                    result = size;
19904                }
19905                break;
19906            case MeasureSpec.EXACTLY:
19907                result = specSize;
19908                break;
19909            case MeasureSpec.UNSPECIFIED:
19910            default:
19911                result = size;
19912        }
19913        return result | (childMeasuredState & MEASURED_STATE_MASK);
19914    }
19915
19916    /**
19917     * Utility to return a default size. Uses the supplied size if the
19918     * MeasureSpec imposed no constraints. Will get larger if allowed
19919     * by the MeasureSpec.
19920     *
19921     * @param size Default size for this view
19922     * @param measureSpec Constraints imposed by the parent
19923     * @return The size this view should be.
19924     */
19925    public static int getDefaultSize(int size, int measureSpec) {
19926        int result = size;
19927        int specMode = MeasureSpec.getMode(measureSpec);
19928        int specSize = MeasureSpec.getSize(measureSpec);
19929
19930        switch (specMode) {
19931        case MeasureSpec.UNSPECIFIED:
19932            result = size;
19933            break;
19934        case MeasureSpec.AT_MOST:
19935        case MeasureSpec.EXACTLY:
19936            result = specSize;
19937            break;
19938        }
19939        return result;
19940    }
19941
19942    /**
19943     * Returns the suggested minimum height that the view should use. This
19944     * returns the maximum of the view's minimum height
19945     * and the background's minimum height
19946     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
19947     * <p>
19948     * When being used in {@link #onMeasure(int, int)}, the caller should still
19949     * ensure the returned height is within the requirements of the parent.
19950     *
19951     * @return The suggested minimum height of the view.
19952     */
19953    protected int getSuggestedMinimumHeight() {
19954        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
19955
19956    }
19957
19958    /**
19959     * Returns the suggested minimum width that the view should use. This
19960     * returns the maximum of the view's minimum width
19961     * and the background's minimum width
19962     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
19963     * <p>
19964     * When being used in {@link #onMeasure(int, int)}, the caller should still
19965     * ensure the returned width is within the requirements of the parent.
19966     *
19967     * @return The suggested minimum width of the view.
19968     */
19969    protected int getSuggestedMinimumWidth() {
19970        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
19971    }
19972
19973    /**
19974     * Returns the minimum height of the view.
19975     *
19976     * @return the minimum height the view will try to be.
19977     *
19978     * @see #setMinimumHeight(int)
19979     *
19980     * @attr ref android.R.styleable#View_minHeight
19981     */
19982    public int getMinimumHeight() {
19983        return mMinHeight;
19984    }
19985
19986    /**
19987     * Sets the minimum height of the view. It is not guaranteed the view will
19988     * be able to achieve this minimum height (for example, if its parent layout
19989     * constrains it with less available height).
19990     *
19991     * @param minHeight The minimum height the view will try to be.
19992     *
19993     * @see #getMinimumHeight()
19994     *
19995     * @attr ref android.R.styleable#View_minHeight
19996     */
19997    @RemotableViewMethod
19998    public void setMinimumHeight(int minHeight) {
19999        mMinHeight = minHeight;
20000        requestLayout();
20001    }
20002
20003    /**
20004     * Returns the minimum width of the view.
20005     *
20006     * @return the minimum width the view will try to be.
20007     *
20008     * @see #setMinimumWidth(int)
20009     *
20010     * @attr ref android.R.styleable#View_minWidth
20011     */
20012    public int getMinimumWidth() {
20013        return mMinWidth;
20014    }
20015
20016    /**
20017     * Sets the minimum width of the view. It is not guaranteed the view will
20018     * be able to achieve this minimum width (for example, if its parent layout
20019     * constrains it with less available width).
20020     *
20021     * @param minWidth The minimum width the view will try to be.
20022     *
20023     * @see #getMinimumWidth()
20024     *
20025     * @attr ref android.R.styleable#View_minWidth
20026     */
20027    public void setMinimumWidth(int minWidth) {
20028        mMinWidth = minWidth;
20029        requestLayout();
20030
20031    }
20032
20033    /**
20034     * Get the animation currently associated with this view.
20035     *
20036     * @return The animation that is currently playing or
20037     *         scheduled to play for this view.
20038     */
20039    public Animation getAnimation() {
20040        return mCurrentAnimation;
20041    }
20042
20043    /**
20044     * Start the specified animation now.
20045     *
20046     * @param animation the animation to start now
20047     */
20048    public void startAnimation(Animation animation) {
20049        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
20050        setAnimation(animation);
20051        invalidateParentCaches();
20052        invalidate(true);
20053    }
20054
20055    /**
20056     * Cancels any animations for this view.
20057     */
20058    public void clearAnimation() {
20059        if (mCurrentAnimation != null) {
20060            mCurrentAnimation.detach();
20061        }
20062        mCurrentAnimation = null;
20063        invalidateParentIfNeeded();
20064    }
20065
20066    /**
20067     * Sets the next animation to play for this view.
20068     * If you want the animation to play immediately, use
20069     * {@link #startAnimation(android.view.animation.Animation)} instead.
20070     * This method provides allows fine-grained
20071     * control over the start time and invalidation, but you
20072     * must make sure that 1) the animation has a start time set, and
20073     * 2) the view's parent (which controls animations on its children)
20074     * will be invalidated when the animation is supposed to
20075     * start.
20076     *
20077     * @param animation The next animation, or null.
20078     */
20079    public void setAnimation(Animation animation) {
20080        mCurrentAnimation = animation;
20081
20082        if (animation != null) {
20083            // If the screen is off assume the animation start time is now instead of
20084            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
20085            // would cause the animation to start when the screen turns back on
20086            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
20087                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
20088                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
20089            }
20090            animation.reset();
20091        }
20092    }
20093
20094    /**
20095     * Invoked by a parent ViewGroup to notify the start of the animation
20096     * currently associated with this view. If you override this method,
20097     * always call super.onAnimationStart();
20098     *
20099     * @see #setAnimation(android.view.animation.Animation)
20100     * @see #getAnimation()
20101     */
20102    @CallSuper
20103    protected void onAnimationStart() {
20104        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
20105    }
20106
20107    /**
20108     * Invoked by a parent ViewGroup to notify the end of the animation
20109     * currently associated with this view. If you override this method,
20110     * always call super.onAnimationEnd();
20111     *
20112     * @see #setAnimation(android.view.animation.Animation)
20113     * @see #getAnimation()
20114     */
20115    @CallSuper
20116    protected void onAnimationEnd() {
20117        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
20118    }
20119
20120    /**
20121     * Invoked if there is a Transform that involves alpha. Subclass that can
20122     * draw themselves with the specified alpha should return true, and then
20123     * respect that alpha when their onDraw() is called. If this returns false
20124     * then the view may be redirected to draw into an offscreen buffer to
20125     * fulfill the request, which will look fine, but may be slower than if the
20126     * subclass handles it internally. The default implementation returns false.
20127     *
20128     * @param alpha The alpha (0..255) to apply to the view's drawing
20129     * @return true if the view can draw with the specified alpha.
20130     */
20131    protected boolean onSetAlpha(int alpha) {
20132        return false;
20133    }
20134
20135    /**
20136     * This is used by the RootView to perform an optimization when
20137     * the view hierarchy contains one or several SurfaceView.
20138     * SurfaceView is always considered transparent, but its children are not,
20139     * therefore all View objects remove themselves from the global transparent
20140     * region (passed as a parameter to this function).
20141     *
20142     * @param region The transparent region for this ViewAncestor (window).
20143     *
20144     * @return Returns true if the effective visibility of the view at this
20145     * point is opaque, regardless of the transparent region; returns false
20146     * if it is possible for underlying windows to be seen behind the view.
20147     *
20148     * {@hide}
20149     */
20150    public boolean gatherTransparentRegion(Region region) {
20151        final AttachInfo attachInfo = mAttachInfo;
20152        if (region != null && attachInfo != null) {
20153            final int pflags = mPrivateFlags;
20154            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
20155                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
20156                // remove it from the transparent region.
20157                final int[] location = attachInfo.mTransparentLocation;
20158                getLocationInWindow(location);
20159                region.op(location[0], location[1], location[0] + mRight - mLeft,
20160                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
20161            } else {
20162                if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
20163                    // The SKIP_DRAW flag IS set and the background drawable exists, we remove
20164                    // the background drawable's non-transparent parts from this transparent region.
20165                    applyDrawableToTransparentRegion(mBackground, region);
20166                }
20167                if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
20168                        && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) {
20169                    // Similarly, we remove the foreground drawable's non-transparent parts.
20170                    applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
20171                }
20172            }
20173        }
20174        return true;
20175    }
20176
20177    /**
20178     * Play a sound effect for this view.
20179     *
20180     * <p>The framework will play sound effects for some built in actions, such as
20181     * clicking, but you may wish to play these effects in your widget,
20182     * for instance, for internal navigation.
20183     *
20184     * <p>The sound effect will only be played if sound effects are enabled by the user, and
20185     * {@link #isSoundEffectsEnabled()} is true.
20186     *
20187     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
20188     */
20189    public void playSoundEffect(int soundConstant) {
20190        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
20191            return;
20192        }
20193        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
20194    }
20195
20196    /**
20197     * BZZZTT!!1!
20198     *
20199     * <p>Provide haptic feedback to the user for this view.
20200     *
20201     * <p>The framework will provide haptic feedback for some built in actions,
20202     * such as long presses, but you may wish to provide feedback for your
20203     * own widget.
20204     *
20205     * <p>The feedback will only be performed if
20206     * {@link #isHapticFeedbackEnabled()} is true.
20207     *
20208     * @param feedbackConstant One of the constants defined in
20209     * {@link HapticFeedbackConstants}
20210     */
20211    public boolean performHapticFeedback(int feedbackConstant) {
20212        return performHapticFeedback(feedbackConstant, 0);
20213    }
20214
20215    /**
20216     * BZZZTT!!1!
20217     *
20218     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
20219     *
20220     * @param feedbackConstant One of the constants defined in
20221     * {@link HapticFeedbackConstants}
20222     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
20223     */
20224    public boolean performHapticFeedback(int feedbackConstant, int flags) {
20225        if (mAttachInfo == null) {
20226            return false;
20227        }
20228        //noinspection SimplifiableIfStatement
20229        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
20230                && !isHapticFeedbackEnabled()) {
20231            return false;
20232        }
20233        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
20234                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
20235    }
20236
20237    /**
20238     * Request that the visibility of the status bar or other screen/window
20239     * decorations be changed.
20240     *
20241     * <p>This method is used to put the over device UI into temporary modes
20242     * where the user's attention is focused more on the application content,
20243     * by dimming or hiding surrounding system affordances.  This is typically
20244     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
20245     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
20246     * to be placed behind the action bar (and with these flags other system
20247     * affordances) so that smooth transitions between hiding and showing them
20248     * can be done.
20249     *
20250     * <p>Two representative examples of the use of system UI visibility is
20251     * implementing a content browsing application (like a magazine reader)
20252     * and a video playing application.
20253     *
20254     * <p>The first code shows a typical implementation of a View in a content
20255     * browsing application.  In this implementation, the application goes
20256     * into a content-oriented mode by hiding the status bar and action bar,
20257     * and putting the navigation elements into lights out mode.  The user can
20258     * then interact with content while in this mode.  Such an application should
20259     * provide an easy way for the user to toggle out of the mode (such as to
20260     * check information in the status bar or access notifications).  In the
20261     * implementation here, this is done simply by tapping on the content.
20262     *
20263     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
20264     *      content}
20265     *
20266     * <p>This second code sample shows a typical implementation of a View
20267     * in a video playing application.  In this situation, while the video is
20268     * playing the application would like to go into a complete full-screen mode,
20269     * to use as much of the display as possible for the video.  When in this state
20270     * the user can not interact with the application; the system intercepts
20271     * touching on the screen to pop the UI out of full screen mode.  See
20272     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
20273     *
20274     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
20275     *      content}
20276     *
20277     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20278     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20279     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20280     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20281     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20282     */
20283    public void setSystemUiVisibility(int visibility) {
20284        if (visibility != mSystemUiVisibility) {
20285            mSystemUiVisibility = visibility;
20286            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20287                mParent.recomputeViewAttributes(this);
20288            }
20289        }
20290    }
20291
20292    /**
20293     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
20294     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20295     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
20296     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
20297     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
20298     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
20299     */
20300    public int getSystemUiVisibility() {
20301        return mSystemUiVisibility;
20302    }
20303
20304    /**
20305     * Returns the current system UI visibility that is currently set for
20306     * the entire window.  This is the combination of the
20307     * {@link #setSystemUiVisibility(int)} values supplied by all of the
20308     * views in the window.
20309     */
20310    public int getWindowSystemUiVisibility() {
20311        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
20312    }
20313
20314    /**
20315     * Override to find out when the window's requested system UI visibility
20316     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
20317     * This is different from the callbacks received through
20318     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
20319     * in that this is only telling you about the local request of the window,
20320     * not the actual values applied by the system.
20321     */
20322    public void onWindowSystemUiVisibilityChanged(int visible) {
20323    }
20324
20325    /**
20326     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
20327     * the view hierarchy.
20328     */
20329    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
20330        onWindowSystemUiVisibilityChanged(visible);
20331    }
20332
20333    /**
20334     * Set a listener to receive callbacks when the visibility of the system bar changes.
20335     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
20336     */
20337    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
20338        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
20339        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
20340            mParent.recomputeViewAttributes(this);
20341        }
20342    }
20343
20344    /**
20345     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
20346     * the view hierarchy.
20347     */
20348    public void dispatchSystemUiVisibilityChanged(int visibility) {
20349        ListenerInfo li = mListenerInfo;
20350        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
20351            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
20352                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
20353        }
20354    }
20355
20356    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
20357        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
20358        if (val != mSystemUiVisibility) {
20359            setSystemUiVisibility(val);
20360            return true;
20361        }
20362        return false;
20363    }
20364
20365    /** @hide */
20366    public void setDisabledSystemUiVisibility(int flags) {
20367        if (mAttachInfo != null) {
20368            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
20369                mAttachInfo.mDisabledSystemUiVisibility = flags;
20370                if (mParent != null) {
20371                    mParent.recomputeViewAttributes(this);
20372                }
20373            }
20374        }
20375    }
20376
20377    /**
20378     * Creates an image that the system displays during the drag and drop
20379     * operation. This is called a &quot;drag shadow&quot;. The default implementation
20380     * for a DragShadowBuilder based on a View returns an image that has exactly the same
20381     * appearance as the given View. The default also positions the center of the drag shadow
20382     * directly under the touch point. If no View is provided (the constructor with no parameters
20383     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
20384     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
20385     * default is an invisible drag shadow.
20386     * <p>
20387     * You are not required to use the View you provide to the constructor as the basis of the
20388     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
20389     * anything you want as the drag shadow.
20390     * </p>
20391     * <p>
20392     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
20393     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
20394     *  size and position of the drag shadow. It uses this data to construct a
20395     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
20396     *  so that your application can draw the shadow image in the Canvas.
20397     * </p>
20398     *
20399     * <div class="special reference">
20400     * <h3>Developer Guides</h3>
20401     * <p>For a guide to implementing drag and drop features, read the
20402     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20403     * </div>
20404     */
20405    public static class DragShadowBuilder {
20406        private final WeakReference<View> mView;
20407
20408        /**
20409         * Constructs a shadow image builder based on a View. By default, the resulting drag
20410         * shadow will have the same appearance and dimensions as the View, with the touch point
20411         * over the center of the View.
20412         * @param view A View. Any View in scope can be used.
20413         */
20414        public DragShadowBuilder(View view) {
20415            mView = new WeakReference<View>(view);
20416        }
20417
20418        /**
20419         * Construct a shadow builder object with no associated View.  This
20420         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
20421         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
20422         * to supply the drag shadow's dimensions and appearance without
20423         * reference to any View object. If they are not overridden, then the result is an
20424         * invisible drag shadow.
20425         */
20426        public DragShadowBuilder() {
20427            mView = new WeakReference<View>(null);
20428        }
20429
20430        /**
20431         * Returns the View object that had been passed to the
20432         * {@link #View.DragShadowBuilder(View)}
20433         * constructor.  If that View parameter was {@code null} or if the
20434         * {@link #View.DragShadowBuilder()}
20435         * constructor was used to instantiate the builder object, this method will return
20436         * null.
20437         *
20438         * @return The View object associate with this builder object.
20439         */
20440        @SuppressWarnings({"JavadocReference"})
20441        final public View getView() {
20442            return mView.get();
20443        }
20444
20445        /**
20446         * Provides the metrics for the shadow image. These include the dimensions of
20447         * the shadow image, and the point within that shadow that should
20448         * be centered under the touch location while dragging.
20449         * <p>
20450         * The default implementation sets the dimensions of the shadow to be the
20451         * same as the dimensions of the View itself and centers the shadow under
20452         * the touch point.
20453         * </p>
20454         *
20455         * @param outShadowSize A {@link android.graphics.Point} containing the width and height
20456         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
20457         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
20458         * image.
20459         *
20460         * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the
20461         * shadow image that should be underneath the touch point during the drag and drop
20462         * operation. Your application must set {@link android.graphics.Point#x} to the
20463         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
20464         */
20465        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
20466            final View view = mView.get();
20467            if (view != null) {
20468                outShadowSize.set(view.getWidth(), view.getHeight());
20469                outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2);
20470            } else {
20471                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
20472            }
20473        }
20474
20475        /**
20476         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
20477         * based on the dimensions it received from the
20478         * {@link #onProvideShadowMetrics(Point, Point)} callback.
20479         *
20480         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
20481         */
20482        public void onDrawShadow(Canvas canvas) {
20483            final View view = mView.get();
20484            if (view != null) {
20485                view.draw(canvas);
20486            } else {
20487                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
20488            }
20489        }
20490    }
20491
20492    /**
20493     * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)
20494     * startDragAndDrop()} for newer platform versions.
20495     */
20496    @Deprecated
20497    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
20498                                   Object myLocalState, int flags) {
20499        return startDragAndDrop(data, shadowBuilder, myLocalState, flags);
20500    }
20501
20502    /**
20503     * Starts a drag and drop operation. When your application calls this method, it passes a
20504     * {@link android.view.View.DragShadowBuilder} object to the system. The
20505     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
20506     * to get metrics for the drag shadow, and then calls the object's
20507     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
20508     * <p>
20509     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
20510     *  drag events to all the View objects in your application that are currently visible. It does
20511     *  this either by calling the View object's drag listener (an implementation of
20512     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
20513     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
20514     *  Both are passed a {@link android.view.DragEvent} object that has a
20515     *  {@link android.view.DragEvent#getAction()} value of
20516     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
20517     * </p>
20518     * <p>
20519     * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object,
20520     * int) startDragAndDrop()} on any attached View object. The View object does not need to be
20521     * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related
20522     * to the View the user selected for dragging.
20523     * </p>
20524     * @param data A {@link android.content.ClipData} object pointing to the data to be
20525     * transferred by the drag and drop operation.
20526     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20527     * drag shadow.
20528     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
20529     * drop operation. This Object is put into every DragEvent object sent by the system during the
20530     * current drag.
20531     * <p>
20532     * myLocalState is a lightweight mechanism for the sending information from the dragged View
20533     * to the target Views. For example, it can contain flags that differentiate between a
20534     * a copy operation and a move operation.
20535     * </p>
20536     * @param flags Flags that control the drag and drop operation. This can be set to 0 for no
20537     * flags, or any combination of the following:
20538     *     <ul>
20539     *         <li>{@link #DRAG_FLAG_GLOBAL}</li>
20540     *         <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li>
20541     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20542     *         <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li>
20543     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li>
20544     *         <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li>
20545     *         <li>{@link #DRAG_FLAG_OPAQUE}</li>
20546     *     </ul>
20547     * @return {@code true} if the method completes successfully, or
20548     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
20549     * do a drag, and so no drag operation is in progress.
20550     */
20551    public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder,
20552            Object myLocalState, int flags) {
20553        if (ViewDebug.DEBUG_DRAG) {
20554            Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags);
20555        }
20556        if (mAttachInfo == null) {
20557            Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view.");
20558            return false;
20559        }
20560        boolean okay = false;
20561
20562        Point shadowSize = new Point();
20563        Point shadowTouchPoint = new Point();
20564        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
20565
20566        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
20567                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
20568            throw new IllegalStateException("Drag shadow dimensions must not be negative");
20569        }
20570
20571        if (ViewDebug.DEBUG_DRAG) {
20572            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
20573                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
20574        }
20575        if (mAttachInfo.mDragSurface != null) {
20576            mAttachInfo.mDragSurface.release();
20577        }
20578        mAttachInfo.mDragSurface = new Surface();
20579        try {
20580            mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
20581                    flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface);
20582            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token="
20583                    + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface);
20584            if (mAttachInfo.mDragToken != null) {
20585                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20586                try {
20587                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20588                    shadowBuilder.onDrawShadow(canvas);
20589                } finally {
20590                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20591                }
20592
20593                final ViewRootImpl root = getViewRootImpl();
20594
20595                // Cache the local state object for delivery with DragEvents
20596                root.setLocalDragState(myLocalState);
20597
20598                // repurpose 'shadowSize' for the last touch point
20599                root.getLastTouchPoint(shadowSize);
20600
20601                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken,
20602                        root.getLastTouchSource(), shadowSize.x, shadowSize.y,
20603                        shadowTouchPoint.x, shadowTouchPoint.y, data);
20604                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
20605            }
20606        } catch (Exception e) {
20607            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
20608            mAttachInfo.mDragSurface.destroy();
20609            mAttachInfo.mDragSurface = null;
20610        }
20611
20612        return okay;
20613    }
20614
20615    /**
20616     * Cancels an ongoing drag and drop operation.
20617     * <p>
20618     * A {@link android.view.DragEvent} object with
20619     * {@link android.view.DragEvent#getAction()} value of
20620     * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and
20621     * {@link android.view.DragEvent#getResult()} value of {@code false}
20622     * will be sent to every
20623     * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED}
20624     * even if they are not currently visible.
20625     * </p>
20626     * <p>
20627     * This method can be called on any View in the same window as the View on which
20628     * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop}
20629     * was called.
20630     * </p>
20631     */
20632    public final void cancelDragAndDrop() {
20633        if (ViewDebug.DEBUG_DRAG) {
20634            Log.d(VIEW_LOG_TAG, "cancelDragAndDrop");
20635        }
20636        if (mAttachInfo == null) {
20637            Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view.");
20638            return;
20639        }
20640        if (mAttachInfo.mDragToken != null) {
20641            try {
20642                mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken);
20643            } catch (Exception e) {
20644                Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e);
20645            }
20646            mAttachInfo.mDragToken = null;
20647        } else {
20648            Log.e(VIEW_LOG_TAG, "No active drag to cancel");
20649        }
20650    }
20651
20652    /**
20653     * Updates the drag shadow for the ongoing drag and drop operation.
20654     *
20655     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
20656     * new drag shadow.
20657     */
20658    public final void updateDragShadow(DragShadowBuilder shadowBuilder) {
20659        if (ViewDebug.DEBUG_DRAG) {
20660            Log.d(VIEW_LOG_TAG, "updateDragShadow");
20661        }
20662        if (mAttachInfo == null) {
20663            Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view.");
20664            return;
20665        }
20666        if (mAttachInfo.mDragToken != null) {
20667            try {
20668                Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null);
20669                try {
20670                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
20671                    shadowBuilder.onDrawShadow(canvas);
20672                } finally {
20673                    mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas);
20674                }
20675            } catch (Exception e) {
20676                Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e);
20677            }
20678        } else {
20679            Log.e(VIEW_LOG_TAG, "No active drag");
20680        }
20681    }
20682
20683    /**
20684     * Starts a move from {startX, startY}, the amount of the movement will be the offset
20685     * between {startX, startY} and the new cursor positon.
20686     * @param startX horizontal coordinate where the move started.
20687     * @param startY vertical coordinate where the move started.
20688     * @return whether moving was started successfully.
20689     * @hide
20690     */
20691    public final boolean startMovingTask(float startX, float startY) {
20692        if (ViewDebug.DEBUG_POSITIONING) {
20693            Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}");
20694        }
20695        try {
20696            return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY);
20697        } catch (RemoteException e) {
20698            Log.e(VIEW_LOG_TAG, "Unable to start moving", e);
20699        }
20700        return false;
20701    }
20702
20703    /**
20704     * Handles drag events sent by the system following a call to
20705     * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int)
20706     * startDragAndDrop()}.
20707     *<p>
20708     * When the system calls this method, it passes a
20709     * {@link android.view.DragEvent} object. A call to
20710     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
20711     * in DragEvent. The method uses these to determine what is happening in the drag and drop
20712     * operation.
20713     * @param event The {@link android.view.DragEvent} sent by the system.
20714     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
20715     * in DragEvent, indicating the type of drag event represented by this object.
20716     * @return {@code true} if the method was successful, otherwise {@code false}.
20717     * <p>
20718     *  The method should return {@code true} in response to an action type of
20719     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
20720     *  operation.
20721     * </p>
20722     * <p>
20723     *  The method should also return {@code true} in response to an action type of
20724     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
20725     *  {@code false} if it didn't.
20726     * </p>
20727     */
20728    public boolean onDragEvent(DragEvent event) {
20729        return false;
20730    }
20731
20732    /**
20733     * Detects if this View is enabled and has a drag event listener.
20734     * If both are true, then it calls the drag event listener with the
20735     * {@link android.view.DragEvent} it received. If the drag event listener returns
20736     * {@code true}, then dispatchDragEvent() returns {@code true}.
20737     * <p>
20738     * For all other cases, the method calls the
20739     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
20740     * method and returns its result.
20741     * </p>
20742     * <p>
20743     * This ensures that a drag event is always consumed, even if the View does not have a drag
20744     * event listener. However, if the View has a listener and the listener returns true, then
20745     * onDragEvent() is not called.
20746     * </p>
20747     */
20748    public boolean dispatchDragEvent(DragEvent event) {
20749        ListenerInfo li = mListenerInfo;
20750        //noinspection SimplifiableIfStatement
20751        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
20752                && li.mOnDragListener.onDrag(this, event)) {
20753            return true;
20754        }
20755        return onDragEvent(event);
20756    }
20757
20758    boolean canAcceptDrag() {
20759        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
20760    }
20761
20762    /**
20763     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
20764     * it is ever exposed at all.
20765     * @hide
20766     */
20767    public void onCloseSystemDialogs(String reason) {
20768    }
20769
20770    /**
20771     * Given a Drawable whose bounds have been set to draw into this view,
20772     * update a Region being computed for
20773     * {@link #gatherTransparentRegion(android.graphics.Region)} so
20774     * that any non-transparent parts of the Drawable are removed from the
20775     * given transparent region.
20776     *
20777     * @param dr The Drawable whose transparency is to be applied to the region.
20778     * @param region A Region holding the current transparency information,
20779     * where any parts of the region that are set are considered to be
20780     * transparent.  On return, this region will be modified to have the
20781     * transparency information reduced by the corresponding parts of the
20782     * Drawable that are not transparent.
20783     * {@hide}
20784     */
20785    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
20786        if (DBG) {
20787            Log.i("View", "Getting transparent region for: " + this);
20788        }
20789        final Region r = dr.getTransparentRegion();
20790        final Rect db = dr.getBounds();
20791        final AttachInfo attachInfo = mAttachInfo;
20792        if (r != null && attachInfo != null) {
20793            final int w = getRight()-getLeft();
20794            final int h = getBottom()-getTop();
20795            if (db.left > 0) {
20796                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
20797                r.op(0, 0, db.left, h, Region.Op.UNION);
20798            }
20799            if (db.right < w) {
20800                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
20801                r.op(db.right, 0, w, h, Region.Op.UNION);
20802            }
20803            if (db.top > 0) {
20804                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
20805                r.op(0, 0, w, db.top, Region.Op.UNION);
20806            }
20807            if (db.bottom < h) {
20808                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
20809                r.op(0, db.bottom, w, h, Region.Op.UNION);
20810            }
20811            final int[] location = attachInfo.mTransparentLocation;
20812            getLocationInWindow(location);
20813            r.translate(location[0], location[1]);
20814            region.op(r, Region.Op.INTERSECT);
20815        } else {
20816            region.op(db, Region.Op.DIFFERENCE);
20817        }
20818    }
20819
20820    private void checkForLongClick(int delayOffset, float x, float y) {
20821        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
20822            mHasPerformedLongPress = false;
20823
20824            if (mPendingCheckForLongPress == null) {
20825                mPendingCheckForLongPress = new CheckForLongPress();
20826            }
20827            mPendingCheckForLongPress.setAnchor(x, y);
20828            mPendingCheckForLongPress.rememberWindowAttachCount();
20829            postDelayed(mPendingCheckForLongPress,
20830                    ViewConfiguration.getLongPressTimeout() - delayOffset);
20831        }
20832    }
20833
20834    /**
20835     * Inflate a view from an XML resource.  This convenience method wraps the {@link
20836     * LayoutInflater} class, which provides a full range of options for view inflation.
20837     *
20838     * @param context The Context object for your activity or application.
20839     * @param resource The resource ID to inflate
20840     * @param root A view group that will be the parent.  Used to properly inflate the
20841     * layout_* parameters.
20842     * @see LayoutInflater
20843     */
20844    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
20845        LayoutInflater factory = LayoutInflater.from(context);
20846        return factory.inflate(resource, root);
20847    }
20848
20849    /**
20850     * Scroll the view with standard behavior for scrolling beyond the normal
20851     * content boundaries. Views that call this method should override
20852     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
20853     * results of an over-scroll operation.
20854     *
20855     * Views can use this method to handle any touch or fling-based scrolling.
20856     *
20857     * @param deltaX Change in X in pixels
20858     * @param deltaY Change in Y in pixels
20859     * @param scrollX Current X scroll value in pixels before applying deltaX
20860     * @param scrollY Current Y scroll value in pixels before applying deltaY
20861     * @param scrollRangeX Maximum content scroll range along the X axis
20862     * @param scrollRangeY Maximum content scroll range along the Y axis
20863     * @param maxOverScrollX Number of pixels to overscroll by in either direction
20864     *          along the X axis.
20865     * @param maxOverScrollY Number of pixels to overscroll by in either direction
20866     *          along the Y axis.
20867     * @param isTouchEvent true if this scroll operation is the result of a touch event.
20868     * @return true if scrolling was clamped to an over-scroll boundary along either
20869     *          axis, false otherwise.
20870     */
20871    @SuppressWarnings({"UnusedParameters"})
20872    protected boolean overScrollBy(int deltaX, int deltaY,
20873            int scrollX, int scrollY,
20874            int scrollRangeX, int scrollRangeY,
20875            int maxOverScrollX, int maxOverScrollY,
20876            boolean isTouchEvent) {
20877        final int overScrollMode = mOverScrollMode;
20878        final boolean canScrollHorizontal =
20879                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
20880        final boolean canScrollVertical =
20881                computeVerticalScrollRange() > computeVerticalScrollExtent();
20882        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
20883                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
20884        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
20885                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
20886
20887        int newScrollX = scrollX + deltaX;
20888        if (!overScrollHorizontal) {
20889            maxOverScrollX = 0;
20890        }
20891
20892        int newScrollY = scrollY + deltaY;
20893        if (!overScrollVertical) {
20894            maxOverScrollY = 0;
20895        }
20896
20897        // Clamp values if at the limits and record
20898        final int left = -maxOverScrollX;
20899        final int right = maxOverScrollX + scrollRangeX;
20900        final int top = -maxOverScrollY;
20901        final int bottom = maxOverScrollY + scrollRangeY;
20902
20903        boolean clampedX = false;
20904        if (newScrollX > right) {
20905            newScrollX = right;
20906            clampedX = true;
20907        } else if (newScrollX < left) {
20908            newScrollX = left;
20909            clampedX = true;
20910        }
20911
20912        boolean clampedY = false;
20913        if (newScrollY > bottom) {
20914            newScrollY = bottom;
20915            clampedY = true;
20916        } else if (newScrollY < top) {
20917            newScrollY = top;
20918            clampedY = true;
20919        }
20920
20921        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
20922
20923        return clampedX || clampedY;
20924    }
20925
20926    /**
20927     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
20928     * respond to the results of an over-scroll operation.
20929     *
20930     * @param scrollX New X scroll value in pixels
20931     * @param scrollY New Y scroll value in pixels
20932     * @param clampedX True if scrollX was clamped to an over-scroll boundary
20933     * @param clampedY True if scrollY was clamped to an over-scroll boundary
20934     */
20935    protected void onOverScrolled(int scrollX, int scrollY,
20936            boolean clampedX, boolean clampedY) {
20937        // Intentionally empty.
20938    }
20939
20940    /**
20941     * Returns the over-scroll mode for this view. The result will be
20942     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20943     * (allow over-scrolling only if the view content is larger than the container),
20944     * or {@link #OVER_SCROLL_NEVER}.
20945     *
20946     * @return This view's over-scroll mode.
20947     */
20948    public int getOverScrollMode() {
20949        return mOverScrollMode;
20950    }
20951
20952    /**
20953     * Set the over-scroll mode for this view. Valid over-scroll modes are
20954     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
20955     * (allow over-scrolling only if the view content is larger than the container),
20956     * or {@link #OVER_SCROLL_NEVER}.
20957     *
20958     * Setting the over-scroll mode of a view will have an effect only if the
20959     * view is capable of scrolling.
20960     *
20961     * @param overScrollMode The new over-scroll mode for this view.
20962     */
20963    public void setOverScrollMode(int overScrollMode) {
20964        if (overScrollMode != OVER_SCROLL_ALWAYS &&
20965                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
20966                overScrollMode != OVER_SCROLL_NEVER) {
20967            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
20968        }
20969        mOverScrollMode = overScrollMode;
20970    }
20971
20972    /**
20973     * Enable or disable nested scrolling for this view.
20974     *
20975     * <p>If this property is set to true the view will be permitted to initiate nested
20976     * scrolling operations with a compatible parent view in the current hierarchy. If this
20977     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
20978     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
20979     * the nested scroll.</p>
20980     *
20981     * @param enabled true to enable nested scrolling, false to disable
20982     *
20983     * @see #isNestedScrollingEnabled()
20984     */
20985    public void setNestedScrollingEnabled(boolean enabled) {
20986        if (enabled) {
20987            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
20988        } else {
20989            stopNestedScroll();
20990            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
20991        }
20992    }
20993
20994    /**
20995     * Returns true if nested scrolling is enabled for this view.
20996     *
20997     * <p>If nested scrolling is enabled and this View class implementation supports it,
20998     * this view will act as a nested scrolling child view when applicable, forwarding data
20999     * about the scroll operation in progress to a compatible and cooperating nested scrolling
21000     * parent.</p>
21001     *
21002     * @return true if nested scrolling is enabled
21003     *
21004     * @see #setNestedScrollingEnabled(boolean)
21005     */
21006    public boolean isNestedScrollingEnabled() {
21007        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
21008                PFLAG3_NESTED_SCROLLING_ENABLED;
21009    }
21010
21011    /**
21012     * Begin a nestable scroll operation along the given axes.
21013     *
21014     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
21015     *
21016     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
21017     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
21018     * In the case of touch scrolling the nested scroll will be terminated automatically in
21019     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
21020     * In the event of programmatic scrolling the caller must explicitly call
21021     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
21022     *
21023     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
21024     * If it returns false the caller may ignore the rest of this contract until the next scroll.
21025     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
21026     *
21027     * <p>At each incremental step of the scroll the caller should invoke
21028     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
21029     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
21030     * parent at least partially consumed the scroll and the caller should adjust the amount it
21031     * scrolls by.</p>
21032     *
21033     * <p>After applying the remainder of the scroll delta the caller should invoke
21034     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
21035     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
21036     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
21037     * </p>
21038     *
21039     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
21040     *             {@link #SCROLL_AXIS_VERTICAL}.
21041     * @return true if a cooperative parent was found and nested scrolling has been enabled for
21042     *         the current gesture.
21043     *
21044     * @see #stopNestedScroll()
21045     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21046     * @see #dispatchNestedScroll(int, int, int, int, int[])
21047     */
21048    public boolean startNestedScroll(int axes) {
21049        if (hasNestedScrollingParent()) {
21050            // Already in progress
21051            return true;
21052        }
21053        if (isNestedScrollingEnabled()) {
21054            ViewParent p = getParent();
21055            View child = this;
21056            while (p != null) {
21057                try {
21058                    if (p.onStartNestedScroll(child, this, axes)) {
21059                        mNestedScrollingParent = p;
21060                        p.onNestedScrollAccepted(child, this, axes);
21061                        return true;
21062                    }
21063                } catch (AbstractMethodError e) {
21064                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
21065                            "method onStartNestedScroll", e);
21066                    // Allow the search upward to continue
21067                }
21068                if (p instanceof View) {
21069                    child = (View) p;
21070                }
21071                p = p.getParent();
21072            }
21073        }
21074        return false;
21075    }
21076
21077    /**
21078     * Stop a nested scroll in progress.
21079     *
21080     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
21081     *
21082     * @see #startNestedScroll(int)
21083     */
21084    public void stopNestedScroll() {
21085        if (mNestedScrollingParent != null) {
21086            mNestedScrollingParent.onStopNestedScroll(this);
21087            mNestedScrollingParent = null;
21088        }
21089    }
21090
21091    /**
21092     * Returns true if this view has a nested scrolling parent.
21093     *
21094     * <p>The presence of a nested scrolling parent indicates that this view has initiated
21095     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
21096     *
21097     * @return whether this view has a nested scrolling parent
21098     */
21099    public boolean hasNestedScrollingParent() {
21100        return mNestedScrollingParent != null;
21101    }
21102
21103    /**
21104     * Dispatch one step of a nested scroll in progress.
21105     *
21106     * <p>Implementations of views that support nested scrolling should call this to report
21107     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
21108     * is not currently in progress or nested scrolling is not
21109     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
21110     *
21111     * <p>Compatible View implementations should also call
21112     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
21113     * consuming a component of the scroll event themselves.</p>
21114     *
21115     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
21116     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
21117     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
21118     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
21119     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21120     *                       in local view coordinates of this view from before this operation
21121     *                       to after it completes. View implementations may use this to adjust
21122     *                       expected input coordinate tracking.
21123     * @return true if the event was dispatched, false if it could not be dispatched.
21124     * @see #dispatchNestedPreScroll(int, int, int[], int[])
21125     */
21126    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
21127            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
21128        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21129            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
21130                int startX = 0;
21131                int startY = 0;
21132                if (offsetInWindow != null) {
21133                    getLocationInWindow(offsetInWindow);
21134                    startX = offsetInWindow[0];
21135                    startY = offsetInWindow[1];
21136                }
21137
21138                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
21139                        dxUnconsumed, dyUnconsumed);
21140
21141                if (offsetInWindow != null) {
21142                    getLocationInWindow(offsetInWindow);
21143                    offsetInWindow[0] -= startX;
21144                    offsetInWindow[1] -= startY;
21145                }
21146                return true;
21147            } else if (offsetInWindow != null) {
21148                // No motion, no dispatch. Keep offsetInWindow up to date.
21149                offsetInWindow[0] = 0;
21150                offsetInWindow[1] = 0;
21151            }
21152        }
21153        return false;
21154    }
21155
21156    /**
21157     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
21158     *
21159     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
21160     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
21161     * scrolling operation to consume some or all of the scroll operation before the child view
21162     * consumes it.</p>
21163     *
21164     * @param dx Horizontal scroll distance in pixels
21165     * @param dy Vertical scroll distance in pixels
21166     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
21167     *                 and consumed[1] the consumed dy.
21168     * @param offsetInWindow Optional. If not null, on return this will contain the offset
21169     *                       in local view coordinates of this view from before this operation
21170     *                       to after it completes. View implementations may use this to adjust
21171     *                       expected input coordinate tracking.
21172     * @return true if the parent consumed some or all of the scroll delta
21173     * @see #dispatchNestedScroll(int, int, int, int, int[])
21174     */
21175    public boolean dispatchNestedPreScroll(int dx, int dy,
21176            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
21177        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21178            if (dx != 0 || dy != 0) {
21179                int startX = 0;
21180                int startY = 0;
21181                if (offsetInWindow != null) {
21182                    getLocationInWindow(offsetInWindow);
21183                    startX = offsetInWindow[0];
21184                    startY = offsetInWindow[1];
21185                }
21186
21187                if (consumed == null) {
21188                    if (mTempNestedScrollConsumed == null) {
21189                        mTempNestedScrollConsumed = new int[2];
21190                    }
21191                    consumed = mTempNestedScrollConsumed;
21192                }
21193                consumed[0] = 0;
21194                consumed[1] = 0;
21195                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
21196
21197                if (offsetInWindow != null) {
21198                    getLocationInWindow(offsetInWindow);
21199                    offsetInWindow[0] -= startX;
21200                    offsetInWindow[1] -= startY;
21201                }
21202                return consumed[0] != 0 || consumed[1] != 0;
21203            } else if (offsetInWindow != null) {
21204                offsetInWindow[0] = 0;
21205                offsetInWindow[1] = 0;
21206            }
21207        }
21208        return false;
21209    }
21210
21211    /**
21212     * Dispatch a fling to a nested scrolling parent.
21213     *
21214     * <p>This method should be used to indicate that a nested scrolling child has detected
21215     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
21216     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
21217     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
21218     * along a scrollable axis.</p>
21219     *
21220     * <p>If a nested scrolling child view would normally fling but it is at the edge of
21221     * its own content, it can use this method to delegate the fling to its nested scrolling
21222     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
21223     *
21224     * @param velocityX Horizontal fling velocity in pixels per second
21225     * @param velocityY Vertical fling velocity in pixels per second
21226     * @param consumed true if the child consumed the fling, false otherwise
21227     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
21228     */
21229    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
21230        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21231            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
21232        }
21233        return false;
21234    }
21235
21236    /**
21237     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
21238     *
21239     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
21240     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
21241     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
21242     * before the child view consumes it. If this method returns <code>true</code>, a nested
21243     * parent view consumed the fling and this view should not scroll as a result.</p>
21244     *
21245     * <p>For a better user experience, only one view in a nested scrolling chain should consume
21246     * the fling at a time. If a parent view consumed the fling this method will return false.
21247     * Custom view implementations should account for this in two ways:</p>
21248     *
21249     * <ul>
21250     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
21251     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
21252     *     position regardless.</li>
21253     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
21254     *     even to settle back to a valid idle position.</li>
21255     * </ul>
21256     *
21257     * <p>Views should also not offer fling velocities to nested parent views along an axis
21258     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
21259     * should not offer a horizontal fling velocity to its parents since scrolling along that
21260     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
21261     *
21262     * @param velocityX Horizontal fling velocity in pixels per second
21263     * @param velocityY Vertical fling velocity in pixels per second
21264     * @return true if a nested scrolling parent consumed the fling
21265     */
21266    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
21267        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
21268            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
21269        }
21270        return false;
21271    }
21272
21273    /**
21274     * Gets a scale factor that determines the distance the view should scroll
21275     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
21276     * @return The vertical scroll scale factor.
21277     * @hide
21278     */
21279    protected float getVerticalScrollFactor() {
21280        if (mVerticalScrollFactor == 0) {
21281            TypedValue outValue = new TypedValue();
21282            if (!mContext.getTheme().resolveAttribute(
21283                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
21284                throw new IllegalStateException(
21285                        "Expected theme to define listPreferredItemHeight.");
21286            }
21287            mVerticalScrollFactor = outValue.getDimension(
21288                    mContext.getResources().getDisplayMetrics());
21289        }
21290        return mVerticalScrollFactor;
21291    }
21292
21293    /**
21294     * Gets a scale factor that determines the distance the view should scroll
21295     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
21296     * @return The horizontal scroll scale factor.
21297     * @hide
21298     */
21299    protected float getHorizontalScrollFactor() {
21300        // TODO: Should use something else.
21301        return getVerticalScrollFactor();
21302    }
21303
21304    /**
21305     * Return the value specifying the text direction or policy that was set with
21306     * {@link #setTextDirection(int)}.
21307     *
21308     * @return the defined text direction. It can be one of:
21309     *
21310     * {@link #TEXT_DIRECTION_INHERIT},
21311     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21312     * {@link #TEXT_DIRECTION_ANY_RTL},
21313     * {@link #TEXT_DIRECTION_LTR},
21314     * {@link #TEXT_DIRECTION_RTL},
21315     * {@link #TEXT_DIRECTION_LOCALE},
21316     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21317     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21318     *
21319     * @attr ref android.R.styleable#View_textDirection
21320     *
21321     * @hide
21322     */
21323    @ViewDebug.ExportedProperty(category = "text", mapping = {
21324            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21325            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21326            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21327            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21328            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21329            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21330            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21331            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21332    })
21333    public int getRawTextDirection() {
21334        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
21335    }
21336
21337    /**
21338     * Set the text direction.
21339     *
21340     * @param textDirection the direction to set. Should be one of:
21341     *
21342     * {@link #TEXT_DIRECTION_INHERIT},
21343     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21344     * {@link #TEXT_DIRECTION_ANY_RTL},
21345     * {@link #TEXT_DIRECTION_LTR},
21346     * {@link #TEXT_DIRECTION_RTL},
21347     * {@link #TEXT_DIRECTION_LOCALE}
21348     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21349     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
21350     *
21351     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
21352     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
21353     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
21354     *
21355     * @attr ref android.R.styleable#View_textDirection
21356     */
21357    public void setTextDirection(int textDirection) {
21358        if (getRawTextDirection() != textDirection) {
21359            // Reset the current text direction and the resolved one
21360            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
21361            resetResolvedTextDirection();
21362            // Set the new text direction
21363            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
21364            // Do resolution
21365            resolveTextDirection();
21366            // Notify change
21367            onRtlPropertiesChanged(getLayoutDirection());
21368            // Refresh
21369            requestLayout();
21370            invalidate(true);
21371        }
21372    }
21373
21374    /**
21375     * Return the resolved text direction.
21376     *
21377     * @return the resolved text direction. Returns one of:
21378     *
21379     * {@link #TEXT_DIRECTION_FIRST_STRONG},
21380     * {@link #TEXT_DIRECTION_ANY_RTL},
21381     * {@link #TEXT_DIRECTION_LTR},
21382     * {@link #TEXT_DIRECTION_RTL},
21383     * {@link #TEXT_DIRECTION_LOCALE},
21384     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
21385     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
21386     *
21387     * @attr ref android.R.styleable#View_textDirection
21388     */
21389    @ViewDebug.ExportedProperty(category = "text", mapping = {
21390            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
21391            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
21392            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
21393            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
21394            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
21395            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
21396            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
21397            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
21398    })
21399    public int getTextDirection() {
21400        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
21401    }
21402
21403    /**
21404     * Resolve the text direction.
21405     *
21406     * @return true if resolution has been done, false otherwise.
21407     *
21408     * @hide
21409     */
21410    public boolean resolveTextDirection() {
21411        // Reset any previous text direction resolution
21412        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21413
21414        if (hasRtlSupport()) {
21415            // Set resolved text direction flag depending on text direction flag
21416            final int textDirection = getRawTextDirection();
21417            switch(textDirection) {
21418                case TEXT_DIRECTION_INHERIT:
21419                    if (!canResolveTextDirection()) {
21420                        // We cannot do the resolution if there is no parent, so use the default one
21421                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21422                        // Resolution will need to happen again later
21423                        return false;
21424                    }
21425
21426                    // Parent has not yet resolved, so we still return the default
21427                    try {
21428                        if (!mParent.isTextDirectionResolved()) {
21429                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21430                            // Resolution will need to happen again later
21431                            return false;
21432                        }
21433                    } catch (AbstractMethodError e) {
21434                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21435                                " does not fully implement ViewParent", e);
21436                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
21437                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21438                        return true;
21439                    }
21440
21441                    // Set current resolved direction to the same value as the parent's one
21442                    int parentResolvedDirection;
21443                    try {
21444                        parentResolvedDirection = mParent.getTextDirection();
21445                    } catch (AbstractMethodError e) {
21446                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21447                                " does not fully implement ViewParent", e);
21448                        parentResolvedDirection = TEXT_DIRECTION_LTR;
21449                    }
21450                    switch (parentResolvedDirection) {
21451                        case TEXT_DIRECTION_FIRST_STRONG:
21452                        case TEXT_DIRECTION_ANY_RTL:
21453                        case TEXT_DIRECTION_LTR:
21454                        case TEXT_DIRECTION_RTL:
21455                        case TEXT_DIRECTION_LOCALE:
21456                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
21457                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
21458                            mPrivateFlags2 |=
21459                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21460                            break;
21461                        default:
21462                            // Default resolved direction is "first strong" heuristic
21463                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21464                    }
21465                    break;
21466                case TEXT_DIRECTION_FIRST_STRONG:
21467                case TEXT_DIRECTION_ANY_RTL:
21468                case TEXT_DIRECTION_LTR:
21469                case TEXT_DIRECTION_RTL:
21470                case TEXT_DIRECTION_LOCALE:
21471                case TEXT_DIRECTION_FIRST_STRONG_LTR:
21472                case TEXT_DIRECTION_FIRST_STRONG_RTL:
21473                    // Resolved direction is the same as text direction
21474                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
21475                    break;
21476                default:
21477                    // Default resolved direction is "first strong" heuristic
21478                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21479            }
21480        } else {
21481            // Default resolved direction is "first strong" heuristic
21482            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21483        }
21484
21485        // Set to resolved
21486        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
21487        return true;
21488    }
21489
21490    /**
21491     * Check if text direction resolution can be done.
21492     *
21493     * @return true if text direction resolution can be done otherwise return false.
21494     */
21495    public boolean canResolveTextDirection() {
21496        switch (getRawTextDirection()) {
21497            case TEXT_DIRECTION_INHERIT:
21498                if (mParent != null) {
21499                    try {
21500                        return mParent.canResolveTextDirection();
21501                    } catch (AbstractMethodError e) {
21502                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21503                                " does not fully implement ViewParent", e);
21504                    }
21505                }
21506                return false;
21507
21508            default:
21509                return true;
21510        }
21511    }
21512
21513    /**
21514     * Reset resolved text direction. Text direction will be resolved during a call to
21515     * {@link #onMeasure(int, int)}.
21516     *
21517     * @hide
21518     */
21519    public void resetResolvedTextDirection() {
21520        // Reset any previous text direction resolution
21521        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
21522        // Set to default value
21523        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
21524    }
21525
21526    /**
21527     * @return true if text direction is inherited.
21528     *
21529     * @hide
21530     */
21531    public boolean isTextDirectionInherited() {
21532        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
21533    }
21534
21535    /**
21536     * @return true if text direction is resolved.
21537     */
21538    public boolean isTextDirectionResolved() {
21539        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
21540    }
21541
21542    /**
21543     * Return the value specifying the text alignment or policy that was set with
21544     * {@link #setTextAlignment(int)}.
21545     *
21546     * @return the defined text alignment. It can be one of:
21547     *
21548     * {@link #TEXT_ALIGNMENT_INHERIT},
21549     * {@link #TEXT_ALIGNMENT_GRAVITY},
21550     * {@link #TEXT_ALIGNMENT_CENTER},
21551     * {@link #TEXT_ALIGNMENT_TEXT_START},
21552     * {@link #TEXT_ALIGNMENT_TEXT_END},
21553     * {@link #TEXT_ALIGNMENT_VIEW_START},
21554     * {@link #TEXT_ALIGNMENT_VIEW_END}
21555     *
21556     * @attr ref android.R.styleable#View_textAlignment
21557     *
21558     * @hide
21559     */
21560    @ViewDebug.ExportedProperty(category = "text", mapping = {
21561            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21562            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21563            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21564            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21565            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21566            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21567            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21568    })
21569    @TextAlignment
21570    public int getRawTextAlignment() {
21571        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
21572    }
21573
21574    /**
21575     * Set the text alignment.
21576     *
21577     * @param textAlignment The text alignment to set. Should be one of
21578     *
21579     * {@link #TEXT_ALIGNMENT_INHERIT},
21580     * {@link #TEXT_ALIGNMENT_GRAVITY},
21581     * {@link #TEXT_ALIGNMENT_CENTER},
21582     * {@link #TEXT_ALIGNMENT_TEXT_START},
21583     * {@link #TEXT_ALIGNMENT_TEXT_END},
21584     * {@link #TEXT_ALIGNMENT_VIEW_START},
21585     * {@link #TEXT_ALIGNMENT_VIEW_END}
21586     *
21587     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
21588     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
21589     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
21590     *
21591     * @attr ref android.R.styleable#View_textAlignment
21592     */
21593    public void setTextAlignment(@TextAlignment int textAlignment) {
21594        if (textAlignment != getRawTextAlignment()) {
21595            // Reset the current and resolved text alignment
21596            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
21597            resetResolvedTextAlignment();
21598            // Set the new text alignment
21599            mPrivateFlags2 |=
21600                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
21601            // Do resolution
21602            resolveTextAlignment();
21603            // Notify change
21604            onRtlPropertiesChanged(getLayoutDirection());
21605            // Refresh
21606            requestLayout();
21607            invalidate(true);
21608        }
21609    }
21610
21611    /**
21612     * Return the resolved text alignment.
21613     *
21614     * @return the resolved text alignment. Returns one of:
21615     *
21616     * {@link #TEXT_ALIGNMENT_GRAVITY},
21617     * {@link #TEXT_ALIGNMENT_CENTER},
21618     * {@link #TEXT_ALIGNMENT_TEXT_START},
21619     * {@link #TEXT_ALIGNMENT_TEXT_END},
21620     * {@link #TEXT_ALIGNMENT_VIEW_START},
21621     * {@link #TEXT_ALIGNMENT_VIEW_END}
21622     *
21623     * @attr ref android.R.styleable#View_textAlignment
21624     */
21625    @ViewDebug.ExportedProperty(category = "text", mapping = {
21626            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
21627            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
21628            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
21629            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
21630            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
21631            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
21632            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
21633    })
21634    @TextAlignment
21635    public int getTextAlignment() {
21636        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
21637                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
21638    }
21639
21640    /**
21641     * Resolve the text alignment.
21642     *
21643     * @return true if resolution has been done, false otherwise.
21644     *
21645     * @hide
21646     */
21647    public boolean resolveTextAlignment() {
21648        // Reset any previous text alignment resolution
21649        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21650
21651        if (hasRtlSupport()) {
21652            // Set resolved text alignment flag depending on text alignment flag
21653            final int textAlignment = getRawTextAlignment();
21654            switch (textAlignment) {
21655                case TEXT_ALIGNMENT_INHERIT:
21656                    // Check if we can resolve the text alignment
21657                    if (!canResolveTextAlignment()) {
21658                        // We cannot do the resolution if there is no parent so use the default
21659                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21660                        // Resolution will need to happen again later
21661                        return false;
21662                    }
21663
21664                    // Parent has not yet resolved, so we still return the default
21665                    try {
21666                        if (!mParent.isTextAlignmentResolved()) {
21667                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21668                            // Resolution will need to happen again later
21669                            return false;
21670                        }
21671                    } catch (AbstractMethodError e) {
21672                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21673                                " does not fully implement ViewParent", e);
21674                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
21675                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21676                        return true;
21677                    }
21678
21679                    int parentResolvedTextAlignment;
21680                    try {
21681                        parentResolvedTextAlignment = mParent.getTextAlignment();
21682                    } catch (AbstractMethodError e) {
21683                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21684                                " does not fully implement ViewParent", e);
21685                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
21686                    }
21687                    switch (parentResolvedTextAlignment) {
21688                        case TEXT_ALIGNMENT_GRAVITY:
21689                        case TEXT_ALIGNMENT_TEXT_START:
21690                        case TEXT_ALIGNMENT_TEXT_END:
21691                        case TEXT_ALIGNMENT_CENTER:
21692                        case TEXT_ALIGNMENT_VIEW_START:
21693                        case TEXT_ALIGNMENT_VIEW_END:
21694                            // Resolved text alignment is the same as the parent resolved
21695                            // text alignment
21696                            mPrivateFlags2 |=
21697                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21698                            break;
21699                        default:
21700                            // Use default resolved text alignment
21701                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21702                    }
21703                    break;
21704                case TEXT_ALIGNMENT_GRAVITY:
21705                case TEXT_ALIGNMENT_TEXT_START:
21706                case TEXT_ALIGNMENT_TEXT_END:
21707                case TEXT_ALIGNMENT_CENTER:
21708                case TEXT_ALIGNMENT_VIEW_START:
21709                case TEXT_ALIGNMENT_VIEW_END:
21710                    // Resolved text alignment is the same as text alignment
21711                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
21712                    break;
21713                default:
21714                    // Use default resolved text alignment
21715                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21716            }
21717        } else {
21718            // Use default resolved text alignment
21719            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21720        }
21721
21722        // Set the resolved
21723        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21724        return true;
21725    }
21726
21727    /**
21728     * Check if text alignment resolution can be done.
21729     *
21730     * @return true if text alignment resolution can be done otherwise return false.
21731     */
21732    public boolean canResolveTextAlignment() {
21733        switch (getRawTextAlignment()) {
21734            case TEXT_DIRECTION_INHERIT:
21735                if (mParent != null) {
21736                    try {
21737                        return mParent.canResolveTextAlignment();
21738                    } catch (AbstractMethodError e) {
21739                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
21740                                " does not fully implement ViewParent", e);
21741                    }
21742                }
21743                return false;
21744
21745            default:
21746                return true;
21747        }
21748    }
21749
21750    /**
21751     * Reset resolved text alignment. Text alignment will be resolved during a call to
21752     * {@link #onMeasure(int, int)}.
21753     *
21754     * @hide
21755     */
21756    public void resetResolvedTextAlignment() {
21757        // Reset any previous text alignment resolution
21758        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
21759        // Set to default
21760        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
21761    }
21762
21763    /**
21764     * @return true if text alignment is inherited.
21765     *
21766     * @hide
21767     */
21768    public boolean isTextAlignmentInherited() {
21769        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
21770    }
21771
21772    /**
21773     * @return true if text alignment is resolved.
21774     */
21775    public boolean isTextAlignmentResolved() {
21776        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
21777    }
21778
21779    /**
21780     * Generate a value suitable for use in {@link #setId(int)}.
21781     * This value will not collide with ID values generated at build time by aapt for R.id.
21782     *
21783     * @return a generated ID value
21784     */
21785    public static int generateViewId() {
21786        for (;;) {
21787            final int result = sNextGeneratedId.get();
21788            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
21789            int newValue = result + 1;
21790            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
21791            if (sNextGeneratedId.compareAndSet(result, newValue)) {
21792                return result;
21793            }
21794        }
21795    }
21796
21797    /**
21798     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
21799     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
21800     *                           a normal View or a ViewGroup with
21801     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
21802     * @hide
21803     */
21804    public void captureTransitioningViews(List<View> transitioningViews) {
21805        if (getVisibility() == View.VISIBLE) {
21806            transitioningViews.add(this);
21807        }
21808    }
21809
21810    /**
21811     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
21812     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
21813     * @hide
21814     */
21815    public void findNamedViews(Map<String, View> namedElements) {
21816        if (getVisibility() == VISIBLE || mGhostView != null) {
21817            String transitionName = getTransitionName();
21818            if (transitionName != null) {
21819                namedElements.put(transitionName, this);
21820            }
21821        }
21822    }
21823
21824    /**
21825     * Returns the pointer icon for the motion event, or null if it doesn't specify the icon.
21826     * The default implementation does not care the location or event types, but some subclasses
21827     * may use it (such as WebViews).
21828     * @param event The MotionEvent from a mouse
21829     * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}.
21830     *                     This will be between 0 and {@link MotionEvent#getPointerCount()}.
21831     * @see PointerIcon
21832     */
21833    public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
21834        final float x = event.getX(pointerIndex);
21835        final float y = event.getY(pointerIndex);
21836        if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) {
21837            return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW);
21838        }
21839        return mPointerIcon;
21840    }
21841
21842    /**
21843     * Set the pointer icon for the current view.
21844     * Passing {@code null} will restore the pointer icon to its default value.
21845     * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers.
21846     */
21847    public void setPointerIcon(PointerIcon pointerIcon) {
21848        mPointerIcon = pointerIcon;
21849        if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) {
21850            return;
21851        }
21852        try {
21853            mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow);
21854        } catch (RemoteException e) {
21855        }
21856    }
21857
21858    /**
21859     * Gets the pointer icon for the current view.
21860     */
21861    public PointerIcon getPointerIcon() {
21862        return mPointerIcon;
21863    }
21864
21865    //
21866    // Properties
21867    //
21868    /**
21869     * A Property wrapper around the <code>alpha</code> functionality handled by the
21870     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
21871     */
21872    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
21873        @Override
21874        public void setValue(View object, float value) {
21875            object.setAlpha(value);
21876        }
21877
21878        @Override
21879        public Float get(View object) {
21880            return object.getAlpha();
21881        }
21882    };
21883
21884    /**
21885     * A Property wrapper around the <code>translationX</code> functionality handled by the
21886     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
21887     */
21888    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
21889        @Override
21890        public void setValue(View object, float value) {
21891            object.setTranslationX(value);
21892        }
21893
21894                @Override
21895        public Float get(View object) {
21896            return object.getTranslationX();
21897        }
21898    };
21899
21900    /**
21901     * A Property wrapper around the <code>translationY</code> functionality handled by the
21902     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
21903     */
21904    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
21905        @Override
21906        public void setValue(View object, float value) {
21907            object.setTranslationY(value);
21908        }
21909
21910        @Override
21911        public Float get(View object) {
21912            return object.getTranslationY();
21913        }
21914    };
21915
21916    /**
21917     * A Property wrapper around the <code>translationZ</code> functionality handled by the
21918     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
21919     */
21920    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
21921        @Override
21922        public void setValue(View object, float value) {
21923            object.setTranslationZ(value);
21924        }
21925
21926        @Override
21927        public Float get(View object) {
21928            return object.getTranslationZ();
21929        }
21930    };
21931
21932    /**
21933     * A Property wrapper around the <code>x</code> functionality handled by the
21934     * {@link View#setX(float)} and {@link View#getX()} methods.
21935     */
21936    public static final Property<View, Float> X = new FloatProperty<View>("x") {
21937        @Override
21938        public void setValue(View object, float value) {
21939            object.setX(value);
21940        }
21941
21942        @Override
21943        public Float get(View object) {
21944            return object.getX();
21945        }
21946    };
21947
21948    /**
21949     * A Property wrapper around the <code>y</code> functionality handled by the
21950     * {@link View#setY(float)} and {@link View#getY()} methods.
21951     */
21952    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
21953        @Override
21954        public void setValue(View object, float value) {
21955            object.setY(value);
21956        }
21957
21958        @Override
21959        public Float get(View object) {
21960            return object.getY();
21961        }
21962    };
21963
21964    /**
21965     * A Property wrapper around the <code>z</code> functionality handled by the
21966     * {@link View#setZ(float)} and {@link View#getZ()} methods.
21967     */
21968    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
21969        @Override
21970        public void setValue(View object, float value) {
21971            object.setZ(value);
21972        }
21973
21974        @Override
21975        public Float get(View object) {
21976            return object.getZ();
21977        }
21978    };
21979
21980    /**
21981     * A Property wrapper around the <code>rotation</code> functionality handled by the
21982     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
21983     */
21984    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
21985        @Override
21986        public void setValue(View object, float value) {
21987            object.setRotation(value);
21988        }
21989
21990        @Override
21991        public Float get(View object) {
21992            return object.getRotation();
21993        }
21994    };
21995
21996    /**
21997     * A Property wrapper around the <code>rotationX</code> functionality handled by the
21998     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
21999     */
22000    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
22001        @Override
22002        public void setValue(View object, float value) {
22003            object.setRotationX(value);
22004        }
22005
22006        @Override
22007        public Float get(View object) {
22008            return object.getRotationX();
22009        }
22010    };
22011
22012    /**
22013     * A Property wrapper around the <code>rotationY</code> functionality handled by the
22014     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
22015     */
22016    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
22017        @Override
22018        public void setValue(View object, float value) {
22019            object.setRotationY(value);
22020        }
22021
22022        @Override
22023        public Float get(View object) {
22024            return object.getRotationY();
22025        }
22026    };
22027
22028    /**
22029     * A Property wrapper around the <code>scaleX</code> functionality handled by the
22030     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
22031     */
22032    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
22033        @Override
22034        public void setValue(View object, float value) {
22035            object.setScaleX(value);
22036        }
22037
22038        @Override
22039        public Float get(View object) {
22040            return object.getScaleX();
22041        }
22042    };
22043
22044    /**
22045     * A Property wrapper around the <code>scaleY</code> functionality handled by the
22046     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
22047     */
22048    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
22049        @Override
22050        public void setValue(View object, float value) {
22051            object.setScaleY(value);
22052        }
22053
22054        @Override
22055        public Float get(View object) {
22056            return object.getScaleY();
22057        }
22058    };
22059
22060    /**
22061     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
22062     * Each MeasureSpec represents a requirement for either the width or the height.
22063     * A MeasureSpec is comprised of a size and a mode. There are three possible
22064     * modes:
22065     * <dl>
22066     * <dt>UNSPECIFIED</dt>
22067     * <dd>
22068     * The parent has not imposed any constraint on the child. It can be whatever size
22069     * it wants.
22070     * </dd>
22071     *
22072     * <dt>EXACTLY</dt>
22073     * <dd>
22074     * The parent has determined an exact size for the child. The child is going to be
22075     * given those bounds regardless of how big it wants to be.
22076     * </dd>
22077     *
22078     * <dt>AT_MOST</dt>
22079     * <dd>
22080     * The child can be as large as it wants up to the specified size.
22081     * </dd>
22082     * </dl>
22083     *
22084     * MeasureSpecs are implemented as ints to reduce object allocation. This class
22085     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
22086     */
22087    public static class MeasureSpec {
22088        private static final int MODE_SHIFT = 30;
22089        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
22090
22091        /** @hide */
22092        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
22093        @Retention(RetentionPolicy.SOURCE)
22094        public @interface MeasureSpecMode {}
22095
22096        /**
22097         * Measure specification mode: The parent has not imposed any constraint
22098         * on the child. It can be whatever size it wants.
22099         */
22100        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
22101
22102        /**
22103         * Measure specification mode: The parent has determined an exact size
22104         * for the child. The child is going to be given those bounds regardless
22105         * of how big it wants to be.
22106         */
22107        public static final int EXACTLY     = 1 << MODE_SHIFT;
22108
22109        /**
22110         * Measure specification mode: The child can be as large as it wants up
22111         * to the specified size.
22112         */
22113        public static final int AT_MOST     = 2 << MODE_SHIFT;
22114
22115        /**
22116         * Creates a measure specification based on the supplied size and mode.
22117         *
22118         * The mode must always be one of the following:
22119         * <ul>
22120         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
22121         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
22122         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
22123         * </ul>
22124         *
22125         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
22126         * implementation was such that the order of arguments did not matter
22127         * and overflow in either value could impact the resulting MeasureSpec.
22128         * {@link android.widget.RelativeLayout} was affected by this bug.
22129         * Apps targeting API levels greater than 17 will get the fixed, more strict
22130         * behavior.</p>
22131         *
22132         * @param size the size of the measure specification
22133         * @param mode the mode of the measure specification
22134         * @return the measure specification based on size and mode
22135         */
22136        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
22137                                          @MeasureSpecMode int mode) {
22138            if (sUseBrokenMakeMeasureSpec) {
22139                return size + mode;
22140            } else {
22141                return (size & ~MODE_MASK) | (mode & MODE_MASK);
22142            }
22143        }
22144
22145        /**
22146         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
22147         * will automatically get a size of 0. Older apps expect this.
22148         *
22149         * @hide internal use only for compatibility with system widgets and older apps
22150         */
22151        public static int makeSafeMeasureSpec(int size, int mode) {
22152            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
22153                return 0;
22154            }
22155            return makeMeasureSpec(size, mode);
22156        }
22157
22158        /**
22159         * Extracts the mode from the supplied measure specification.
22160         *
22161         * @param measureSpec the measure specification to extract the mode from
22162         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
22163         *         {@link android.view.View.MeasureSpec#AT_MOST} or
22164         *         {@link android.view.View.MeasureSpec#EXACTLY}
22165         */
22166        @MeasureSpecMode
22167        public static int getMode(int measureSpec) {
22168            //noinspection ResourceType
22169            return (measureSpec & MODE_MASK);
22170        }
22171
22172        /**
22173         * Extracts the size from the supplied measure specification.
22174         *
22175         * @param measureSpec the measure specification to extract the size from
22176         * @return the size in pixels defined in the supplied measure specification
22177         */
22178        public static int getSize(int measureSpec) {
22179            return (measureSpec & ~MODE_MASK);
22180        }
22181
22182        static int adjust(int measureSpec, int delta) {
22183            final int mode = getMode(measureSpec);
22184            int size = getSize(measureSpec);
22185            if (mode == UNSPECIFIED) {
22186                // No need to adjust size for UNSPECIFIED mode.
22187                return makeMeasureSpec(size, UNSPECIFIED);
22188            }
22189            size += delta;
22190            if (size < 0) {
22191                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
22192                        ") spec: " + toString(measureSpec) + " delta: " + delta);
22193                size = 0;
22194            }
22195            return makeMeasureSpec(size, mode);
22196        }
22197
22198        /**
22199         * Returns a String representation of the specified measure
22200         * specification.
22201         *
22202         * @param measureSpec the measure specification to convert to a String
22203         * @return a String with the following format: "MeasureSpec: MODE SIZE"
22204         */
22205        public static String toString(int measureSpec) {
22206            int mode = getMode(measureSpec);
22207            int size = getSize(measureSpec);
22208
22209            StringBuilder sb = new StringBuilder("MeasureSpec: ");
22210
22211            if (mode == UNSPECIFIED)
22212                sb.append("UNSPECIFIED ");
22213            else if (mode == EXACTLY)
22214                sb.append("EXACTLY ");
22215            else if (mode == AT_MOST)
22216                sb.append("AT_MOST ");
22217            else
22218                sb.append(mode).append(" ");
22219
22220            sb.append(size);
22221            return sb.toString();
22222        }
22223    }
22224
22225    private final class CheckForLongPress implements Runnable {
22226        private int mOriginalWindowAttachCount;
22227        private float mX;
22228        private float mY;
22229
22230        @Override
22231        public void run() {
22232            if (isPressed() && (mParent != null)
22233                    && mOriginalWindowAttachCount == mWindowAttachCount) {
22234                if (performLongClick(mX, mY)) {
22235                    mHasPerformedLongPress = true;
22236                }
22237            }
22238        }
22239
22240        public void setAnchor(float x, float y) {
22241            mX = x;
22242            mY = y;
22243        }
22244
22245        public void rememberWindowAttachCount() {
22246            mOriginalWindowAttachCount = mWindowAttachCount;
22247        }
22248    }
22249
22250    private final class CheckForTap implements Runnable {
22251        public float x;
22252        public float y;
22253
22254        @Override
22255        public void run() {
22256            mPrivateFlags &= ~PFLAG_PREPRESSED;
22257            setPressed(true, x, y);
22258            checkForLongClick(ViewConfiguration.getTapTimeout(), x, y);
22259        }
22260    }
22261
22262    private final class PerformClick implements Runnable {
22263        @Override
22264        public void run() {
22265            performClick();
22266        }
22267    }
22268
22269    /**
22270     * This method returns a ViewPropertyAnimator object, which can be used to animate
22271     * specific properties on this View.
22272     *
22273     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
22274     */
22275    public ViewPropertyAnimator animate() {
22276        if (mAnimator == null) {
22277            mAnimator = new ViewPropertyAnimator(this);
22278        }
22279        return mAnimator;
22280    }
22281
22282    /**
22283     * Sets the name of the View to be used to identify Views in Transitions.
22284     * Names should be unique in the View hierarchy.
22285     *
22286     * @param transitionName The name of the View to uniquely identify it for Transitions.
22287     */
22288    public final void setTransitionName(String transitionName) {
22289        mTransitionName = transitionName;
22290    }
22291
22292    /**
22293     * Returns the name of the View to be used to identify Views in Transitions.
22294     * Names should be unique in the View hierarchy.
22295     *
22296     * <p>This returns null if the View has not been given a name.</p>
22297     *
22298     * @return The name used of the View to be used to identify Views in Transitions or null
22299     * if no name has been given.
22300     */
22301    @ViewDebug.ExportedProperty
22302    public String getTransitionName() {
22303        return mTransitionName;
22304    }
22305
22306    /**
22307     * @hide
22308     */
22309    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) {
22310        // Do nothing.
22311    }
22312
22313    /**
22314     * Interface definition for a callback to be invoked when a hardware key event is
22315     * dispatched to this view. The callback will be invoked before the key event is
22316     * given to the view. This is only useful for hardware keyboards; a software input
22317     * method has no obligation to trigger this listener.
22318     */
22319    public interface OnKeyListener {
22320        /**
22321         * Called when a hardware key is dispatched to a view. This allows listeners to
22322         * get a chance to respond before the target view.
22323         * <p>Key presses in software keyboards will generally NOT trigger this method,
22324         * although some may elect to do so in some situations. Do not assume a
22325         * software input method has to be key-based; even if it is, it may use key presses
22326         * in a different way than you expect, so there is no way to reliably catch soft
22327         * input key presses.
22328         *
22329         * @param v The view the key has been dispatched to.
22330         * @param keyCode The code for the physical key that was pressed
22331         * @param event The KeyEvent object containing full information about
22332         *        the event.
22333         * @return True if the listener has consumed the event, false otherwise.
22334         */
22335        boolean onKey(View v, int keyCode, KeyEvent event);
22336    }
22337
22338    /**
22339     * Interface definition for a callback to be invoked when a touch event is
22340     * dispatched to this view. The callback will be invoked before the touch
22341     * event is given to the view.
22342     */
22343    public interface OnTouchListener {
22344        /**
22345         * Called when a touch event is dispatched to a view. This allows listeners to
22346         * get a chance to respond before the target view.
22347         *
22348         * @param v The view the touch event has been dispatched to.
22349         * @param event The MotionEvent object containing full information about
22350         *        the event.
22351         * @return True if the listener has consumed the event, false otherwise.
22352         */
22353        boolean onTouch(View v, MotionEvent event);
22354    }
22355
22356    /**
22357     * Interface definition for a callback to be invoked when a hover event is
22358     * dispatched to this view. The callback will be invoked before the hover
22359     * event is given to the view.
22360     */
22361    public interface OnHoverListener {
22362        /**
22363         * Called when a hover event is dispatched to a view. This allows listeners to
22364         * get a chance to respond before the target view.
22365         *
22366         * @param v The view the hover event has been dispatched to.
22367         * @param event The MotionEvent object containing full information about
22368         *        the event.
22369         * @return True if the listener has consumed the event, false otherwise.
22370         */
22371        boolean onHover(View v, MotionEvent event);
22372    }
22373
22374    /**
22375     * Interface definition for a callback to be invoked when a generic motion event is
22376     * dispatched to this view. The callback will be invoked before the generic motion
22377     * event is given to the view.
22378     */
22379    public interface OnGenericMotionListener {
22380        /**
22381         * Called when a generic motion event is dispatched to a view. This allows listeners to
22382         * get a chance to respond before the target view.
22383         *
22384         * @param v The view the generic motion event has been dispatched to.
22385         * @param event The MotionEvent object containing full information about
22386         *        the event.
22387         * @return True if the listener has consumed the event, false otherwise.
22388         */
22389        boolean onGenericMotion(View v, MotionEvent event);
22390    }
22391
22392    /**
22393     * Interface definition for a callback to be invoked when a view has been clicked and held.
22394     */
22395    public interface OnLongClickListener {
22396        /**
22397         * Called when a view has been clicked and held.
22398         *
22399         * @param v The view that was clicked and held.
22400         *
22401         * @return true if the callback consumed the long click, false otherwise.
22402         */
22403        boolean onLongClick(View v);
22404    }
22405
22406    /**
22407     * Interface definition for a callback to be invoked when a drag is being dispatched
22408     * to this view.  The callback will be invoked before the hosting view's own
22409     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
22410     * onDrag(event) behavior, it should return 'false' from this callback.
22411     *
22412     * <div class="special reference">
22413     * <h3>Developer Guides</h3>
22414     * <p>For a guide to implementing drag and drop features, read the
22415     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
22416     * </div>
22417     */
22418    public interface OnDragListener {
22419        /**
22420         * Called when a drag event is dispatched to a view. This allows listeners
22421         * to get a chance to override base View behavior.
22422         *
22423         * @param v The View that received the drag event.
22424         * @param event The {@link android.view.DragEvent} object for the drag event.
22425         * @return {@code true} if the drag event was handled successfully, or {@code false}
22426         * if the drag event was not handled. Note that {@code false} will trigger the View
22427         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
22428         */
22429        boolean onDrag(View v, DragEvent event);
22430    }
22431
22432    /**
22433     * Interface definition for a callback to be invoked when the focus state of
22434     * a view changed.
22435     */
22436    public interface OnFocusChangeListener {
22437        /**
22438         * Called when the focus state of a view has changed.
22439         *
22440         * @param v The view whose state has changed.
22441         * @param hasFocus The new focus state of v.
22442         */
22443        void onFocusChange(View v, boolean hasFocus);
22444    }
22445
22446    /**
22447     * Interface definition for a callback to be invoked when a view is clicked.
22448     */
22449    public interface OnClickListener {
22450        /**
22451         * Called when a view has been clicked.
22452         *
22453         * @param v The view that was clicked.
22454         */
22455        void onClick(View v);
22456    }
22457
22458    /**
22459     * Interface definition for a callback to be invoked when a view is context clicked.
22460     */
22461    public interface OnContextClickListener {
22462        /**
22463         * Called when a view is context clicked.
22464         *
22465         * @param v The view that has been context clicked.
22466         * @return true if the callback consumed the context click, false otherwise.
22467         */
22468        boolean onContextClick(View v);
22469    }
22470
22471    /**
22472     * Interface definition for a callback to be invoked when the context menu
22473     * for this view is being built.
22474     */
22475    public interface OnCreateContextMenuListener {
22476        /**
22477         * Called when the context menu for this view is being built. It is not
22478         * safe to hold onto the menu after this method returns.
22479         *
22480         * @param menu The context menu that is being built
22481         * @param v The view for which the context menu is being built
22482         * @param menuInfo Extra information about the item for which the
22483         *            context menu should be shown. This information will vary
22484         *            depending on the class of v.
22485         */
22486        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
22487    }
22488
22489    /**
22490     * Interface definition for a callback to be invoked when the status bar changes
22491     * visibility.  This reports <strong>global</strong> changes to the system UI
22492     * state, not what the application is requesting.
22493     *
22494     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
22495     */
22496    public interface OnSystemUiVisibilityChangeListener {
22497        /**
22498         * Called when the status bar changes visibility because of a call to
22499         * {@link View#setSystemUiVisibility(int)}.
22500         *
22501         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
22502         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
22503         * This tells you the <strong>global</strong> state of these UI visibility
22504         * flags, not what your app is currently applying.
22505         */
22506        public void onSystemUiVisibilityChange(int visibility);
22507    }
22508
22509    /**
22510     * Interface definition for a callback to be invoked when this view is attached
22511     * or detached from its window.
22512     */
22513    public interface OnAttachStateChangeListener {
22514        /**
22515         * Called when the view is attached to a window.
22516         * @param v The view that was attached
22517         */
22518        public void onViewAttachedToWindow(View v);
22519        /**
22520         * Called when the view is detached from a window.
22521         * @param v The view that was detached
22522         */
22523        public void onViewDetachedFromWindow(View v);
22524    }
22525
22526    /**
22527     * Listener for applying window insets on a view in a custom way.
22528     *
22529     * <p>Apps may choose to implement this interface if they want to apply custom policy
22530     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
22531     * is set, its
22532     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
22533     * method will be called instead of the View's own
22534     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
22535     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
22536     * the View's normal behavior as part of its own.</p>
22537     */
22538    public interface OnApplyWindowInsetsListener {
22539        /**
22540         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
22541         * on a View, this listener method will be called instead of the view's own
22542         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
22543         *
22544         * @param v The view applying window insets
22545         * @param insets The insets to apply
22546         * @return The insets supplied, minus any insets that were consumed
22547         */
22548        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
22549    }
22550
22551    private final class UnsetPressedState implements Runnable {
22552        @Override
22553        public void run() {
22554            setPressed(false);
22555        }
22556    }
22557
22558    /**
22559     * Base class for derived classes that want to save and restore their own
22560     * state in {@link android.view.View#onSaveInstanceState()}.
22561     */
22562    public static class BaseSavedState extends AbsSavedState {
22563        String mStartActivityRequestWhoSaved;
22564
22565        /**
22566         * Constructor used when reading from a parcel. Reads the state of the superclass.
22567         *
22568         * @param source parcel to read from
22569         */
22570        public BaseSavedState(Parcel source) {
22571            this(source, null);
22572        }
22573
22574        /**
22575         * Constructor used when reading from a parcel using a given class loader.
22576         * Reads the state of the superclass.
22577         *
22578         * @param source parcel to read from
22579         * @param loader ClassLoader to use for reading
22580         */
22581        public BaseSavedState(Parcel source, ClassLoader loader) {
22582            super(source, loader);
22583            mStartActivityRequestWhoSaved = source.readString();
22584        }
22585
22586        /**
22587         * Constructor called by derived classes when creating their SavedState objects
22588         *
22589         * @param superState The state of the superclass of this view
22590         */
22591        public BaseSavedState(Parcelable superState) {
22592            super(superState);
22593        }
22594
22595        @Override
22596        public void writeToParcel(Parcel out, int flags) {
22597            super.writeToParcel(out, flags);
22598            out.writeString(mStartActivityRequestWhoSaved);
22599        }
22600
22601        public static final Parcelable.Creator<BaseSavedState> CREATOR
22602                = new Parcelable.ClassLoaderCreator<BaseSavedState>() {
22603            @Override
22604            public BaseSavedState createFromParcel(Parcel in) {
22605                return new BaseSavedState(in);
22606            }
22607
22608            @Override
22609            public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) {
22610                return new BaseSavedState(in, loader);
22611            }
22612
22613            @Override
22614            public BaseSavedState[] newArray(int size) {
22615                return new BaseSavedState[size];
22616            }
22617        };
22618    }
22619
22620    /**
22621     * A set of information given to a view when it is attached to its parent
22622     * window.
22623     */
22624    final static class AttachInfo {
22625        interface Callbacks {
22626            void playSoundEffect(int effectId);
22627            boolean performHapticFeedback(int effectId, boolean always);
22628        }
22629
22630        /**
22631         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
22632         * to a Handler. This class contains the target (View) to invalidate and
22633         * the coordinates of the dirty rectangle.
22634         *
22635         * For performance purposes, this class also implements a pool of up to
22636         * POOL_LIMIT objects that get reused. This reduces memory allocations
22637         * whenever possible.
22638         */
22639        static class InvalidateInfo {
22640            private static final int POOL_LIMIT = 10;
22641
22642            private static final SynchronizedPool<InvalidateInfo> sPool =
22643                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
22644
22645            View target;
22646
22647            int left;
22648            int top;
22649            int right;
22650            int bottom;
22651
22652            public static InvalidateInfo obtain() {
22653                InvalidateInfo instance = sPool.acquire();
22654                return (instance != null) ? instance : new InvalidateInfo();
22655            }
22656
22657            public void recycle() {
22658                target = null;
22659                sPool.release(this);
22660            }
22661        }
22662
22663        final IWindowSession mSession;
22664
22665        final IWindow mWindow;
22666
22667        final IBinder mWindowToken;
22668
22669        final Display mDisplay;
22670
22671        final Callbacks mRootCallbacks;
22672
22673        IWindowId mIWindowId;
22674        WindowId mWindowId;
22675
22676        /**
22677         * The top view of the hierarchy.
22678         */
22679        View mRootView;
22680
22681        IBinder mPanelParentWindowToken;
22682
22683        boolean mHardwareAccelerated;
22684        boolean mHardwareAccelerationRequested;
22685        ThreadedRenderer mThreadedRenderer;
22686        List<RenderNode> mPendingAnimatingRenderNodes;
22687
22688        /**
22689         * The state of the display to which the window is attached, as reported
22690         * by {@link Display#getState()}.  Note that the display state constants
22691         * declared by {@link Display} do not exactly line up with the screen state
22692         * constants declared by {@link View} (there are more display states than
22693         * screen states).
22694         */
22695        int mDisplayState = Display.STATE_UNKNOWN;
22696
22697        /**
22698         * Scale factor used by the compatibility mode
22699         */
22700        float mApplicationScale;
22701
22702        /**
22703         * Indicates whether the application is in compatibility mode
22704         */
22705        boolean mScalingRequired;
22706
22707        /**
22708         * Left position of this view's window
22709         */
22710        int mWindowLeft;
22711
22712        /**
22713         * Top position of this view's window
22714         */
22715        int mWindowTop;
22716
22717        /**
22718         * Indicates whether views need to use 32-bit drawing caches
22719         */
22720        boolean mUse32BitDrawingCache;
22721
22722        /**
22723         * For windows that are full-screen but using insets to layout inside
22724         * of the screen areas, these are the current insets to appear inside
22725         * the overscan area of the display.
22726         */
22727        final Rect mOverscanInsets = new Rect();
22728
22729        /**
22730         * For windows that are full-screen but using insets to layout inside
22731         * of the screen decorations, these are the current insets for the
22732         * content of the window.
22733         */
22734        final Rect mContentInsets = new Rect();
22735
22736        /**
22737         * For windows that are full-screen but using insets to layout inside
22738         * of the screen decorations, these are the current insets for the
22739         * actual visible parts of the window.
22740         */
22741        final Rect mVisibleInsets = new Rect();
22742
22743        /**
22744         * For windows that are full-screen but using insets to layout inside
22745         * of the screen decorations, these are the current insets for the
22746         * stable system windows.
22747         */
22748        final Rect mStableInsets = new Rect();
22749
22750        /**
22751         * For windows that include areas that are not covered by real surface these are the outsets
22752         * for real surface.
22753         */
22754        final Rect mOutsets = new Rect();
22755
22756        /**
22757         * In multi-window we force show the navigation bar. Because we don't want that the surface
22758         * size changes in this mode, we instead have a flag whether the navigation bar size should
22759         * always be consumed, so the app is treated like there is no virtual navigation bar at all.
22760         */
22761        boolean mAlwaysConsumeNavBar;
22762
22763        /**
22764         * The internal insets given by this window.  This value is
22765         * supplied by the client (through
22766         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
22767         * be given to the window manager when changed to be used in laying
22768         * out windows behind it.
22769         */
22770        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
22771                = new ViewTreeObserver.InternalInsetsInfo();
22772
22773        /**
22774         * Set to true when mGivenInternalInsets is non-empty.
22775         */
22776        boolean mHasNonEmptyGivenInternalInsets;
22777
22778        /**
22779         * All views in the window's hierarchy that serve as scroll containers,
22780         * used to determine if the window can be resized or must be panned
22781         * to adjust for a soft input area.
22782         */
22783        final ArrayList<View> mScrollContainers = new ArrayList<View>();
22784
22785        final KeyEvent.DispatcherState mKeyDispatchState
22786                = new KeyEvent.DispatcherState();
22787
22788        /**
22789         * Indicates whether the view's window currently has the focus.
22790         */
22791        boolean mHasWindowFocus;
22792
22793        /**
22794         * The current visibility of the window.
22795         */
22796        int mWindowVisibility;
22797
22798        /**
22799         * Indicates the time at which drawing started to occur.
22800         */
22801        long mDrawingTime;
22802
22803        /**
22804         * Indicates whether or not ignoring the DIRTY_MASK flags.
22805         */
22806        boolean mIgnoreDirtyState;
22807
22808        /**
22809         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
22810         * to avoid clearing that flag prematurely.
22811         */
22812        boolean mSetIgnoreDirtyState = false;
22813
22814        /**
22815         * Indicates whether the view's window is currently in touch mode.
22816         */
22817        boolean mInTouchMode;
22818
22819        /**
22820         * Indicates whether the view has requested unbuffered input dispatching for the current
22821         * event stream.
22822         */
22823        boolean mUnbufferedDispatchRequested;
22824
22825        /**
22826         * Indicates that ViewAncestor should trigger a global layout change
22827         * the next time it performs a traversal
22828         */
22829        boolean mRecomputeGlobalAttributes;
22830
22831        /**
22832         * Always report new attributes at next traversal.
22833         */
22834        boolean mForceReportNewAttributes;
22835
22836        /**
22837         * Set during a traveral if any views want to keep the screen on.
22838         */
22839        boolean mKeepScreenOn;
22840
22841        /**
22842         * Set during a traveral if the light center needs to be updated.
22843         */
22844        boolean mNeedsUpdateLightCenter;
22845
22846        /**
22847         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
22848         */
22849        int mSystemUiVisibility;
22850
22851        /**
22852         * Hack to force certain system UI visibility flags to be cleared.
22853         */
22854        int mDisabledSystemUiVisibility;
22855
22856        /**
22857         * Last global system UI visibility reported by the window manager.
22858         */
22859        int mGlobalSystemUiVisibility;
22860
22861        /**
22862         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
22863         * attached.
22864         */
22865        boolean mHasSystemUiListeners;
22866
22867        /**
22868         * Set if the window has requested to extend into the overscan region
22869         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
22870         */
22871        boolean mOverscanRequested;
22872
22873        /**
22874         * Set if the visibility of any views has changed.
22875         */
22876        boolean mViewVisibilityChanged;
22877
22878        /**
22879         * Set to true if a view has been scrolled.
22880         */
22881        boolean mViewScrollChanged;
22882
22883        /**
22884         * Set to true if high contrast mode enabled
22885         */
22886        boolean mHighContrastText;
22887
22888        /**
22889         * Set to true if a pointer event is currently being handled.
22890         */
22891        boolean mHandlingPointerEvent;
22892
22893        /**
22894         * Global to the view hierarchy used as a temporary for dealing with
22895         * x/y points in the transparent region computations.
22896         */
22897        final int[] mTransparentLocation = new int[2];
22898
22899        /**
22900         * Global to the view hierarchy used as a temporary for dealing with
22901         * x/y points in the ViewGroup.invalidateChild implementation.
22902         */
22903        final int[] mInvalidateChildLocation = new int[2];
22904
22905        /**
22906         * Global to the view hierarchy used as a temporary for dealng with
22907         * computing absolute on-screen location.
22908         */
22909        final int[] mTmpLocation = new int[2];
22910
22911        /**
22912         * Global to the view hierarchy used as a temporary for dealing with
22913         * x/y location when view is transformed.
22914         */
22915        final float[] mTmpTransformLocation = new float[2];
22916
22917        /**
22918         * The view tree observer used to dispatch global events like
22919         * layout, pre-draw, touch mode change, etc.
22920         */
22921        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
22922
22923        /**
22924         * A Canvas used by the view hierarchy to perform bitmap caching.
22925         */
22926        Canvas mCanvas;
22927
22928        /**
22929         * The view root impl.
22930         */
22931        final ViewRootImpl mViewRootImpl;
22932
22933        /**
22934         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
22935         * handler can be used to pump events in the UI events queue.
22936         */
22937        final Handler mHandler;
22938
22939        /**
22940         * Temporary for use in computing invalidate rectangles while
22941         * calling up the hierarchy.
22942         */
22943        final Rect mTmpInvalRect = new Rect();
22944
22945        /**
22946         * Temporary for use in computing hit areas with transformed views
22947         */
22948        final RectF mTmpTransformRect = new RectF();
22949
22950        /**
22951         * Temporary for use in computing hit areas with transformed views
22952         */
22953        final RectF mTmpTransformRect1 = new RectF();
22954
22955        /**
22956         * Temporary list of rectanges.
22957         */
22958        final List<RectF> mTmpRectList = new ArrayList<>();
22959
22960        /**
22961         * Temporary for use in transforming invalidation rect
22962         */
22963        final Matrix mTmpMatrix = new Matrix();
22964
22965        /**
22966         * Temporary for use in transforming invalidation rect
22967         */
22968        final Transformation mTmpTransformation = new Transformation();
22969
22970        /**
22971         * Temporary for use in querying outlines from OutlineProviders
22972         */
22973        final Outline mTmpOutline = new Outline();
22974
22975        /**
22976         * Temporary list for use in collecting focusable descendents of a view.
22977         */
22978        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
22979
22980        /**
22981         * The id of the window for accessibility purposes.
22982         */
22983        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
22984
22985        /**
22986         * Flags related to accessibility processing.
22987         *
22988         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
22989         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
22990         */
22991        int mAccessibilityFetchFlags;
22992
22993        /**
22994         * The drawable for highlighting accessibility focus.
22995         */
22996        Drawable mAccessibilityFocusDrawable;
22997
22998        /**
22999         * Show where the margins, bounds and layout bounds are for each view.
23000         */
23001        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
23002
23003        /**
23004         * Point used to compute visible regions.
23005         */
23006        final Point mPoint = new Point();
23007
23008        /**
23009         * Used to track which View originated a requestLayout() call, used when
23010         * requestLayout() is called during layout.
23011         */
23012        View mViewRequestingLayout;
23013
23014        /**
23015         * Used to track views that need (at least) a partial relayout at their current size
23016         * during the next traversal.
23017         */
23018        List<View> mPartialLayoutViews = new ArrayList<>();
23019
23020        /**
23021         * Swapped with mPartialLayoutViews during layout to avoid concurrent
23022         * modification. Lazily assigned during ViewRootImpl layout.
23023         */
23024        List<View> mEmptyPartialLayoutViews;
23025
23026        /**
23027         * Used to track the identity of the current drag operation.
23028         */
23029        IBinder mDragToken;
23030
23031        /**
23032         * The drag shadow surface for the current drag operation.
23033         */
23034        public Surface mDragSurface;
23035
23036        /**
23037         * Creates a new set of attachment information with the specified
23038         * events handler and thread.
23039         *
23040         * @param handler the events handler the view must use
23041         */
23042        AttachInfo(IWindowSession session, IWindow window, Display display,
23043                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
23044            mSession = session;
23045            mWindow = window;
23046            mWindowToken = window.asBinder();
23047            mDisplay = display;
23048            mViewRootImpl = viewRootImpl;
23049            mHandler = handler;
23050            mRootCallbacks = effectPlayer;
23051        }
23052    }
23053
23054    /**
23055     * <p>ScrollabilityCache holds various fields used by a View when scrolling
23056     * is supported. This avoids keeping too many unused fields in most
23057     * instances of View.</p>
23058     */
23059    private static class ScrollabilityCache implements Runnable {
23060
23061        /**
23062         * Scrollbars are not visible
23063         */
23064        public static final int OFF = 0;
23065
23066        /**
23067         * Scrollbars are visible
23068         */
23069        public static final int ON = 1;
23070
23071        /**
23072         * Scrollbars are fading away
23073         */
23074        public static final int FADING = 2;
23075
23076        public boolean fadeScrollBars;
23077
23078        public int fadingEdgeLength;
23079        public int scrollBarDefaultDelayBeforeFade;
23080        public int scrollBarFadeDuration;
23081
23082        public int scrollBarSize;
23083        public ScrollBarDrawable scrollBar;
23084        public float[] interpolatorValues;
23085        public View host;
23086
23087        public final Paint paint;
23088        public final Matrix matrix;
23089        public Shader shader;
23090
23091        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
23092
23093        private static final float[] OPAQUE = { 255 };
23094        private static final float[] TRANSPARENT = { 0.0f };
23095
23096        /**
23097         * When fading should start. This time moves into the future every time
23098         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
23099         */
23100        public long fadeStartTime;
23101
23102
23103        /**
23104         * The current state of the scrollbars: ON, OFF, or FADING
23105         */
23106        public int state = OFF;
23107
23108        private int mLastColor;
23109
23110        public final Rect mScrollBarBounds = new Rect();
23111
23112        public static final int NOT_DRAGGING = 0;
23113        public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1;
23114        public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2;
23115        public int mScrollBarDraggingState = NOT_DRAGGING;
23116
23117        public float mScrollBarDraggingPos = 0;
23118
23119        public ScrollabilityCache(ViewConfiguration configuration, View host) {
23120            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
23121            scrollBarSize = configuration.getScaledScrollBarSize();
23122            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
23123            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
23124
23125            paint = new Paint();
23126            matrix = new Matrix();
23127            // use use a height of 1, and then wack the matrix each time we
23128            // actually use it.
23129            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23130            paint.setShader(shader);
23131            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23132
23133            this.host = host;
23134        }
23135
23136        public void setFadeColor(int color) {
23137            if (color != mLastColor) {
23138                mLastColor = color;
23139
23140                if (color != 0) {
23141                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
23142                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
23143                    paint.setShader(shader);
23144                    // Restore the default transfer mode (src_over)
23145                    paint.setXfermode(null);
23146                } else {
23147                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
23148                    paint.setShader(shader);
23149                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
23150                }
23151            }
23152        }
23153
23154        public void run() {
23155            long now = AnimationUtils.currentAnimationTimeMillis();
23156            if (now >= fadeStartTime) {
23157
23158                // the animation fades the scrollbars out by changing
23159                // the opacity (alpha) from fully opaque to fully
23160                // transparent
23161                int nextFrame = (int) now;
23162                int framesCount = 0;
23163
23164                Interpolator interpolator = scrollBarInterpolator;
23165
23166                // Start opaque
23167                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
23168
23169                // End transparent
23170                nextFrame += scrollBarFadeDuration;
23171                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
23172
23173                state = FADING;
23174
23175                // Kick off the fade animation
23176                host.invalidate(true);
23177            }
23178        }
23179    }
23180
23181    /**
23182     * Resuable callback for sending
23183     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
23184     */
23185    private class SendViewScrolledAccessibilityEvent implements Runnable {
23186        public volatile boolean mIsPending;
23187
23188        public void run() {
23189            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
23190            mIsPending = false;
23191        }
23192    }
23193
23194    /**
23195     * <p>
23196     * This class represents a delegate that can be registered in a {@link View}
23197     * to enhance accessibility support via composition rather via inheritance.
23198     * It is specifically targeted to widget developers that extend basic View
23199     * classes i.e. classes in package android.view, that would like their
23200     * applications to be backwards compatible.
23201     * </p>
23202     * <div class="special reference">
23203     * <h3>Developer Guides</h3>
23204     * <p>For more information about making applications accessible, read the
23205     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
23206     * developer guide.</p>
23207     * </div>
23208     * <p>
23209     * A scenario in which a developer would like to use an accessibility delegate
23210     * is overriding a method introduced in a later API version than the minimal API
23211     * version supported by the application. For example, the method
23212     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
23213     * in API version 4 when the accessibility APIs were first introduced. If a
23214     * developer would like his application to run on API version 4 devices (assuming
23215     * all other APIs used by the application are version 4 or lower) and take advantage
23216     * of this method, instead of overriding the method which would break the application's
23217     * backwards compatibility, he can override the corresponding method in this
23218     * delegate and register the delegate in the target View if the API version of
23219     * the system is high enough, i.e. the API version is the same as or higher than the API
23220     * version that introduced
23221     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
23222     * </p>
23223     * <p>
23224     * Here is an example implementation:
23225     * </p>
23226     * <code><pre><p>
23227     * if (Build.VERSION.SDK_INT >= 14) {
23228     *     // If the API version is equal of higher than the version in
23229     *     // which onInitializeAccessibilityNodeInfo was introduced we
23230     *     // register a delegate with a customized implementation.
23231     *     View view = findViewById(R.id.view_id);
23232     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
23233     *         public void onInitializeAccessibilityNodeInfo(View host,
23234     *                 AccessibilityNodeInfo info) {
23235     *             // Let the default implementation populate the info.
23236     *             super.onInitializeAccessibilityNodeInfo(host, info);
23237     *             // Set some other information.
23238     *             info.setEnabled(host.isEnabled());
23239     *         }
23240     *     });
23241     * }
23242     * </code></pre></p>
23243     * <p>
23244     * This delegate contains methods that correspond to the accessibility methods
23245     * in View. If a delegate has been specified the implementation in View hands
23246     * off handling to the corresponding method in this delegate. The default
23247     * implementation the delegate methods behaves exactly as the corresponding
23248     * method in View for the case of no accessibility delegate been set. Hence,
23249     * to customize the behavior of a View method, clients can override only the
23250     * corresponding delegate method without altering the behavior of the rest
23251     * accessibility related methods of the host view.
23252     * </p>
23253     * <p>
23254     * <strong>Note:</strong> On platform versions prior to
23255     * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on
23256     * views in the {@code android.widget.*} package are called <i>before</i>
23257     * host methods. This prevents certain properties such as class name from
23258     * being modified by overriding
23259     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)},
23260     * as any changes will be overwritten by the host class.
23261     * <p>
23262     * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate
23263     * methods are called <i>after</i> host methods, which all properties to be
23264     * modified without being overwritten by the host class.
23265     */
23266    public static class AccessibilityDelegate {
23267
23268        /**
23269         * Sends an accessibility event of the given type. If accessibility is not
23270         * enabled this method has no effect.
23271         * <p>
23272         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
23273         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
23274         * been set.
23275         * </p>
23276         *
23277         * @param host The View hosting the delegate.
23278         * @param eventType The type of the event to send.
23279         *
23280         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
23281         */
23282        public void sendAccessibilityEvent(View host, int eventType) {
23283            host.sendAccessibilityEventInternal(eventType);
23284        }
23285
23286        /**
23287         * Performs the specified accessibility action on the view. For
23288         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
23289         * <p>
23290         * The default implementation behaves as
23291         * {@link View#performAccessibilityAction(int, Bundle)
23292         *  View#performAccessibilityAction(int, Bundle)} for the case of
23293         *  no accessibility delegate been set.
23294         * </p>
23295         *
23296         * @param action The action to perform.
23297         * @return Whether the action was performed.
23298         *
23299         * @see View#performAccessibilityAction(int, Bundle)
23300         *      View#performAccessibilityAction(int, Bundle)
23301         */
23302        public boolean performAccessibilityAction(View host, int action, Bundle args) {
23303            return host.performAccessibilityActionInternal(action, args);
23304        }
23305
23306        /**
23307         * Sends an accessibility event. This method behaves exactly as
23308         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
23309         * empty {@link AccessibilityEvent} and does not perform a check whether
23310         * accessibility is enabled.
23311         * <p>
23312         * The default implementation behaves as
23313         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23314         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
23315         * the case of no accessibility delegate been set.
23316         * </p>
23317         *
23318         * @param host The View hosting the delegate.
23319         * @param event The event to send.
23320         *
23321         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23322         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
23323         */
23324        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
23325            host.sendAccessibilityEventUncheckedInternal(event);
23326        }
23327
23328        /**
23329         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
23330         * to its children for adding their text content to the event.
23331         * <p>
23332         * The default implementation behaves as
23333         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23334         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
23335         * the case of no accessibility delegate been set.
23336         * </p>
23337         *
23338         * @param host The View hosting the delegate.
23339         * @param event The event.
23340         * @return True if the event population was completed.
23341         *
23342         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23343         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
23344         */
23345        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23346            return host.dispatchPopulateAccessibilityEventInternal(event);
23347        }
23348
23349        /**
23350         * Gives a chance to the host View to populate the accessibility event with its
23351         * text content.
23352         * <p>
23353         * The default implementation behaves as
23354         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
23355         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
23356         * the case of no accessibility delegate been set.
23357         * </p>
23358         *
23359         * @param host The View hosting the delegate.
23360         * @param event The accessibility event which to populate.
23361         *
23362         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
23363         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
23364         */
23365        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
23366            host.onPopulateAccessibilityEventInternal(event);
23367        }
23368
23369        /**
23370         * Initializes an {@link AccessibilityEvent} with information about the
23371         * the host View which is the event source.
23372         * <p>
23373         * The default implementation behaves as
23374         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
23375         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
23376         * the case of no accessibility delegate been set.
23377         * </p>
23378         *
23379         * @param host The View hosting the delegate.
23380         * @param event The event to initialize.
23381         *
23382         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
23383         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
23384         */
23385        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
23386            host.onInitializeAccessibilityEventInternal(event);
23387        }
23388
23389        /**
23390         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
23391         * <p>
23392         * The default implementation behaves as
23393         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23394         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
23395         * the case of no accessibility delegate been set.
23396         * </p>
23397         *
23398         * @param host The View hosting the delegate.
23399         * @param info The instance to initialize.
23400         *
23401         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23402         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
23403         */
23404        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
23405            host.onInitializeAccessibilityNodeInfoInternal(info);
23406        }
23407
23408        /**
23409         * Called when a child of the host View has requested sending an
23410         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
23411         * to augment the event.
23412         * <p>
23413         * The default implementation behaves as
23414         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23415         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
23416         * the case of no accessibility delegate been set.
23417         * </p>
23418         *
23419         * @param host The View hosting the delegate.
23420         * @param child The child which requests sending the event.
23421         * @param event The event to be sent.
23422         * @return True if the event should be sent
23423         *
23424         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23425         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
23426         */
23427        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
23428                AccessibilityEvent event) {
23429            return host.onRequestSendAccessibilityEventInternal(child, event);
23430        }
23431
23432        /**
23433         * Gets the provider for managing a virtual view hierarchy rooted at this View
23434         * and reported to {@link android.accessibilityservice.AccessibilityService}s
23435         * that explore the window content.
23436         * <p>
23437         * The default implementation behaves as
23438         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
23439         * the case of no accessibility delegate been set.
23440         * </p>
23441         *
23442         * @return The provider.
23443         *
23444         * @see AccessibilityNodeProvider
23445         */
23446        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
23447            return null;
23448        }
23449
23450        /**
23451         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
23452         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
23453         * This method is responsible for obtaining an accessibility node info from a
23454         * pool of reusable instances and calling
23455         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
23456         * view to initialize the former.
23457         * <p>
23458         * <strong>Note:</strong> The client is responsible for recycling the obtained
23459         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
23460         * creation.
23461         * </p>
23462         * <p>
23463         * The default implementation behaves as
23464         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
23465         * the case of no accessibility delegate been set.
23466         * </p>
23467         * @return A populated {@link AccessibilityNodeInfo}.
23468         *
23469         * @see AccessibilityNodeInfo
23470         *
23471         * @hide
23472         */
23473        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
23474            return host.createAccessibilityNodeInfoInternal();
23475        }
23476    }
23477
23478    private class MatchIdPredicate implements Predicate<View> {
23479        public int mId;
23480
23481        @Override
23482        public boolean apply(View view) {
23483            return (view.mID == mId);
23484        }
23485    }
23486
23487    private class MatchLabelForPredicate implements Predicate<View> {
23488        private int mLabeledId;
23489
23490        @Override
23491        public boolean apply(View view) {
23492            return (view.mLabelForId == mLabeledId);
23493        }
23494    }
23495
23496    private class SendViewStateChangedAccessibilityEvent implements Runnable {
23497        private int mChangeTypes = 0;
23498        private boolean mPosted;
23499        private boolean mPostedWithDelay;
23500        private long mLastEventTimeMillis;
23501
23502        @Override
23503        public void run() {
23504            mPosted = false;
23505            mPostedWithDelay = false;
23506            mLastEventTimeMillis = SystemClock.uptimeMillis();
23507            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
23508                final AccessibilityEvent event = AccessibilityEvent.obtain();
23509                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
23510                event.setContentChangeTypes(mChangeTypes);
23511                sendAccessibilityEventUnchecked(event);
23512            }
23513            mChangeTypes = 0;
23514        }
23515
23516        public void runOrPost(int changeType) {
23517            mChangeTypes |= changeType;
23518
23519            // If this is a live region or the child of a live region, collect
23520            // all events from this frame and send them on the next frame.
23521            if (inLiveRegion()) {
23522                // If we're already posted with a delay, remove that.
23523                if (mPostedWithDelay) {
23524                    removeCallbacks(this);
23525                    mPostedWithDelay = false;
23526                }
23527                // Only post if we're not already posted.
23528                if (!mPosted) {
23529                    post(this);
23530                    mPosted = true;
23531                }
23532                return;
23533            }
23534
23535            if (mPosted) {
23536                return;
23537            }
23538
23539            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
23540            final long minEventIntevalMillis =
23541                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
23542            if (timeSinceLastMillis >= minEventIntevalMillis) {
23543                removeCallbacks(this);
23544                run();
23545            } else {
23546                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
23547                mPostedWithDelay = true;
23548            }
23549        }
23550    }
23551
23552    private boolean inLiveRegion() {
23553        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23554            return true;
23555        }
23556
23557        ViewParent parent = getParent();
23558        while (parent instanceof View) {
23559            if (((View) parent).getAccessibilityLiveRegion()
23560                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
23561                return true;
23562            }
23563            parent = parent.getParent();
23564        }
23565
23566        return false;
23567    }
23568
23569    /**
23570     * Dump all private flags in readable format, useful for documentation and
23571     * sanity checking.
23572     */
23573    private static void dumpFlags() {
23574        final HashMap<String, String> found = Maps.newHashMap();
23575        try {
23576            for (Field field : View.class.getDeclaredFields()) {
23577                final int modifiers = field.getModifiers();
23578                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
23579                    if (field.getType().equals(int.class)) {
23580                        final int value = field.getInt(null);
23581                        dumpFlag(found, field.getName(), value);
23582                    } else if (field.getType().equals(int[].class)) {
23583                        final int[] values = (int[]) field.get(null);
23584                        for (int i = 0; i < values.length; i++) {
23585                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
23586                        }
23587                    }
23588                }
23589            }
23590        } catch (IllegalAccessException e) {
23591            throw new RuntimeException(e);
23592        }
23593
23594        final ArrayList<String> keys = Lists.newArrayList();
23595        keys.addAll(found.keySet());
23596        Collections.sort(keys);
23597        for (String key : keys) {
23598            Log.d(VIEW_LOG_TAG, found.get(key));
23599        }
23600    }
23601
23602    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
23603        // Sort flags by prefix, then by bits, always keeping unique keys
23604        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
23605        final int prefix = name.indexOf('_');
23606        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
23607        final String output = bits + " " + name;
23608        found.put(key, output);
23609    }
23610
23611    /** {@hide} */
23612    public void encode(@NonNull ViewHierarchyEncoder stream) {
23613        stream.beginObject(this);
23614        encodeProperties(stream);
23615        stream.endObject();
23616    }
23617
23618    /** {@hide} */
23619    @CallSuper
23620    protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) {
23621        Object resolveId = ViewDebug.resolveId(getContext(), mID);
23622        if (resolveId instanceof String) {
23623            stream.addProperty("id", (String) resolveId);
23624        } else {
23625            stream.addProperty("id", mID);
23626        }
23627
23628        stream.addProperty("misc:transformation.alpha",
23629                mTransformationInfo != null ? mTransformationInfo.mAlpha : 0);
23630        stream.addProperty("misc:transitionName", getTransitionName());
23631
23632        // layout
23633        stream.addProperty("layout:left", mLeft);
23634        stream.addProperty("layout:right", mRight);
23635        stream.addProperty("layout:top", mTop);
23636        stream.addProperty("layout:bottom", mBottom);
23637        stream.addProperty("layout:width", getWidth());
23638        stream.addProperty("layout:height", getHeight());
23639        stream.addProperty("layout:layoutDirection", getLayoutDirection());
23640        stream.addProperty("layout:layoutRtl", isLayoutRtl());
23641        stream.addProperty("layout:hasTransientState", hasTransientState());
23642        stream.addProperty("layout:baseline", getBaseline());
23643
23644        // layout params
23645        ViewGroup.LayoutParams layoutParams = getLayoutParams();
23646        if (layoutParams != null) {
23647            stream.addPropertyKey("layoutParams");
23648            layoutParams.encode(stream);
23649        }
23650
23651        // scrolling
23652        stream.addProperty("scrolling:scrollX", mScrollX);
23653        stream.addProperty("scrolling:scrollY", mScrollY);
23654
23655        // padding
23656        stream.addProperty("padding:paddingLeft", mPaddingLeft);
23657        stream.addProperty("padding:paddingRight", mPaddingRight);
23658        stream.addProperty("padding:paddingTop", mPaddingTop);
23659        stream.addProperty("padding:paddingBottom", mPaddingBottom);
23660        stream.addProperty("padding:userPaddingRight", mUserPaddingRight);
23661        stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft);
23662        stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom);
23663        stream.addProperty("padding:userPaddingStart", mUserPaddingStart);
23664        stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd);
23665
23666        // measurement
23667        stream.addProperty("measurement:minHeight", mMinHeight);
23668        stream.addProperty("measurement:minWidth", mMinWidth);
23669        stream.addProperty("measurement:measuredWidth", mMeasuredWidth);
23670        stream.addProperty("measurement:measuredHeight", mMeasuredHeight);
23671
23672        // drawing
23673        stream.addProperty("drawing:elevation", getElevation());
23674        stream.addProperty("drawing:translationX", getTranslationX());
23675        stream.addProperty("drawing:translationY", getTranslationY());
23676        stream.addProperty("drawing:translationZ", getTranslationZ());
23677        stream.addProperty("drawing:rotation", getRotation());
23678        stream.addProperty("drawing:rotationX", getRotationX());
23679        stream.addProperty("drawing:rotationY", getRotationY());
23680        stream.addProperty("drawing:scaleX", getScaleX());
23681        stream.addProperty("drawing:scaleY", getScaleY());
23682        stream.addProperty("drawing:pivotX", getPivotX());
23683        stream.addProperty("drawing:pivotY", getPivotY());
23684        stream.addProperty("drawing:opaque", isOpaque());
23685        stream.addProperty("drawing:alpha", getAlpha());
23686        stream.addProperty("drawing:transitionAlpha", getTransitionAlpha());
23687        stream.addProperty("drawing:shadow", hasShadow());
23688        stream.addProperty("drawing:solidColor", getSolidColor());
23689        stream.addProperty("drawing:layerType", mLayerType);
23690        stream.addProperty("drawing:willNotDraw", willNotDraw());
23691        stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated());
23692        stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
23693        stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
23694        stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
23695
23696        // focus
23697        stream.addProperty("focus:hasFocus", hasFocus());
23698        stream.addProperty("focus:isFocused", isFocused());
23699        stream.addProperty("focus:isFocusable", isFocusable());
23700        stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode());
23701
23702        stream.addProperty("misc:clickable", isClickable());
23703        stream.addProperty("misc:pressed", isPressed());
23704        stream.addProperty("misc:selected", isSelected());
23705        stream.addProperty("misc:touchMode", isInTouchMode());
23706        stream.addProperty("misc:hovered", isHovered());
23707        stream.addProperty("misc:activated", isActivated());
23708
23709        stream.addProperty("misc:visibility", getVisibility());
23710        stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows());
23711        stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured());
23712
23713        stream.addProperty("misc:enabled", isEnabled());
23714        stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled());
23715        stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled());
23716
23717        // theme attributes
23718        Resources.Theme theme = getContext().getTheme();
23719        if (theme != null) {
23720            stream.addPropertyKey("theme");
23721            theme.encode(stream);
23722        }
23723
23724        // view attribute information
23725        int n = mAttributes != null ? mAttributes.length : 0;
23726        stream.addProperty("meta:__attrCount__", n/2);
23727        for (int i = 0; i < n; i += 2) {
23728            stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]);
23729        }
23730
23731        stream.addProperty("misc:scrollBarStyle", getScrollBarStyle());
23732
23733        // text
23734        stream.addProperty("text:textDirection", getTextDirection());
23735        stream.addProperty("text:textAlignment", getTextAlignment());
23736
23737        // accessibility
23738        CharSequence contentDescription = getContentDescription();
23739        stream.addProperty("accessibility:contentDescription",
23740                contentDescription == null ? "" : contentDescription.toString());
23741        stream.addProperty("accessibility:labelFor", getLabelFor());
23742        stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility());
23743    }
23744}
23745