View.java revision d274400205d054010e60ddd69f1535bedf41d96b
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.AnimatorInflater;
20import android.animation.StateListAnimator;
21import android.annotation.CallSuper;
22import android.annotation.ColorInt;
23import android.annotation.DrawableRes;
24import android.annotation.FloatRange;
25import android.annotation.IdRes;
26import android.annotation.IntDef;
27import android.annotation.LayoutRes;
28import android.annotation.NonNull;
29import android.annotation.Nullable;
30import android.annotation.Size;
31import android.annotation.UiThread;
32import android.content.ClipData;
33import android.content.Context;
34import android.content.ContextWrapper;
35import android.content.Intent;
36import android.content.res.ColorStateList;
37import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.content.res.TypedArray;
40import android.graphics.Bitmap;
41import android.graphics.Canvas;
42import android.graphics.Insets;
43import android.graphics.Interpolator;
44import android.graphics.LinearGradient;
45import android.graphics.Matrix;
46import android.graphics.Outline;
47import android.graphics.Paint;
48import android.graphics.PixelFormat;
49import android.graphics.Point;
50import android.graphics.PorterDuff;
51import android.graphics.PorterDuffXfermode;
52import android.graphics.Rect;
53import android.graphics.RectF;
54import android.graphics.Region;
55import android.graphics.Shader;
56import android.graphics.drawable.ColorDrawable;
57import android.graphics.drawable.Drawable;
58import android.hardware.display.DisplayManagerGlobal;
59import android.os.Bundle;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Parcel;
63import android.os.Parcelable;
64import android.os.RemoteException;
65import android.os.SystemClock;
66import android.os.SystemProperties;
67import android.os.Trace;
68import android.text.TextUtils;
69import android.util.AttributeSet;
70import android.util.FloatProperty;
71import android.util.LayoutDirection;
72import android.util.Log;
73import android.util.LongSparseLongArray;
74import android.util.Pools.SynchronizedPool;
75import android.util.Property;
76import android.util.SparseArray;
77import android.util.StateSet;
78import android.util.SuperNotCalledException;
79import android.util.TypedValue;
80import android.view.ContextMenu.ContextMenuInfo;
81import android.view.AccessibilityIterators.TextSegmentIterator;
82import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
83import android.view.AccessibilityIterators.WordTextSegmentIterator;
84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
85import android.view.accessibility.AccessibilityEvent;
86import android.view.accessibility.AccessibilityEventSource;
87import android.view.accessibility.AccessibilityManager;
88import android.view.accessibility.AccessibilityNodeInfo;
89import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
90import android.view.accessibility.AccessibilityNodeProvider;
91import android.view.animation.Animation;
92import android.view.animation.AnimationUtils;
93import android.view.animation.Transformation;
94import android.view.inputmethod.EditorInfo;
95import android.view.inputmethod.InputConnection;
96import android.view.inputmethod.InputMethodManager;
97import android.widget.Checkable;
98import android.widget.ScrollBarDrawable;
99
100import static android.os.Build.VERSION_CODES.*;
101import static java.lang.Math.max;
102
103import com.android.internal.R;
104import com.android.internal.util.Predicate;
105import com.android.internal.view.menu.MenuBuilder;
106import com.google.android.collect.Lists;
107import com.google.android.collect.Maps;
108
109import java.lang.annotation.Retention;
110import java.lang.annotation.RetentionPolicy;
111import java.lang.ref.WeakReference;
112import java.lang.reflect.Field;
113import java.lang.reflect.InvocationTargetException;
114import java.lang.reflect.Method;
115import java.lang.reflect.Modifier;
116import java.util.ArrayList;
117import java.util.Arrays;
118import java.util.Collections;
119import java.util.HashMap;
120import java.util.List;
121import java.util.Locale;
122import java.util.Map;
123import java.util.concurrent.CopyOnWriteArrayList;
124import java.util.concurrent.atomic.AtomicInteger;
125
126/**
127 * <p>
128 * This class represents the basic building block for user interface components. A View
129 * occupies a rectangular area on the screen and is responsible for drawing and
130 * event handling. View is the base class for <em>widgets</em>, which are
131 * used to create interactive UI components (buttons, text fields, etc.). The
132 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
133 * are invisible containers that hold other Views (or other ViewGroups) and define
134 * their layout properties.
135 * </p>
136 *
137 * <div class="special reference">
138 * <h3>Developer Guides</h3>
139 * <p>For information about using this class to develop your application's user interface,
140 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
141 * </div>
142 *
143 * <a name="Using"></a>
144 * <h3>Using Views</h3>
145 * <p>
146 * All of the views in a window are arranged in a single tree. You can add views
147 * either from code or by specifying a tree of views in one or more XML layout
148 * files. There are many specialized subclasses of views that act as controls or
149 * are capable of displaying text, images, or other content.
150 * </p>
151 * <p>
152 * Once you have created a tree of views, there are typically a few types of
153 * common operations you may wish to perform:
154 * <ul>
155 * <li><strong>Set properties:</strong> for example setting the text of a
156 * {@link android.widget.TextView}. The available properties and the methods
157 * that set them will vary among the different subclasses of views. Note that
158 * properties that are known at build time can be set in the XML layout
159 * files.</li>
160 * <li><strong>Set focus:</strong> The framework will handled moving focus in
161 * response to user input. To force focus to a specific view, call
162 * {@link #requestFocus}.</li>
163 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
164 * that will be notified when something interesting happens to the view. For
165 * example, all views will let you set a listener to be notified when the view
166 * gains or loses focus. You can register such a listener using
167 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
168 * Other view subclasses offer more specialized listeners. For example, a Button
169 * exposes a listener to notify clients when the button is clicked.</li>
170 * <li><strong>Set visibility:</strong> You can hide or show views using
171 * {@link #setVisibility(int)}.</li>
172 * </ul>
173 * </p>
174 * <p><em>
175 * Note: The Android framework is responsible for measuring, laying out and
176 * drawing views. You should not call methods that perform these actions on
177 * views yourself unless you are actually implementing a
178 * {@link android.view.ViewGroup}.
179 * </em></p>
180 *
181 * <a name="Lifecycle"></a>
182 * <h3>Implementing a Custom View</h3>
183 *
184 * <p>
185 * To implement a custom view, you will usually begin by providing overrides for
186 * some of the standard methods that the framework calls on all views. You do
187 * not need to override all of these methods. In fact, you can start by just
188 * overriding {@link #onDraw(android.graphics.Canvas)}.
189 * <table border="2" width="85%" align="center" cellpadding="5">
190 *     <thead>
191 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
192 *     </thead>
193 *
194 *     <tbody>
195 *     <tr>
196 *         <td rowspan="2">Creation</td>
197 *         <td>Constructors</td>
198 *         <td>There is a form of the constructor that are called when the view
199 *         is created from code and a form that is called when the view is
200 *         inflated from a layout file. The second form should parse and apply
201 *         any attributes defined in the layout file.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onFinishInflate()}</code></td>
206 *         <td>Called after a view and all of its children has been inflated
207 *         from XML.</td>
208 *     </tr>
209 *
210 *     <tr>
211 *         <td rowspan="3">Layout</td>
212 *         <td><code>{@link #onMeasure(int, int)}</code></td>
213 *         <td>Called to determine the size requirements for this view and all
214 *         of its children.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
219 *         <td>Called when this view should assign a size and position to all
220 *         of its children.
221 *         </td>
222 *     </tr>
223 *     <tr>
224 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
225 *         <td>Called when the size of this view has changed.
226 *         </td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td>Drawing</td>
231 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
232 *         <td>Called when the view should render its content.
233 *         </td>
234 *     </tr>
235 *
236 *     <tr>
237 *         <td rowspan="4">Event processing</td>
238 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
239 *         <td>Called when a new hardware key event occurs.
240 *         </td>
241 *     </tr>
242 *     <tr>
243 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
244 *         <td>Called when a hardware key up event occurs.
245 *         </td>
246 *     </tr>
247 *     <tr>
248 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
249 *         <td>Called when a trackball motion event occurs.
250 *         </td>
251 *     </tr>
252 *     <tr>
253 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
254 *         <td>Called when a touch screen motion event occurs.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td rowspan="2">Focus</td>
260 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
261 *         <td>Called when the view gains or loses focus.
262 *         </td>
263 *     </tr>
264 *
265 *     <tr>
266 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
267 *         <td>Called when the window containing the view gains or loses focus.
268 *         </td>
269 *     </tr>
270 *
271 *     <tr>
272 *         <td rowspan="3">Attaching</td>
273 *         <td><code>{@link #onAttachedToWindow()}</code></td>
274 *         <td>Called when the view is attached to a window.
275 *         </td>
276 *     </tr>
277 *
278 *     <tr>
279 *         <td><code>{@link #onDetachedFromWindow}</code></td>
280 *         <td>Called when the view is detached from its window.
281 *         </td>
282 *     </tr>
283 *
284 *     <tr>
285 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
286 *         <td>Called when the visibility of the window containing the view
287 *         has changed.
288 *         </td>
289 *     </tr>
290 *     </tbody>
291 *
292 * </table>
293 * </p>
294 *
295 * <a name="IDs"></a>
296 * <h3>IDs</h3>
297 * Views may have an integer id associated with them. These ids are typically
298 * assigned in the layout XML files, and are used to find specific views within
299 * the view tree. A common pattern is to:
300 * <ul>
301 * <li>Define a Button in the layout file and assign it a unique ID.
302 * <pre>
303 * &lt;Button
304 *     android:id="@+id/my_button"
305 *     android:layout_width="wrap_content"
306 *     android:layout_height="wrap_content"
307 *     android:text="@string/my_button_text"/&gt;
308 * </pre></li>
309 * <li>From the onCreate method of an Activity, find the Button
310 * <pre class="prettyprint">
311 *      Button myButton = (Button) findViewById(R.id.my_button);
312 * </pre></li>
313 * </ul>
314 * <p>
315 * View IDs need not be unique throughout the tree, but it is good practice to
316 * ensure that they are at least unique within the part of the tree you are
317 * searching.
318 * </p>
319 *
320 * <a name="Position"></a>
321 * <h3>Position</h3>
322 * <p>
323 * The geometry of a view is that of a rectangle. A view has a location,
324 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
325 * two dimensions, expressed as a width and a height. The unit for location
326 * and dimensions is the pixel.
327 * </p>
328 *
329 * <p>
330 * It is possible to retrieve the location of a view by invoking the methods
331 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
332 * coordinate of the rectangle representing the view. The latter returns the
333 * top, or Y, coordinate of the rectangle representing the view. These methods
334 * both return the location of the view relative to its parent. For instance,
335 * when getLeft() returns 20, that means the view is located 20 pixels to the
336 * right of the left edge of its direct parent.
337 * </p>
338 *
339 * <p>
340 * In addition, several convenience methods are offered to avoid unnecessary
341 * computations, namely {@link #getRight()} and {@link #getBottom()}.
342 * These methods return the coordinates of the right and bottom edges of the
343 * rectangle representing the view. For instance, calling {@link #getRight()}
344 * is similar to the following computation: <code>getLeft() + getWidth()</code>
345 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
346 * </p>
347 *
348 * <a name="SizePaddingMargins"></a>
349 * <h3>Size, padding and margins</h3>
350 * <p>
351 * The size of a view is expressed with a width and a height. A view actually
352 * possess two pairs of width and height values.
353 * </p>
354 *
355 * <p>
356 * The first pair is known as <em>measured width</em> and
357 * <em>measured height</em>. These dimensions define how big a view wants to be
358 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
359 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
360 * and {@link #getMeasuredHeight()}.
361 * </p>
362 *
363 * <p>
364 * The second pair is simply known as <em>width</em> and <em>height</em>, or
365 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
366 * dimensions define the actual size of the view on screen, at drawing time and
367 * after layout. These values may, but do not have to, be different from the
368 * measured width and height. The width and height can be obtained by calling
369 * {@link #getWidth()} and {@link #getHeight()}.
370 * </p>
371 *
372 * <p>
373 * To measure its dimensions, a view takes into account its padding. The padding
374 * is expressed in pixels for the left, top, right and bottom parts of the view.
375 * Padding can be used to offset the content of the view by a specific amount of
376 * pixels. For instance, a left padding of 2 will push the view's content by
377 * 2 pixels to the right of the left edge. Padding can be set using the
378 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
379 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
380 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
381 * {@link #getPaddingEnd()}.
382 * </p>
383 *
384 * <p>
385 * Even though a view can define a padding, it does not provide any support for
386 * margins. However, view groups provide such a support. Refer to
387 * {@link android.view.ViewGroup} and
388 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
389 * </p>
390 *
391 * <a name="Layout"></a>
392 * <h3>Layout</h3>
393 * <p>
394 * Layout is a two pass process: a measure pass and a layout pass. The measuring
395 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
396 * of the view tree. Each view pushes dimension specifications down the tree
397 * during the recursion. At the end of the measure pass, every view has stored
398 * its measurements. The second pass happens in
399 * {@link #layout(int,int,int,int)} and is also top-down. During
400 * this pass each parent is responsible for positioning all of its children
401 * using the sizes computed in the measure pass.
402 * </p>
403 *
404 * <p>
405 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
406 * {@link #getMeasuredHeight()} values must be set, along with those for all of
407 * that view's descendants. A view's measured width and measured height values
408 * must respect the constraints imposed by the view's parents. This guarantees
409 * that at the end of the measure pass, all parents accept all of their
410 * children's measurements. A parent view may call measure() more than once on
411 * its children. For example, the parent may measure each child once with
412 * unspecified dimensions to find out how big they want to be, then call
413 * measure() on them again with actual numbers if the sum of all the children's
414 * unconstrained sizes is too big or too small.
415 * </p>
416 *
417 * <p>
418 * The measure pass uses two classes to communicate dimensions. The
419 * {@link MeasureSpec} class is used by views to tell their parents how they
420 * want to be measured and positioned. The base LayoutParams class just
421 * describes how big the view wants to be for both width and height. For each
422 * dimension, it can specify one of:
423 * <ul>
424 * <li> an exact number
425 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
426 * (minus padding)
427 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
428 * enclose its content (plus padding).
429 * </ul>
430 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
431 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
432 * an X and Y value.
433 * </p>
434 *
435 * <p>
436 * MeasureSpecs are used to push requirements down the tree from parent to
437 * child. A MeasureSpec can be in one of three modes:
438 * <ul>
439 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
440 * of a child view. For example, a LinearLayout may call measure() on its child
441 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
442 * tall the child view wants to be given a width of 240 pixels.
443 * <li>EXACTLY: This is used by the parent to impose an exact size on the
444 * child. The child must use this size, and guarantee that all of its
445 * descendants will fit within this size.
446 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
447 * child. The child must guarantee that it and all of its descendants will fit
448 * within this size.
449 * </ul>
450 * </p>
451 *
452 * <p>
453 * To initiate a layout, call {@link #requestLayout}. This method is typically
454 * called by a view on itself when it believes that is can no longer fit within
455 * its current bounds.
456 * </p>
457 *
458 * <a name="Drawing"></a>
459 * <h3>Drawing</h3>
460 * <p>
461 * Drawing is handled by walking the tree and recording the drawing commands of
462 * any View that needs to update. After this, the drawing commands of the
463 * entire tree are issued to screen, clipped to the newly damaged area.
464 * </p>
465 *
466 * <p>
467 * The tree is largely recorded and drawn in order, with parents drawn before
468 * (i.e., behind) their children, with siblings drawn in the order they appear
469 * in the tree. If you set a background drawable for a View, then the View will
470 * draw it before calling back to its <code>onDraw()</code> method. The child
471 * drawing order can be overridden with
472 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order}
473 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views.
474 * </p>
475 *
476 * <p>
477 * To force a view to draw, call {@link #invalidate()}.
478 * </p>
479 *
480 * <a name="EventHandlingThreading"></a>
481 * <h3>Event Handling and Threading</h3>
482 * <p>
483 * The basic cycle of a view is as follows:
484 * <ol>
485 * <li>An event comes in and is dispatched to the appropriate view. The view
486 * handles the event and notifies any listeners.</li>
487 * <li>If in the course of processing the event, the view's bounds may need
488 * to be changed, the view will call {@link #requestLayout()}.</li>
489 * <li>Similarly, if in the course of processing the event the view's appearance
490 * may need to be changed, the view will call {@link #invalidate()}.</li>
491 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
492 * the framework will take care of measuring, laying out, and drawing the tree
493 * as appropriate.</li>
494 * </ol>
495 * </p>
496 *
497 * <p><em>Note: The entire view tree is single threaded. You must always be on
498 * the UI thread when calling any method on any view.</em>
499 * If you are doing work on other threads and want to update the state of a view
500 * from that thread, you should use a {@link Handler}.
501 * </p>
502 *
503 * <a name="FocusHandling"></a>
504 * <h3>Focus Handling</h3>
505 * <p>
506 * The framework will handle routine focus movement in response to user input.
507 * This includes changing the focus as views are removed or hidden, or as new
508 * views become available. Views indicate their willingness to take focus
509 * through the {@link #isFocusable} method. To change whether a view can take
510 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
511 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
512 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
513 * </p>
514 * <p>
515 * Focus movement is based on an algorithm which finds the nearest neighbor in a
516 * given direction. In rare cases, the default algorithm may not match the
517 * intended behavior of the developer. In these situations, you can provide
518 * explicit overrides by using these XML attributes in the layout file:
519 * <pre>
520 * nextFocusDown
521 * nextFocusLeft
522 * nextFocusRight
523 * nextFocusUp
524 * </pre>
525 * </p>
526 *
527 *
528 * <p>
529 * To get a particular view to take focus, call {@link #requestFocus()}.
530 * </p>
531 *
532 * <a name="TouchMode"></a>
533 * <h3>Touch Mode</h3>
534 * <p>
535 * When a user is navigating a user interface via directional keys such as a D-pad, it is
536 * necessary to give focus to actionable items such as buttons so the user can see
537 * what will take input.  If the device has touch capabilities, however, and the user
538 * begins interacting with the interface by touching it, it is no longer necessary to
539 * always highlight, or give focus to, a particular view.  This motivates a mode
540 * for interaction named 'touch mode'.
541 * </p>
542 * <p>
543 * For a touch capable device, once the user touches the screen, the device
544 * will enter touch mode.  From this point onward, only views for which
545 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
546 * Other views that are touchable, like buttons, will not take focus when touched; they will
547 * only fire the on click listeners.
548 * </p>
549 * <p>
550 * Any time a user hits a directional key, such as a D-pad direction, the view device will
551 * exit touch mode, and find a view to take focus, so that the user may resume interacting
552 * with the user interface without touching the screen again.
553 * </p>
554 * <p>
555 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
556 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
557 * </p>
558 *
559 * <a name="Scrolling"></a>
560 * <h3>Scrolling</h3>
561 * <p>
562 * The framework provides basic support for views that wish to internally
563 * scroll their content. This includes keeping track of the X and Y scroll
564 * offset as well as mechanisms for drawing scrollbars. See
565 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
566 * {@link #awakenScrollBars()} for more details.
567 * </p>
568 *
569 * <a name="Tags"></a>
570 * <h3>Tags</h3>
571 * <p>
572 * Unlike IDs, tags are not used to identify views. Tags are essentially an
573 * extra piece of information that can be associated with a view. They are most
574 * often used as a convenience to store data related to views in the views
575 * themselves rather than by putting them in a separate structure.
576 * </p>
577 *
578 * <a name="Properties"></a>
579 * <h3>Properties</h3>
580 * <p>
581 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
582 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
583 * available both in the {@link Property} form as well as in similarly-named setter/getter
584 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
585 * be used to set persistent state associated with these rendering-related properties on the view.
586 * The properties and methods can also be used in conjunction with
587 * {@link android.animation.Animator Animator}-based animations, described more in the
588 * <a href="#Animation">Animation</a> section.
589 * </p>
590 *
591 * <a name="Animation"></a>
592 * <h3>Animation</h3>
593 * <p>
594 * Starting with Android 3.0, the preferred way of animating views is to use the
595 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
596 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
597 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
598 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
599 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
600 * makes animating these View properties particularly easy and efficient.
601 * </p>
602 * <p>
603 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
604 * You can attach an {@link Animation} object to a view using
605 * {@link #setAnimation(Animation)} or
606 * {@link #startAnimation(Animation)}. The animation can alter the scale,
607 * rotation, translation and alpha of a view over time. If the animation is
608 * attached to a view that has children, the animation will affect the entire
609 * subtree rooted by that node. When an animation is started, the framework will
610 * take care of redrawing the appropriate views until the animation completes.
611 * </p>
612 *
613 * <a name="Security"></a>
614 * <h3>Security</h3>
615 * <p>
616 * Sometimes it is essential that an application be able to verify that an action
617 * is being performed with the full knowledge and consent of the user, such as
618 * granting a permission request, making a purchase or clicking on an advertisement.
619 * Unfortunately, a malicious application could try to spoof the user into
620 * performing these actions, unaware, by concealing the intended purpose of the view.
621 * As a remedy, the framework offers a touch filtering mechanism that can be used to
622 * improve the security of views that provide access to sensitive functionality.
623 * </p><p>
624 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
625 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
626 * will discard touches that are received whenever the view's window is obscured by
627 * another visible window.  As a result, the view will not receive touches whenever a
628 * toast, dialog or other window appears above the view's window.
629 * </p><p>
630 * For more fine-grained control over security, consider overriding the
631 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
632 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
633 * </p>
634 *
635 * @attr ref android.R.styleable#View_alpha
636 * @attr ref android.R.styleable#View_assistBlocked
637 * @attr ref android.R.styleable#View_background
638 * @attr ref android.R.styleable#View_clickable
639 * @attr ref android.R.styleable#View_contentDescription
640 * @attr ref android.R.styleable#View_drawingCacheQuality
641 * @attr ref android.R.styleable#View_duplicateParentState
642 * @attr ref android.R.styleable#View_id
643 * @attr ref android.R.styleable#View_requiresFadingEdge
644 * @attr ref android.R.styleable#View_fadeScrollbars
645 * @attr ref android.R.styleable#View_fadingEdgeLength
646 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
647 * @attr ref android.R.styleable#View_fitsSystemWindows
648 * @attr ref android.R.styleable#View_isScrollContainer
649 * @attr ref android.R.styleable#View_focusable
650 * @attr ref android.R.styleable#View_focusableInTouchMode
651 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
652 * @attr ref android.R.styleable#View_keepScreenOn
653 * @attr ref android.R.styleable#View_layerType
654 * @attr ref android.R.styleable#View_layoutDirection
655 * @attr ref android.R.styleable#View_longClickable
656 * @attr ref android.R.styleable#View_minHeight
657 * @attr ref android.R.styleable#View_minWidth
658 * @attr ref android.R.styleable#View_nextFocusDown
659 * @attr ref android.R.styleable#View_nextFocusLeft
660 * @attr ref android.R.styleable#View_nextFocusRight
661 * @attr ref android.R.styleable#View_nextFocusUp
662 * @attr ref android.R.styleable#View_onClick
663 * @attr ref android.R.styleable#View_padding
664 * @attr ref android.R.styleable#View_paddingBottom
665 * @attr ref android.R.styleable#View_paddingLeft
666 * @attr ref android.R.styleable#View_paddingRight
667 * @attr ref android.R.styleable#View_paddingTop
668 * @attr ref android.R.styleable#View_paddingStart
669 * @attr ref android.R.styleable#View_paddingEnd
670 * @attr ref android.R.styleable#View_saveEnabled
671 * @attr ref android.R.styleable#View_rotation
672 * @attr ref android.R.styleable#View_rotationX
673 * @attr ref android.R.styleable#View_rotationY
674 * @attr ref android.R.styleable#View_scaleX
675 * @attr ref android.R.styleable#View_scaleY
676 * @attr ref android.R.styleable#View_scrollX
677 * @attr ref android.R.styleable#View_scrollY
678 * @attr ref android.R.styleable#View_scrollbarSize
679 * @attr ref android.R.styleable#View_scrollbarStyle
680 * @attr ref android.R.styleable#View_scrollbars
681 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
682 * @attr ref android.R.styleable#View_scrollbarFadeDuration
683 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
684 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
685 * @attr ref android.R.styleable#View_scrollbarThumbVertical
686 * @attr ref android.R.styleable#View_scrollbarTrackVertical
687 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
688 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
689 * @attr ref android.R.styleable#View_stateListAnimator
690 * @attr ref android.R.styleable#View_transitionName
691 * @attr ref android.R.styleable#View_soundEffectsEnabled
692 * @attr ref android.R.styleable#View_tag
693 * @attr ref android.R.styleable#View_textAlignment
694 * @attr ref android.R.styleable#View_textDirection
695 * @attr ref android.R.styleable#View_transformPivotX
696 * @attr ref android.R.styleable#View_transformPivotY
697 * @attr ref android.R.styleable#View_translationX
698 * @attr ref android.R.styleable#View_translationY
699 * @attr ref android.R.styleable#View_translationZ
700 * @attr ref android.R.styleable#View_visibility
701 *
702 * @see android.view.ViewGroup
703 */
704@UiThread
705public class View implements Drawable.Callback, KeyEvent.Callback,
706        AccessibilityEventSource {
707    private static final boolean DBG = false;
708
709    /**
710     * The logging tag used by this class with android.util.Log.
711     */
712    protected static final String VIEW_LOG_TAG = "View";
713
714    /**
715     * When set to true, apps will draw debugging information about their layouts.
716     *
717     * @hide
718     */
719    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
720
721    /**
722     * When set to true, this view will save its attribute data.
723     *
724     * @hide
725     */
726    public static boolean mDebugViewAttributes = false;
727
728    /**
729     * Used to mark a View that has no ID.
730     */
731    public static final int NO_ID = -1;
732
733    /**
734     * Signals that compatibility booleans have been initialized according to
735     * target SDK versions.
736     */
737    private static boolean sCompatibilityDone = false;
738
739    /**
740     * Use the old (broken) way of building MeasureSpecs.
741     */
742    private static boolean sUseBrokenMakeMeasureSpec = false;
743
744    /**
745     * Ignore any optimizations using the measure cache.
746     */
747    private static boolean sIgnoreMeasureCache = false;
748
749    /**
750     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
751     * calling setFlags.
752     */
753    private static final int NOT_FOCUSABLE = 0x00000000;
754
755    /**
756     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
757     * setFlags.
758     */
759    private static final int FOCUSABLE = 0x00000001;
760
761    /**
762     * Mask for use with setFlags indicating bits used for focus.
763     */
764    private static final int FOCUSABLE_MASK = 0x00000001;
765
766    /**
767     * This view will adjust its padding to fit sytem windows (e.g. status bar)
768     */
769    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
770
771    /** @hide */
772    @IntDef({VISIBLE, INVISIBLE, GONE})
773    @Retention(RetentionPolicy.SOURCE)
774    public @interface Visibility {}
775
776    /**
777     * This view is visible.
778     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
779     * android:visibility}.
780     */
781    public static final int VISIBLE = 0x00000000;
782
783    /**
784     * This view is invisible, but it still takes up space for layout purposes.
785     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
786     * android:visibility}.
787     */
788    public static final int INVISIBLE = 0x00000004;
789
790    /**
791     * This view is invisible, and it doesn't take any space for layout
792     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
793     * android:visibility}.
794     */
795    public static final int GONE = 0x00000008;
796
797    /**
798     * Mask for use with setFlags indicating bits used for visibility.
799     * {@hide}
800     */
801    static final int VISIBILITY_MASK = 0x0000000C;
802
803    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
804
805    /**
806     * This view is enabled. Interpretation varies by subclass.
807     * Use with ENABLED_MASK when calling setFlags.
808     * {@hide}
809     */
810    static final int ENABLED = 0x00000000;
811
812    /**
813     * This view is disabled. Interpretation varies by subclass.
814     * Use with ENABLED_MASK when calling setFlags.
815     * {@hide}
816     */
817    static final int DISABLED = 0x00000020;
818
819   /**
820    * Mask for use with setFlags indicating bits used for indicating whether
821    * this view is enabled
822    * {@hide}
823    */
824    static final int ENABLED_MASK = 0x00000020;
825
826    /**
827     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
828     * called and further optimizations will be performed. It is okay to have
829     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
830     * {@hide}
831     */
832    static final int WILL_NOT_DRAW = 0x00000080;
833
834    /**
835     * Mask for use with setFlags indicating bits used for indicating whether
836     * this view is will draw
837     * {@hide}
838     */
839    static final int DRAW_MASK = 0x00000080;
840
841    /**
842     * <p>This view doesn't show scrollbars.</p>
843     * {@hide}
844     */
845    static final int SCROLLBARS_NONE = 0x00000000;
846
847    /**
848     * <p>This view shows horizontal scrollbars.</p>
849     * {@hide}
850     */
851    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
852
853    /**
854     * <p>This view shows vertical scrollbars.</p>
855     * {@hide}
856     */
857    static final int SCROLLBARS_VERTICAL = 0x00000200;
858
859    /**
860     * <p>Mask for use with setFlags indicating bits used for indicating which
861     * scrollbars are enabled.</p>
862     * {@hide}
863     */
864    static final int SCROLLBARS_MASK = 0x00000300;
865
866    /**
867     * Indicates that the view should filter touches when its window is obscured.
868     * Refer to the class comments for more information about this security feature.
869     * {@hide}
870     */
871    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
872
873    /**
874     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
875     * that they are optional and should be skipped if the window has
876     * requested system UI flags that ignore those insets for layout.
877     */
878    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
879
880    /**
881     * <p>This view doesn't show fading edges.</p>
882     * {@hide}
883     */
884    static final int FADING_EDGE_NONE = 0x00000000;
885
886    /**
887     * <p>This view shows horizontal fading edges.</p>
888     * {@hide}
889     */
890    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
891
892    /**
893     * <p>This view shows vertical fading edges.</p>
894     * {@hide}
895     */
896    static final int FADING_EDGE_VERTICAL = 0x00002000;
897
898    /**
899     * <p>Mask for use with setFlags indicating bits used for indicating which
900     * fading edges are enabled.</p>
901     * {@hide}
902     */
903    static final int FADING_EDGE_MASK = 0x00003000;
904
905    /**
906     * <p>Indicates this view can be clicked. When clickable, a View reacts
907     * to clicks by notifying the OnClickListener.<p>
908     * {@hide}
909     */
910    static final int CLICKABLE = 0x00004000;
911
912    /**
913     * <p>Indicates this view is caching its drawing into a bitmap.</p>
914     * {@hide}
915     */
916    static final int DRAWING_CACHE_ENABLED = 0x00008000;
917
918    /**
919     * <p>Indicates that no icicle should be saved for this view.<p>
920     * {@hide}
921     */
922    static final int SAVE_DISABLED = 0x000010000;
923
924    /**
925     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
926     * property.</p>
927     * {@hide}
928     */
929    static final int SAVE_DISABLED_MASK = 0x000010000;
930
931    /**
932     * <p>Indicates that no drawing cache should ever be created for this view.<p>
933     * {@hide}
934     */
935    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
936
937    /**
938     * <p>Indicates this view can take / keep focus when int touch mode.</p>
939     * {@hide}
940     */
941    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
942
943    /** @hide */
944    @Retention(RetentionPolicy.SOURCE)
945    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
946    public @interface DrawingCacheQuality {}
947
948    /**
949     * <p>Enables low quality mode for the drawing cache.</p>
950     */
951    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
952
953    /**
954     * <p>Enables high quality mode for the drawing cache.</p>
955     */
956    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
957
958    /**
959     * <p>Enables automatic quality mode for the drawing cache.</p>
960     */
961    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
962
963    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
964            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
965    };
966
967    /**
968     * <p>Mask for use with setFlags indicating bits used for the cache
969     * quality property.</p>
970     * {@hide}
971     */
972    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
973
974    /**
975     * <p>
976     * Indicates this view can be long clicked. When long clickable, a View
977     * reacts to long clicks by notifying the OnLongClickListener or showing a
978     * context menu.
979     * </p>
980     * {@hide}
981     */
982    static final int LONG_CLICKABLE = 0x00200000;
983
984    /**
985     * <p>Indicates that this view gets its drawable states from its direct parent
986     * and ignores its original internal states.</p>
987     *
988     * @hide
989     */
990    static final int DUPLICATE_PARENT_STATE = 0x00400000;
991
992    /**
993     * <p>
994     * Indicates this view can be stylus button pressed. When stylus button
995     * pressable, a View reacts to stylus button presses by notifiying
996     * the OnStylusButtonPressListener.
997     * </p>
998     * {@hide}
999     */
1000    static final int STYLUS_BUTTON_PRESSABLE = 0x00800000;
1001
1002
1003    /** @hide */
1004    @IntDef({
1005        SCROLLBARS_INSIDE_OVERLAY,
1006        SCROLLBARS_INSIDE_INSET,
1007        SCROLLBARS_OUTSIDE_OVERLAY,
1008        SCROLLBARS_OUTSIDE_INSET
1009    })
1010    @Retention(RetentionPolicy.SOURCE)
1011    public @interface ScrollBarStyle {}
1012
1013    /**
1014     * The scrollbar style to display the scrollbars inside the content area,
1015     * without increasing the padding. The scrollbars will be overlaid with
1016     * translucency on the view's content.
1017     */
1018    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
1019
1020    /**
1021     * The scrollbar style to display the scrollbars inside the padded area,
1022     * increasing the padding of the view. The scrollbars will not overlap the
1023     * content area of the view.
1024     */
1025    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
1026
1027    /**
1028     * The scrollbar style to display the scrollbars at the edge of the view,
1029     * without increasing the padding. The scrollbars will be overlaid with
1030     * translucency.
1031     */
1032    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1033
1034    /**
1035     * The scrollbar style to display the scrollbars at the edge of the view,
1036     * increasing the padding of the view. The scrollbars will only overlap the
1037     * background, if any.
1038     */
1039    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1040
1041    /**
1042     * Mask to check if the scrollbar style is overlay or inset.
1043     * {@hide}
1044     */
1045    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1046
1047    /**
1048     * Mask to check if the scrollbar style is inside or outside.
1049     * {@hide}
1050     */
1051    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1052
1053    /**
1054     * Mask for scrollbar style.
1055     * {@hide}
1056     */
1057    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1058
1059    /**
1060     * View flag indicating that the screen should remain on while the
1061     * window containing this view is visible to the user.  This effectively
1062     * takes care of automatically setting the WindowManager's
1063     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1064     */
1065    public static final int KEEP_SCREEN_ON = 0x04000000;
1066
1067    /**
1068     * View flag indicating whether this view should have sound effects enabled
1069     * for events such as clicking and touching.
1070     */
1071    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1072
1073    /**
1074     * View flag indicating whether this view should have haptic feedback
1075     * enabled for events such as long presses.
1076     */
1077    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1078
1079    /**
1080     * <p>Indicates that the view hierarchy should stop saving state when
1081     * it reaches this view.  If state saving is initiated immediately at
1082     * the view, it will be allowed.
1083     * {@hide}
1084     */
1085    static final int PARENT_SAVE_DISABLED = 0x20000000;
1086
1087    /**
1088     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1089     * {@hide}
1090     */
1091    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1092
1093    /** @hide */
1094    @IntDef(flag = true,
1095            value = {
1096                FOCUSABLES_ALL,
1097                FOCUSABLES_TOUCH_MODE
1098            })
1099    @Retention(RetentionPolicy.SOURCE)
1100    public @interface FocusableMode {}
1101
1102    /**
1103     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1104     * should add all focusable Views regardless if they are focusable in touch mode.
1105     */
1106    public static final int FOCUSABLES_ALL = 0x00000000;
1107
1108    /**
1109     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1110     * should add only Views focusable in touch mode.
1111     */
1112    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1113
1114    /** @hide */
1115    @IntDef({
1116            FOCUS_BACKWARD,
1117            FOCUS_FORWARD,
1118            FOCUS_LEFT,
1119            FOCUS_UP,
1120            FOCUS_RIGHT,
1121            FOCUS_DOWN
1122    })
1123    @Retention(RetentionPolicy.SOURCE)
1124    public @interface FocusDirection {}
1125
1126    /** @hide */
1127    @IntDef({
1128            FOCUS_LEFT,
1129            FOCUS_UP,
1130            FOCUS_RIGHT,
1131            FOCUS_DOWN
1132    })
1133    @Retention(RetentionPolicy.SOURCE)
1134    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1135
1136    /**
1137     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1138     * item.
1139     */
1140    public static final int FOCUS_BACKWARD = 0x00000001;
1141
1142    /**
1143     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1144     * item.
1145     */
1146    public static final int FOCUS_FORWARD = 0x00000002;
1147
1148    /**
1149     * Use with {@link #focusSearch(int)}. Move focus to the left.
1150     */
1151    public static final int FOCUS_LEFT = 0x00000011;
1152
1153    /**
1154     * Use with {@link #focusSearch(int)}. Move focus up.
1155     */
1156    public static final int FOCUS_UP = 0x00000021;
1157
1158    /**
1159     * Use with {@link #focusSearch(int)}. Move focus to the right.
1160     */
1161    public static final int FOCUS_RIGHT = 0x00000042;
1162
1163    /**
1164     * Use with {@link #focusSearch(int)}. Move focus down.
1165     */
1166    public static final int FOCUS_DOWN = 0x00000082;
1167
1168    /**
1169     * Bits of {@link #getMeasuredWidthAndState()} and
1170     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1171     */
1172    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1173
1174    /**
1175     * Bits of {@link #getMeasuredWidthAndState()} and
1176     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1177     */
1178    public static final int MEASURED_STATE_MASK = 0xff000000;
1179
1180    /**
1181     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1182     * for functions that combine both width and height into a single int,
1183     * such as {@link #getMeasuredState()} and the childState argument of
1184     * {@link #resolveSizeAndState(int, int, int)}.
1185     */
1186    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1187
1188    /**
1189     * Bit of {@link #getMeasuredWidthAndState()} and
1190     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1191     * is smaller that the space the view would like to have.
1192     */
1193    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1194
1195    /**
1196     * Base View state sets
1197     */
1198    // Singles
1199    /**
1200     * Indicates the view has no states set. States are used with
1201     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1202     * view depending on its state.
1203     *
1204     * @see android.graphics.drawable.Drawable
1205     * @see #getDrawableState()
1206     */
1207    protected static final int[] EMPTY_STATE_SET;
1208    /**
1209     * Indicates the view is enabled. States are used with
1210     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1211     * view depending on its state.
1212     *
1213     * @see android.graphics.drawable.Drawable
1214     * @see #getDrawableState()
1215     */
1216    protected static final int[] ENABLED_STATE_SET;
1217    /**
1218     * Indicates the view is focused. States are used with
1219     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1220     * view depending on its state.
1221     *
1222     * @see android.graphics.drawable.Drawable
1223     * @see #getDrawableState()
1224     */
1225    protected static final int[] FOCUSED_STATE_SET;
1226    /**
1227     * Indicates the view is selected. States are used with
1228     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1229     * view depending on its state.
1230     *
1231     * @see android.graphics.drawable.Drawable
1232     * @see #getDrawableState()
1233     */
1234    protected static final int[] SELECTED_STATE_SET;
1235    /**
1236     * Indicates the view is pressed. States are used with
1237     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1238     * view depending on its state.
1239     *
1240     * @see android.graphics.drawable.Drawable
1241     * @see #getDrawableState()
1242     */
1243    protected static final int[] PRESSED_STATE_SET;
1244    /**
1245     * Indicates the view's window has focus. States are used with
1246     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1247     * view depending on its state.
1248     *
1249     * @see android.graphics.drawable.Drawable
1250     * @see #getDrawableState()
1251     */
1252    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1253    // Doubles
1254    /**
1255     * Indicates the view is enabled and has the focus.
1256     *
1257     * @see #ENABLED_STATE_SET
1258     * @see #FOCUSED_STATE_SET
1259     */
1260    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is enabled and selected.
1263     *
1264     * @see #ENABLED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     */
1267    protected static final int[] ENABLED_SELECTED_STATE_SET;
1268    /**
1269     * Indicates the view is enabled and that its window has focus.
1270     *
1271     * @see #ENABLED_STATE_SET
1272     * @see #WINDOW_FOCUSED_STATE_SET
1273     */
1274    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1275    /**
1276     * Indicates the view is focused and selected.
1277     *
1278     * @see #FOCUSED_STATE_SET
1279     * @see #SELECTED_STATE_SET
1280     */
1281    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1282    /**
1283     * Indicates the view has the focus and that its window has the focus.
1284     *
1285     * @see #FOCUSED_STATE_SET
1286     * @see #WINDOW_FOCUSED_STATE_SET
1287     */
1288    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1289    /**
1290     * Indicates the view is selected and that its window has the focus.
1291     *
1292     * @see #SELECTED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1296    // Triples
1297    /**
1298     * Indicates the view is enabled, focused and selected.
1299     *
1300     * @see #ENABLED_STATE_SET
1301     * @see #FOCUSED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     */
1304    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1305    /**
1306     * Indicates the view is enabled, focused and its window has the focus.
1307     *
1308     * @see #ENABLED_STATE_SET
1309     * @see #FOCUSED_STATE_SET
1310     * @see #WINDOW_FOCUSED_STATE_SET
1311     */
1312    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1313    /**
1314     * Indicates the view is enabled, selected and its window has the focus.
1315     *
1316     * @see #ENABLED_STATE_SET
1317     * @see #SELECTED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is focused, selected and its window has the focus.
1323     *
1324     * @see #FOCUSED_STATE_SET
1325     * @see #SELECTED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is enabled, focused, selected and its window
1331     * has the focus.
1332     *
1333     * @see #ENABLED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     * @see #SELECTED_STATE_SET
1336     * @see #WINDOW_FOCUSED_STATE_SET
1337     */
1338    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1339    /**
1340     * Indicates the view is pressed and its window has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed and selected.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #SELECTED_STATE_SET
1351     */
1352    protected static final int[] PRESSED_SELECTED_STATE_SET;
1353    /**
1354     * Indicates the view is pressed, selected and its window has the focus.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #SELECTED_STATE_SET
1358     * @see #WINDOW_FOCUSED_STATE_SET
1359     */
1360    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1361    /**
1362     * Indicates the view is pressed and focused.
1363     *
1364     * @see #PRESSED_STATE_SET
1365     * @see #FOCUSED_STATE_SET
1366     */
1367    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1368    /**
1369     * Indicates the view is pressed, focused and its window has the focus.
1370     *
1371     * @see #PRESSED_STATE_SET
1372     * @see #FOCUSED_STATE_SET
1373     * @see #WINDOW_FOCUSED_STATE_SET
1374     */
1375    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1376    /**
1377     * Indicates the view is pressed, focused and selected.
1378     *
1379     * @see #PRESSED_STATE_SET
1380     * @see #SELECTED_STATE_SET
1381     * @see #FOCUSED_STATE_SET
1382     */
1383    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1384    /**
1385     * Indicates the view is pressed, focused, selected and its window has the focus.
1386     *
1387     * @see #PRESSED_STATE_SET
1388     * @see #FOCUSED_STATE_SET
1389     * @see #SELECTED_STATE_SET
1390     * @see #WINDOW_FOCUSED_STATE_SET
1391     */
1392    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1393    /**
1394     * Indicates the view is pressed and enabled.
1395     *
1396     * @see #PRESSED_STATE_SET
1397     * @see #ENABLED_STATE_SET
1398     */
1399    protected static final int[] PRESSED_ENABLED_STATE_SET;
1400    /**
1401     * Indicates the view is pressed, enabled and its window has the focus.
1402     *
1403     * @see #PRESSED_STATE_SET
1404     * @see #ENABLED_STATE_SET
1405     * @see #WINDOW_FOCUSED_STATE_SET
1406     */
1407    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1408    /**
1409     * Indicates the view is pressed, enabled and selected.
1410     *
1411     * @see #PRESSED_STATE_SET
1412     * @see #ENABLED_STATE_SET
1413     * @see #SELECTED_STATE_SET
1414     */
1415    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1416    /**
1417     * Indicates the view is pressed, enabled, selected and its window has the
1418     * focus.
1419     *
1420     * @see #PRESSED_STATE_SET
1421     * @see #ENABLED_STATE_SET
1422     * @see #SELECTED_STATE_SET
1423     * @see #WINDOW_FOCUSED_STATE_SET
1424     */
1425    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1426    /**
1427     * Indicates the view is pressed, enabled and focused.
1428     *
1429     * @see #PRESSED_STATE_SET
1430     * @see #ENABLED_STATE_SET
1431     * @see #FOCUSED_STATE_SET
1432     */
1433    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1434    /**
1435     * Indicates the view is pressed, enabled, focused and its window has the
1436     * focus.
1437     *
1438     * @see #PRESSED_STATE_SET
1439     * @see #ENABLED_STATE_SET
1440     * @see #FOCUSED_STATE_SET
1441     * @see #WINDOW_FOCUSED_STATE_SET
1442     */
1443    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1444    /**
1445     * Indicates the view is pressed, enabled, focused and selected.
1446     *
1447     * @see #PRESSED_STATE_SET
1448     * @see #ENABLED_STATE_SET
1449     * @see #SELECTED_STATE_SET
1450     * @see #FOCUSED_STATE_SET
1451     */
1452    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1453    /**
1454     * Indicates the view is pressed, enabled, focused, selected and its window
1455     * has the focus.
1456     *
1457     * @see #PRESSED_STATE_SET
1458     * @see #ENABLED_STATE_SET
1459     * @see #SELECTED_STATE_SET
1460     * @see #FOCUSED_STATE_SET
1461     * @see #WINDOW_FOCUSED_STATE_SET
1462     */
1463    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1464
1465    static {
1466        EMPTY_STATE_SET = StateSet.get(0);
1467
1468        WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED);
1469
1470        SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED);
1471        SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1472                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED);
1473
1474        FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED);
1475        FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1476                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED);
1477        FOCUSED_SELECTED_STATE_SET = StateSet.get(
1478                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED);
1479        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1480                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1481                        | StateSet.VIEW_STATE_FOCUSED);
1482
1483        ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED);
1484        ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1485                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1486        ENABLED_SELECTED_STATE_SET = StateSet.get(
1487                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED);
1488        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1489                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1490                        | StateSet.VIEW_STATE_ENABLED);
1491        ENABLED_FOCUSED_STATE_SET = StateSet.get(
1492                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED);
1493        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1494                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1495                        | StateSet.VIEW_STATE_ENABLED);
1496        ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1497                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1498                        | StateSet.VIEW_STATE_ENABLED);
1499        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1500                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1501                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED);
1502
1503        PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED);
1504        PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1505                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1506        PRESSED_SELECTED_STATE_SET = StateSet.get(
1507                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED);
1508        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1509                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1510                        | StateSet.VIEW_STATE_PRESSED);
1511        PRESSED_FOCUSED_STATE_SET = StateSet.get(
1512                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1513        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1514                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1515                        | StateSet.VIEW_STATE_PRESSED);
1516        PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1517                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1518                        | StateSet.VIEW_STATE_PRESSED);
1519        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1520                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1521                        | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED);
1522        PRESSED_ENABLED_STATE_SET = StateSet.get(
1523                StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1524        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1525                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED
1526                        | StateSet.VIEW_STATE_PRESSED);
1527        PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get(
1528                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED
1529                        | StateSet.VIEW_STATE_PRESSED);
1530        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1531                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1532                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1533        PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get(
1534                StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED
1535                        | StateSet.VIEW_STATE_PRESSED);
1536        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1537                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED
1538                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1539        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get(
1540                StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED
1541                        | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED);
1542        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get(
1543                StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED
1544                        | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED
1545                        | StateSet.VIEW_STATE_PRESSED);
1546    }
1547
1548    /**
1549     * Accessibility event types that are dispatched for text population.
1550     */
1551    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1552            AccessibilityEvent.TYPE_VIEW_CLICKED
1553            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1554            | AccessibilityEvent.TYPE_VIEW_SELECTED
1555            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1556            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1557            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1558            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1559            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1560            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1561            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1562            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1563
1564    /**
1565     * Temporary Rect currently for use in setBackground().  This will probably
1566     * be extended in the future to hold our own class with more than just
1567     * a Rect. :)
1568     */
1569    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1570
1571    /**
1572     * Map used to store views' tags.
1573     */
1574    private SparseArray<Object> mKeyedTags;
1575
1576    /**
1577     * The next available accessibility id.
1578     */
1579    private static int sNextAccessibilityViewId;
1580
1581    /**
1582     * The animation currently associated with this view.
1583     * @hide
1584     */
1585    protected Animation mCurrentAnimation = null;
1586
1587    /**
1588     * Width as measured during measure pass.
1589     * {@hide}
1590     */
1591    @ViewDebug.ExportedProperty(category = "measurement")
1592    int mMeasuredWidth;
1593
1594    /**
1595     * Height as measured during measure pass.
1596     * {@hide}
1597     */
1598    @ViewDebug.ExportedProperty(category = "measurement")
1599    int mMeasuredHeight;
1600
1601    /**
1602     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1603     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1604     * its display list. This flag, used only when hw accelerated, allows us to clear the
1605     * flag while retaining this information until it's needed (at getDisplayList() time and
1606     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1607     *
1608     * {@hide}
1609     */
1610    boolean mRecreateDisplayList = false;
1611
1612    /**
1613     * The view's identifier.
1614     * {@hide}
1615     *
1616     * @see #setId(int)
1617     * @see #getId()
1618     */
1619    @IdRes
1620    @ViewDebug.ExportedProperty(resolveId = true)
1621    int mID = NO_ID;
1622
1623    /**
1624     * The stable ID of this view for accessibility purposes.
1625     */
1626    int mAccessibilityViewId = NO_ID;
1627
1628    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1629
1630    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1631
1632    /**
1633     * The view's tag.
1634     * {@hide}
1635     *
1636     * @see #setTag(Object)
1637     * @see #getTag()
1638     */
1639    protected Object mTag = null;
1640
1641    // for mPrivateFlags:
1642    /** {@hide} */
1643    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1644    /** {@hide} */
1645    static final int PFLAG_FOCUSED                     = 0x00000002;
1646    /** {@hide} */
1647    static final int PFLAG_SELECTED                    = 0x00000004;
1648    /** {@hide} */
1649    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1650    /** {@hide} */
1651    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1652    /** {@hide} */
1653    static final int PFLAG_DRAWN                       = 0x00000020;
1654    /**
1655     * When this flag is set, this view is running an animation on behalf of its
1656     * children and should therefore not cancel invalidate requests, even if they
1657     * lie outside of this view's bounds.
1658     *
1659     * {@hide}
1660     */
1661    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1662    /** {@hide} */
1663    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1664    /** {@hide} */
1665    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1666    /** {@hide} */
1667    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1668    /** {@hide} */
1669    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1670    /** {@hide} */
1671    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1672    /** {@hide} */
1673    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1674    /** {@hide} */
1675    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1676
1677    private static final int PFLAG_PRESSED             = 0x00004000;
1678
1679    /** {@hide} */
1680    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1681    /**
1682     * Flag used to indicate that this view should be drawn once more (and only once
1683     * more) after its animation has completed.
1684     * {@hide}
1685     */
1686    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1687
1688    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1689
1690    /**
1691     * Indicates that the View returned true when onSetAlpha() was called and that
1692     * the alpha must be restored.
1693     * {@hide}
1694     */
1695    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1696
1697    /**
1698     * Set by {@link #setScrollContainer(boolean)}.
1699     */
1700    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1701
1702    /**
1703     * Set by {@link #setScrollContainer(boolean)}.
1704     */
1705    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1706
1707    /**
1708     * View flag indicating whether this view was invalidated (fully or partially.)
1709     *
1710     * @hide
1711     */
1712    static final int PFLAG_DIRTY                       = 0x00200000;
1713
1714    /**
1715     * View flag indicating whether this view was invalidated by an opaque
1716     * invalidate request.
1717     *
1718     * @hide
1719     */
1720    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1721
1722    /**
1723     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1724     *
1725     * @hide
1726     */
1727    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1728
1729    /**
1730     * Indicates whether the background is opaque.
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1735
1736    /**
1737     * Indicates whether the scrollbars are opaque.
1738     *
1739     * @hide
1740     */
1741    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1742
1743    /**
1744     * Indicates whether the view is opaque.
1745     *
1746     * @hide
1747     */
1748    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1749
1750    /**
1751     * Indicates a prepressed state;
1752     * the short time between ACTION_DOWN and recognizing
1753     * a 'real' press. Prepressed is used to recognize quick taps
1754     * even when they are shorter than ViewConfiguration.getTapTimeout().
1755     *
1756     * @hide
1757     */
1758    private static final int PFLAG_PREPRESSED          = 0x02000000;
1759
1760    /**
1761     * Indicates whether the view is temporarily detached.
1762     *
1763     * @hide
1764     */
1765    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1766
1767    /**
1768     * Indicates that we should awaken scroll bars once attached
1769     *
1770     * @hide
1771     */
1772    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1773
1774    /**
1775     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1776     * @hide
1777     */
1778    private static final int PFLAG_HOVERED             = 0x10000000;
1779
1780    /**
1781     * no longer needed, should be reused
1782     */
1783    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1784
1785    /** {@hide} */
1786    static final int PFLAG_ACTIVATED                   = 0x40000000;
1787
1788    /**
1789     * Indicates that this view was specifically invalidated, not just dirtied because some
1790     * child view was invalidated. The flag is used to determine when we need to recreate
1791     * a view's display list (as opposed to just returning a reference to its existing
1792     * display list).
1793     *
1794     * @hide
1795     */
1796    static final int PFLAG_INVALIDATED                 = 0x80000000;
1797
1798    /**
1799     * Masks for mPrivateFlags2, as generated by dumpFlags():
1800     *
1801     * |-------|-------|-------|-------|
1802     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1803     *                                1  PFLAG2_DRAG_HOVERED
1804     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1805     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1806     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1807     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1808     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1809     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1810     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1811     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1812     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1813     *                         11        PFLAG2_TEXT_DIRECTION_FLAGS[6]
1814     *                         111       PFLAG2_TEXT_DIRECTION_FLAGS[7]
1815     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1816     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1817     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1818     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1819     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1820     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1821     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1822     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1823     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1824     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1825     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1826     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1827     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1828     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1829     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1830     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1831     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1832     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1833     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1834     *    1                              PFLAG2_PADDING_RESOLVED
1835     *   1                               PFLAG2_DRAWABLE_RESOLVED
1836     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1837     * |-------|-------|-------|-------|
1838     */
1839
1840    /**
1841     * Indicates that this view has reported that it can accept the current drag's content.
1842     * Cleared when the drag operation concludes.
1843     * @hide
1844     */
1845    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1846
1847    /**
1848     * Indicates that this view is currently directly under the drag location in a
1849     * drag-and-drop operation involving content that it can accept.  Cleared when
1850     * the drag exits the view, or when the drag operation concludes.
1851     * @hide
1852     */
1853    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1854
1855    /** @hide */
1856    @IntDef({
1857        LAYOUT_DIRECTION_LTR,
1858        LAYOUT_DIRECTION_RTL,
1859        LAYOUT_DIRECTION_INHERIT,
1860        LAYOUT_DIRECTION_LOCALE
1861    })
1862    @Retention(RetentionPolicy.SOURCE)
1863    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1864    public @interface LayoutDir {}
1865
1866    /** @hide */
1867    @IntDef({
1868        LAYOUT_DIRECTION_LTR,
1869        LAYOUT_DIRECTION_RTL
1870    })
1871    @Retention(RetentionPolicy.SOURCE)
1872    public @interface ResolvedLayoutDir {}
1873
1874    /**
1875     * Horizontal layout direction of this view is from Left to Right.
1876     * Use with {@link #setLayoutDirection}.
1877     */
1878    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1879
1880    /**
1881     * Horizontal layout direction of this view is from Right to Left.
1882     * Use with {@link #setLayoutDirection}.
1883     */
1884    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1885
1886    /**
1887     * Horizontal layout direction of this view is inherited from its parent.
1888     * Use with {@link #setLayoutDirection}.
1889     */
1890    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1891
1892    /**
1893     * Horizontal layout direction of this view is from deduced from the default language
1894     * script for the locale. Use with {@link #setLayoutDirection}.
1895     */
1896    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1897
1898    /**
1899     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1900     * @hide
1901     */
1902    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1903
1904    /**
1905     * Mask for use with private flags indicating bits used for horizontal layout direction.
1906     * @hide
1907     */
1908    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1909
1910    /**
1911     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1912     * right-to-left direction.
1913     * @hide
1914     */
1915    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1916
1917    /**
1918     * Indicates whether the view horizontal layout direction has been resolved.
1919     * @hide
1920     */
1921    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1922
1923    /**
1924     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1925     * @hide
1926     */
1927    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1928            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1929
1930    /*
1931     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1932     * flag value.
1933     * @hide
1934     */
1935    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1936            LAYOUT_DIRECTION_LTR,
1937            LAYOUT_DIRECTION_RTL,
1938            LAYOUT_DIRECTION_INHERIT,
1939            LAYOUT_DIRECTION_LOCALE
1940    };
1941
1942    /**
1943     * Default horizontal layout direction.
1944     */
1945    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1946
1947    /**
1948     * Default horizontal layout direction.
1949     * @hide
1950     */
1951    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1952
1953    /**
1954     * Text direction is inherited through {@link ViewGroup}
1955     */
1956    public static final int TEXT_DIRECTION_INHERIT = 0;
1957
1958    /**
1959     * Text direction is using "first strong algorithm". The first strong directional character
1960     * determines the paragraph direction. If there is no strong directional character, the
1961     * paragraph direction is the view's resolved layout direction.
1962     */
1963    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1964
1965    /**
1966     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1967     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1968     * If there are neither, the paragraph direction is the view's resolved layout direction.
1969     */
1970    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1971
1972    /**
1973     * Text direction is forced to LTR.
1974     */
1975    public static final int TEXT_DIRECTION_LTR = 3;
1976
1977    /**
1978     * Text direction is forced to RTL.
1979     */
1980    public static final int TEXT_DIRECTION_RTL = 4;
1981
1982    /**
1983     * Text direction is coming from the system Locale.
1984     */
1985    public static final int TEXT_DIRECTION_LOCALE = 5;
1986
1987    /**
1988     * Text direction is using "first strong algorithm". The first strong directional character
1989     * determines the paragraph direction. If there is no strong directional character, the
1990     * paragraph direction is LTR.
1991     */
1992    public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6;
1993
1994    /**
1995     * Text direction is using "first strong algorithm". The first strong directional character
1996     * determines the paragraph direction. If there is no strong directional character, the
1997     * paragraph direction is RTL.
1998     */
1999    public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7;
2000
2001    /**
2002     * Default text direction is inherited
2003     */
2004    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2005
2006    /**
2007     * Default resolved text direction
2008     * @hide
2009     */
2010    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2011
2012    /**
2013     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2014     * @hide
2015     */
2016    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2017
2018    /**
2019     * Mask for use with private flags indicating bits used for text direction.
2020     * @hide
2021     */
2022    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2023            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2024
2025    /**
2026     * Array of text direction flags for mapping attribute "textDirection" to correct
2027     * flag value.
2028     * @hide
2029     */
2030    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2031            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2032            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2033            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2034            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2035            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2036            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2037            TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2038            TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2039    };
2040
2041    /**
2042     * Indicates whether the view text direction has been resolved.
2043     * @hide
2044     */
2045    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2046            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2047
2048    /**
2049     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2050     * @hide
2051     */
2052    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2053
2054    /**
2055     * Mask for use with private flags indicating bits used for resolved text direction.
2056     * @hide
2057     */
2058    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2059            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2060
2061    /**
2062     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2063     * @hide
2064     */
2065    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2066            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2067
2068    /** @hide */
2069    @IntDef({
2070        TEXT_ALIGNMENT_INHERIT,
2071        TEXT_ALIGNMENT_GRAVITY,
2072        TEXT_ALIGNMENT_CENTER,
2073        TEXT_ALIGNMENT_TEXT_START,
2074        TEXT_ALIGNMENT_TEXT_END,
2075        TEXT_ALIGNMENT_VIEW_START,
2076        TEXT_ALIGNMENT_VIEW_END
2077    })
2078    @Retention(RetentionPolicy.SOURCE)
2079    public @interface TextAlignment {}
2080
2081    /**
2082     * Default text alignment. The text alignment of this View is inherited from its parent.
2083     * Use with {@link #setTextAlignment(int)}
2084     */
2085    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2086
2087    /**
2088     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2089     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2090     *
2091     * Use with {@link #setTextAlignment(int)}
2092     */
2093    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2094
2095    /**
2096     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2097     *
2098     * Use with {@link #setTextAlignment(int)}
2099     */
2100    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2101
2102    /**
2103     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2104     *
2105     * Use with {@link #setTextAlignment(int)}
2106     */
2107    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2108
2109    /**
2110     * Center the paragraph, e.g. ALIGN_CENTER.
2111     *
2112     * Use with {@link #setTextAlignment(int)}
2113     */
2114    public static final int TEXT_ALIGNMENT_CENTER = 4;
2115
2116    /**
2117     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2118     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2119     *
2120     * Use with {@link #setTextAlignment(int)}
2121     */
2122    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2123
2124    /**
2125     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2126     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2127     *
2128     * Use with {@link #setTextAlignment(int)}
2129     */
2130    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2131
2132    /**
2133     * Default text alignment is inherited
2134     */
2135    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2136
2137    /**
2138     * Default resolved text alignment
2139     * @hide
2140     */
2141    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2142
2143    /**
2144      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2145      * @hide
2146      */
2147    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2148
2149    /**
2150      * Mask for use with private flags indicating bits used for text alignment.
2151      * @hide
2152      */
2153    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2154
2155    /**
2156     * Array of text direction flags for mapping attribute "textAlignment" to correct
2157     * flag value.
2158     * @hide
2159     */
2160    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2161            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2162            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2163            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2164            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2165            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2166            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2167            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2168    };
2169
2170    /**
2171     * Indicates whether the view text alignment has been resolved.
2172     * @hide
2173     */
2174    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2175
2176    /**
2177     * Bit shift to get the resolved text alignment.
2178     * @hide
2179     */
2180    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2181
2182    /**
2183     * Mask for use with private flags indicating bits used for text alignment.
2184     * @hide
2185     */
2186    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2187            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2188
2189    /**
2190     * Indicates whether if the view text alignment has been resolved to gravity
2191     */
2192    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2193            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2194
2195    // Accessiblity constants for mPrivateFlags2
2196
2197    /**
2198     * Shift for the bits in {@link #mPrivateFlags2} related to the
2199     * "importantForAccessibility" attribute.
2200     */
2201    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2202
2203    /**
2204     * Automatically determine whether a view is important for accessibility.
2205     */
2206    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2207
2208    /**
2209     * The view is important for accessibility.
2210     */
2211    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2212
2213    /**
2214     * The view is not important for accessibility.
2215     */
2216    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2217
2218    /**
2219     * The view is not important for accessibility, nor are any of its
2220     * descendant views.
2221     */
2222    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2223
2224    /**
2225     * The default whether the view is important for accessibility.
2226     */
2227    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2228
2229    /**
2230     * Mask for obtainig the bits which specify how to determine
2231     * whether a view is important for accessibility.
2232     */
2233    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2234        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2235        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2236        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2237
2238    /**
2239     * Shift for the bits in {@link #mPrivateFlags2} related to the
2240     * "accessibilityLiveRegion" attribute.
2241     */
2242    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2243
2244    /**
2245     * Live region mode specifying that accessibility services should not
2246     * automatically announce changes to this view. This is the default live
2247     * region mode for most views.
2248     * <p>
2249     * Use with {@link #setAccessibilityLiveRegion(int)}.
2250     */
2251    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2252
2253    /**
2254     * Live region mode specifying that accessibility services should announce
2255     * changes to this view.
2256     * <p>
2257     * Use with {@link #setAccessibilityLiveRegion(int)}.
2258     */
2259    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2260
2261    /**
2262     * Live region mode specifying that accessibility services should interrupt
2263     * ongoing speech to immediately announce changes to this view.
2264     * <p>
2265     * Use with {@link #setAccessibilityLiveRegion(int)}.
2266     */
2267    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2268
2269    /**
2270     * The default whether the view is important for accessibility.
2271     */
2272    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2273
2274    /**
2275     * Mask for obtaining the bits which specify a view's accessibility live
2276     * region mode.
2277     */
2278    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2279            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2280            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2281
2282    /**
2283     * Flag indicating whether a view has accessibility focus.
2284     */
2285    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2286
2287    /**
2288     * Flag whether the accessibility state of the subtree rooted at this view changed.
2289     */
2290    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2291
2292    /**
2293     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2294     * is used to check whether later changes to the view's transform should invalidate the
2295     * view to force the quickReject test to run again.
2296     */
2297    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2298
2299    /**
2300     * Flag indicating that start/end padding has been resolved into left/right padding
2301     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2302     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2303     * during measurement. In some special cases this is required such as when an adapter-based
2304     * view measures prospective children without attaching them to a window.
2305     */
2306    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2307
2308    /**
2309     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2310     */
2311    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2312
2313    /**
2314     * Indicates that the view is tracking some sort of transient state
2315     * that the app should not need to be aware of, but that the framework
2316     * should take special care to preserve.
2317     */
2318    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2319
2320    /**
2321     * Group of bits indicating that RTL properties resolution is done.
2322     */
2323    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2324            PFLAG2_TEXT_DIRECTION_RESOLVED |
2325            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2326            PFLAG2_PADDING_RESOLVED |
2327            PFLAG2_DRAWABLE_RESOLVED;
2328
2329    // There are a couple of flags left in mPrivateFlags2
2330
2331    /* End of masks for mPrivateFlags2 */
2332
2333    /**
2334     * Masks for mPrivateFlags3, as generated by dumpFlags():
2335     *
2336     * |-------|-------|-------|-------|
2337     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2338     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2339     *                               1   PFLAG3_IS_LAID_OUT
2340     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2341     *                             1     PFLAG3_CALLED_SUPER
2342     *                            1      PFLAG3_APPLYING_INSETS
2343     *                           1       PFLAG3_FITTING_SYSTEM_WINDOWS
2344     *                          1        PFLAG3_NESTED_SCROLLING_ENABLED
2345     *                         1         PFLAG3_ASSIST_BLOCKED
2346     * |-------|-------|-------|-------|
2347     */
2348
2349    /**
2350     * Flag indicating that view has a transform animation set on it. This is used to track whether
2351     * an animation is cleared between successive frames, in order to tell the associated
2352     * DisplayList to clear its animation matrix.
2353     */
2354    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2355
2356    /**
2357     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2358     * animation is cleared between successive frames, in order to tell the associated
2359     * DisplayList to restore its alpha value.
2360     */
2361    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2362
2363    /**
2364     * Flag indicating that the view has been through at least one layout since it
2365     * was last attached to a window.
2366     */
2367    static final int PFLAG3_IS_LAID_OUT = 0x4;
2368
2369    /**
2370     * Flag indicating that a call to measure() was skipped and should be done
2371     * instead when layout() is invoked.
2372     */
2373    static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8;
2374
2375    /**
2376     * Flag indicating that an overridden method correctly called down to
2377     * the superclass implementation as required by the API spec.
2378     */
2379    static final int PFLAG3_CALLED_SUPER = 0x10;
2380
2381    /**
2382     * Flag indicating that we're in the process of applying window insets.
2383     */
2384    static final int PFLAG3_APPLYING_INSETS = 0x20;
2385
2386    /**
2387     * Flag indicating that we're in the process of fitting system windows using the old method.
2388     */
2389    static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40;
2390
2391    /**
2392     * Flag indicating that nested scrolling is enabled for this view.
2393     * The view will optionally cooperate with views up its parent chain to allow for
2394     * integrated nested scrolling along the same axis.
2395     */
2396    static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80;
2397
2398    /* End of masks for mPrivateFlags3 */
2399
2400    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2401
2402    /**
2403     * <p>Indicates that we are allowing {@link android.view.ViewAssistStructure} to traverse
2404     * into this view.<p>
2405     */
2406    static final int PFLAG3_ASSIST_BLOCKED = 0x100;
2407
2408    /**
2409     * Always allow a user to over-scroll this view, provided it is a
2410     * view that can scroll.
2411     *
2412     * @see #getOverScrollMode()
2413     * @see #setOverScrollMode(int)
2414     */
2415    public static final int OVER_SCROLL_ALWAYS = 0;
2416
2417    /**
2418     * Allow a user to over-scroll this view only if the content is large
2419     * enough to meaningfully scroll, provided it is a view that can scroll.
2420     *
2421     * @see #getOverScrollMode()
2422     * @see #setOverScrollMode(int)
2423     */
2424    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2425
2426    /**
2427     * Never allow a user to over-scroll this view.
2428     *
2429     * @see #getOverScrollMode()
2430     * @see #setOverScrollMode(int)
2431     */
2432    public static final int OVER_SCROLL_NEVER = 2;
2433
2434    /**
2435     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2436     * requested the system UI (status bar) to be visible (the default).
2437     *
2438     * @see #setSystemUiVisibility(int)
2439     */
2440    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2441
2442    /**
2443     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2444     * system UI to enter an unobtrusive "low profile" mode.
2445     *
2446     * <p>This is for use in games, book readers, video players, or any other
2447     * "immersive" application where the usual system chrome is deemed too distracting.
2448     *
2449     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2450     *
2451     * @see #setSystemUiVisibility(int)
2452     */
2453    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2454
2455    /**
2456     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2457     * system navigation be temporarily hidden.
2458     *
2459     * <p>This is an even less obtrusive state than that called for by
2460     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2461     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2462     * those to disappear. This is useful (in conjunction with the
2463     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2464     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2465     * window flags) for displaying content using every last pixel on the display.
2466     *
2467     * <p>There is a limitation: because navigation controls are so important, the least user
2468     * interaction will cause them to reappear immediately.  When this happens, both
2469     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2470     * so that both elements reappear at the same time.
2471     *
2472     * @see #setSystemUiVisibility(int)
2473     */
2474    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2475
2476    /**
2477     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2478     * into the normal fullscreen mode so that its content can take over the screen
2479     * while still allowing the user to interact with the application.
2480     *
2481     * <p>This has the same visual effect as
2482     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2483     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2484     * meaning that non-critical screen decorations (such as the status bar) will be
2485     * hidden while the user is in the View's window, focusing the experience on
2486     * that content.  Unlike the window flag, if you are using ActionBar in
2487     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2488     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2489     * hide the action bar.
2490     *
2491     * <p>This approach to going fullscreen is best used over the window flag when
2492     * it is a transient state -- that is, the application does this at certain
2493     * points in its user interaction where it wants to allow the user to focus
2494     * on content, but not as a continuous state.  For situations where the application
2495     * would like to simply stay full screen the entire time (such as a game that
2496     * wants to take over the screen), the
2497     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2498     * is usually a better approach.  The state set here will be removed by the system
2499     * in various situations (such as the user moving to another application) like
2500     * the other system UI states.
2501     *
2502     * <p>When using this flag, the application should provide some easy facility
2503     * for the user to go out of it.  A common example would be in an e-book
2504     * reader, where tapping on the screen brings back whatever screen and UI
2505     * decorations that had been hidden while the user was immersed in reading
2506     * the book.
2507     *
2508     * @see #setSystemUiVisibility(int)
2509     */
2510    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2511
2512    /**
2513     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2514     * flags, we would like a stable view of the content insets given to
2515     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2516     * will always represent the worst case that the application can expect
2517     * as a continuous state.  In the stock Android UI this is the space for
2518     * the system bar, nav bar, and status bar, but not more transient elements
2519     * such as an input method.
2520     *
2521     * The stable layout your UI sees is based on the system UI modes you can
2522     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2523     * then you will get a stable layout for changes of the
2524     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2525     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2526     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2527     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2528     * with a stable layout.  (Note that you should avoid using
2529     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2530     *
2531     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2532     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2533     * then a hidden status bar will be considered a "stable" state for purposes
2534     * here.  This allows your UI to continually hide the status bar, while still
2535     * using the system UI flags to hide the action bar while still retaining
2536     * a stable layout.  Note that changing the window fullscreen flag will never
2537     * provide a stable layout for a clean transition.
2538     *
2539     * <p>If you are using ActionBar in
2540     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2541     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2542     * insets it adds to those given to the application.
2543     */
2544    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2545
2546    /**
2547     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2548     * to be laid out as if it has requested
2549     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2550     * allows it to avoid artifacts when switching in and out of that mode, at
2551     * the expense that some of its user interface may be covered by screen
2552     * decorations when they are shown.  You can perform layout of your inner
2553     * UI elements to account for the navigation system UI through the
2554     * {@link #fitSystemWindows(Rect)} method.
2555     */
2556    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2557
2558    /**
2559     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2560     * to be laid out as if it has requested
2561     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2562     * allows it to avoid artifacts when switching in and out of that mode, at
2563     * the expense that some of its user interface may be covered by screen
2564     * decorations when they are shown.  You can perform layout of your inner
2565     * UI elements to account for non-fullscreen system UI through the
2566     * {@link #fitSystemWindows(Rect)} method.
2567     */
2568    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2569
2570    /**
2571     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2572     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2573     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2574     * user interaction.
2575     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2576     * has an effect when used in combination with that flag.</p>
2577     */
2578    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2579
2580    /**
2581     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2582     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2583     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2584     * experience while also hiding the system bars.  If this flag is not set,
2585     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2586     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2587     * if the user swipes from the top of the screen.
2588     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2589     * system gestures, such as swiping from the top of the screen.  These transient system bars
2590     * will overlay app’s content, may have some degree of transparency, and will automatically
2591     * hide after a short timeout.
2592     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2593     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2594     * with one or both of those flags.</p>
2595     */
2596    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2597
2598    /**
2599     * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that
2600     * is compatible with light status bar backgrounds.
2601     *
2602     * <p>For this to take effect, the window must request
2603     * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
2604     *         FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not
2605     * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
2606     *         FLAG_TRANSLUCENT_STATUS}.
2607     *
2608     * @see android.R.attr#windowLightStatusBar
2609     */
2610    public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
2611
2612    /**
2613     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2614     */
2615    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2616
2617    /**
2618     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2619     */
2620    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2621
2622    /**
2623     * @hide
2624     *
2625     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2626     * out of the public fields to keep the undefined bits out of the developer's way.
2627     *
2628     * Flag to make the status bar not expandable.  Unless you also
2629     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2630     */
2631    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2632
2633    /**
2634     * @hide
2635     *
2636     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2637     * out of the public fields to keep the undefined bits out of the developer's way.
2638     *
2639     * Flag to hide notification icons and scrolling ticker text.
2640     */
2641    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2642
2643    /**
2644     * @hide
2645     *
2646     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2647     * out of the public fields to keep the undefined bits out of the developer's way.
2648     *
2649     * Flag to disable incoming notification alerts.  This will not block
2650     * icons, but it will block sound, vibrating and other visual or aural notifications.
2651     */
2652    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2653
2654    /**
2655     * @hide
2656     *
2657     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2658     * out of the public fields to keep the undefined bits out of the developer's way.
2659     *
2660     * Flag to hide only the scrolling ticker.  Note that
2661     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2662     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2663     */
2664    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2665
2666    /**
2667     * @hide
2668     *
2669     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2670     * out of the public fields to keep the undefined bits out of the developer's way.
2671     *
2672     * Flag to hide the center system info area.
2673     */
2674    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2675
2676    /**
2677     * @hide
2678     *
2679     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2680     * out of the public fields to keep the undefined bits out of the developer's way.
2681     *
2682     * Flag to hide only the home button.  Don't use this
2683     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2684     */
2685    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2686
2687    /**
2688     * @hide
2689     *
2690     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2691     * out of the public fields to keep the undefined bits out of the developer's way.
2692     *
2693     * Flag to hide only the back button. Don't use this
2694     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2695     */
2696    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2697
2698    /**
2699     * @hide
2700     *
2701     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2702     * out of the public fields to keep the undefined bits out of the developer's way.
2703     *
2704     * Flag to hide only the clock.  You might use this if your activity has
2705     * its own clock making the status bar's clock redundant.
2706     */
2707    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2708
2709    /**
2710     * @hide
2711     *
2712     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2713     * out of the public fields to keep the undefined bits out of the developer's way.
2714     *
2715     * Flag to hide only the recent apps button. Don't use this
2716     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2717     */
2718    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2719
2720    /**
2721     * @hide
2722     *
2723     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2724     * out of the public fields to keep the undefined bits out of the developer's way.
2725     *
2726     * Flag to disable the global search gesture. Don't use this
2727     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2728     */
2729    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2730
2731    /**
2732     * @hide
2733     *
2734     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2735     * out of the public fields to keep the undefined bits out of the developer's way.
2736     *
2737     * Flag to specify that the status bar is displayed in transient mode.
2738     */
2739    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2740
2741    /**
2742     * @hide
2743     *
2744     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2745     * out of the public fields to keep the undefined bits out of the developer's way.
2746     *
2747     * Flag to specify that the navigation bar is displayed in transient mode.
2748     */
2749    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
2750
2751    /**
2752     * @hide
2753     *
2754     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2755     * out of the public fields to keep the undefined bits out of the developer's way.
2756     *
2757     * Flag to specify that the hidden status bar would like to be shown.
2758     */
2759    public static final int STATUS_BAR_UNHIDE = 0x10000000;
2760
2761    /**
2762     * @hide
2763     *
2764     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2765     * out of the public fields to keep the undefined bits out of the developer's way.
2766     *
2767     * Flag to specify that the hidden navigation bar would like to be shown.
2768     */
2769    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
2770
2771    /**
2772     * @hide
2773     *
2774     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2775     * out of the public fields to keep the undefined bits out of the developer's way.
2776     *
2777     * Flag to specify that the status bar is displayed in translucent mode.
2778     */
2779    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
2780
2781    /**
2782     * @hide
2783     *
2784     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2785     * out of the public fields to keep the undefined bits out of the developer's way.
2786     *
2787     * Flag to specify that the navigation bar is displayed in translucent mode.
2788     */
2789    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2790
2791    /**
2792     * @hide
2793     *
2794     * Whether Recents is visible or not.
2795     */
2796    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2797
2798    /**
2799     * @hide
2800     *
2801     * Makes system ui transparent.
2802     */
2803    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2804
2805    /**
2806     * @hide
2807     */
2808    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2809
2810    /**
2811     * These are the system UI flags that can be cleared by events outside
2812     * of an application.  Currently this is just the ability to tap on the
2813     * screen while hiding the navigation bar to have it return.
2814     * @hide
2815     */
2816    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2817            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2818            | SYSTEM_UI_FLAG_FULLSCREEN;
2819
2820    /**
2821     * Flags that can impact the layout in relation to system UI.
2822     */
2823    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2824            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2825            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2826
2827    /** @hide */
2828    @IntDef(flag = true,
2829            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2830    @Retention(RetentionPolicy.SOURCE)
2831    public @interface FindViewFlags {}
2832
2833    /**
2834     * Find views that render the specified text.
2835     *
2836     * @see #findViewsWithText(ArrayList, CharSequence, int)
2837     */
2838    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2839
2840    /**
2841     * Find find views that contain the specified content description.
2842     *
2843     * @see #findViewsWithText(ArrayList, CharSequence, int)
2844     */
2845    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2846
2847    /**
2848     * Find views that contain {@link AccessibilityNodeProvider}. Such
2849     * a View is a root of virtual view hierarchy and may contain the searched
2850     * text. If this flag is set Views with providers are automatically
2851     * added and it is a responsibility of the client to call the APIs of
2852     * the provider to determine whether the virtual tree rooted at this View
2853     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2854     * representing the virtual views with this text.
2855     *
2856     * @see #findViewsWithText(ArrayList, CharSequence, int)
2857     *
2858     * @hide
2859     */
2860    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2861
2862    /**
2863     * The undefined cursor position.
2864     *
2865     * @hide
2866     */
2867    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2868
2869    /**
2870     * Indicates that the screen has changed state and is now off.
2871     *
2872     * @see #onScreenStateChanged(int)
2873     */
2874    public static final int SCREEN_STATE_OFF = 0x0;
2875
2876    /**
2877     * Indicates that the screen has changed state and is now on.
2878     *
2879     * @see #onScreenStateChanged(int)
2880     */
2881    public static final int SCREEN_STATE_ON = 0x1;
2882
2883    /**
2884     * Indicates no axis of view scrolling.
2885     */
2886    public static final int SCROLL_AXIS_NONE = 0;
2887
2888    /**
2889     * Indicates scrolling along the horizontal axis.
2890     */
2891    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2892
2893    /**
2894     * Indicates scrolling along the vertical axis.
2895     */
2896    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2897
2898    /**
2899     * Controls the over-scroll mode for this view.
2900     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2901     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2902     * and {@link #OVER_SCROLL_NEVER}.
2903     */
2904    private int mOverScrollMode;
2905
2906    /**
2907     * The parent this view is attached to.
2908     * {@hide}
2909     *
2910     * @see #getParent()
2911     */
2912    protected ViewParent mParent;
2913
2914    /**
2915     * {@hide}
2916     */
2917    AttachInfo mAttachInfo;
2918
2919    /**
2920     * {@hide}
2921     */
2922    @ViewDebug.ExportedProperty(flagMapping = {
2923        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2924                name = "FORCE_LAYOUT"),
2925        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2926                name = "LAYOUT_REQUIRED"),
2927        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2928            name = "DRAWING_CACHE_INVALID", outputIf = false),
2929        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2930        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2931        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2932        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2933    }, formatToHexString = true)
2934    int mPrivateFlags;
2935    int mPrivateFlags2;
2936    int mPrivateFlags3;
2937
2938    /**
2939     * This view's request for the visibility of the status bar.
2940     * @hide
2941     */
2942    @ViewDebug.ExportedProperty(flagMapping = {
2943        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2944                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2945                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2946        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2947                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2948                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2949        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2950                                equals = SYSTEM_UI_FLAG_VISIBLE,
2951                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2952    }, formatToHexString = true)
2953    int mSystemUiVisibility;
2954
2955    /**
2956     * Reference count for transient state.
2957     * @see #setHasTransientState(boolean)
2958     */
2959    int mTransientStateCount = 0;
2960
2961    /**
2962     * Count of how many windows this view has been attached to.
2963     */
2964    int mWindowAttachCount;
2965
2966    /**
2967     * The layout parameters associated with this view and used by the parent
2968     * {@link android.view.ViewGroup} to determine how this view should be
2969     * laid out.
2970     * {@hide}
2971     */
2972    protected ViewGroup.LayoutParams mLayoutParams;
2973
2974    /**
2975     * The view flags hold various views states.
2976     * {@hide}
2977     */
2978    @ViewDebug.ExportedProperty(formatToHexString = true)
2979    int mViewFlags;
2980
2981    static class TransformationInfo {
2982        /**
2983         * The transform matrix for the View. This transform is calculated internally
2984         * based on the translation, rotation, and scale properties.
2985         *
2986         * Do *not* use this variable directly; instead call getMatrix(), which will
2987         * load the value from the View's RenderNode.
2988         */
2989        private final Matrix mMatrix = new Matrix();
2990
2991        /**
2992         * The inverse transform matrix for the View. This transform is calculated
2993         * internally based on the translation, rotation, and scale properties.
2994         *
2995         * Do *not* use this variable directly; instead call getInverseMatrix(),
2996         * which will load the value from the View's RenderNode.
2997         */
2998        private Matrix mInverseMatrix;
2999
3000        /**
3001         * The opacity of the View. This is a value from 0 to 1, where 0 means
3002         * completely transparent and 1 means completely opaque.
3003         */
3004        @ViewDebug.ExportedProperty
3005        float mAlpha = 1f;
3006
3007        /**
3008         * The opacity of the view as manipulated by the Fade transition. This is a hidden
3009         * property only used by transitions, which is composited with the other alpha
3010         * values to calculate the final visual alpha value.
3011         */
3012        float mTransitionAlpha = 1f;
3013    }
3014
3015    TransformationInfo mTransformationInfo;
3016
3017    /**
3018     * Current clip bounds. to which all drawing of this view are constrained.
3019     */
3020    Rect mClipBounds = null;
3021
3022    private boolean mLastIsOpaque;
3023
3024    /**
3025     * The distance in pixels from the left edge of this view's parent
3026     * to the left edge of this view.
3027     * {@hide}
3028     */
3029    @ViewDebug.ExportedProperty(category = "layout")
3030    protected int mLeft;
3031    /**
3032     * The distance in pixels from the left edge of this view's parent
3033     * to the right edge of this view.
3034     * {@hide}
3035     */
3036    @ViewDebug.ExportedProperty(category = "layout")
3037    protected int mRight;
3038    /**
3039     * The distance in pixels from the top edge of this view's parent
3040     * to the top edge of this view.
3041     * {@hide}
3042     */
3043    @ViewDebug.ExportedProperty(category = "layout")
3044    protected int mTop;
3045    /**
3046     * The distance in pixels from the top edge of this view's parent
3047     * to the bottom edge of this view.
3048     * {@hide}
3049     */
3050    @ViewDebug.ExportedProperty(category = "layout")
3051    protected int mBottom;
3052
3053    /**
3054     * The offset, in pixels, by which the content of this view is scrolled
3055     * horizontally.
3056     * {@hide}
3057     */
3058    @ViewDebug.ExportedProperty(category = "scrolling")
3059    protected int mScrollX;
3060    /**
3061     * The offset, in pixels, by which the content of this view is scrolled
3062     * vertically.
3063     * {@hide}
3064     */
3065    @ViewDebug.ExportedProperty(category = "scrolling")
3066    protected int mScrollY;
3067
3068    /**
3069     * The left padding in pixels, that is the distance in pixels between the
3070     * left edge of this view and the left edge of its content.
3071     * {@hide}
3072     */
3073    @ViewDebug.ExportedProperty(category = "padding")
3074    protected int mPaddingLeft = 0;
3075    /**
3076     * The right padding in pixels, that is the distance in pixels between the
3077     * right edge of this view and the right edge of its content.
3078     * {@hide}
3079     */
3080    @ViewDebug.ExportedProperty(category = "padding")
3081    protected int mPaddingRight = 0;
3082    /**
3083     * The top padding in pixels, that is the distance in pixels between the
3084     * top edge of this view and the top edge of its content.
3085     * {@hide}
3086     */
3087    @ViewDebug.ExportedProperty(category = "padding")
3088    protected int mPaddingTop;
3089    /**
3090     * The bottom padding in pixels, that is the distance in pixels between the
3091     * bottom edge of this view and the bottom edge of its content.
3092     * {@hide}
3093     */
3094    @ViewDebug.ExportedProperty(category = "padding")
3095    protected int mPaddingBottom;
3096
3097    /**
3098     * The layout insets in pixels, that is the distance in pixels between the
3099     * visible edges of this view its bounds.
3100     */
3101    private Insets mLayoutInsets;
3102
3103    /**
3104     * Briefly describes the view and is primarily used for accessibility support.
3105     */
3106    private CharSequence mContentDescription;
3107
3108    /**
3109     * Specifies the id of a view for which this view serves as a label for
3110     * accessibility purposes.
3111     */
3112    private int mLabelForId = View.NO_ID;
3113
3114    /**
3115     * Predicate for matching labeled view id with its label for
3116     * accessibility purposes.
3117     */
3118    private MatchLabelForPredicate mMatchLabelForPredicate;
3119
3120    /**
3121     * Specifies a view before which this one is visited in accessibility traversal.
3122     */
3123    private int mAccessibilityTraversalBeforeId = NO_ID;
3124
3125    /**
3126     * Specifies a view after which this one is visited in accessibility traversal.
3127     */
3128    private int mAccessibilityTraversalAfterId = NO_ID;
3129
3130    /**
3131     * Predicate for matching a view by its id.
3132     */
3133    private MatchIdPredicate mMatchIdPredicate;
3134
3135    /**
3136     * Cache the paddingRight set by the user to append to the scrollbar's size.
3137     *
3138     * @hide
3139     */
3140    @ViewDebug.ExportedProperty(category = "padding")
3141    protected int mUserPaddingRight;
3142
3143    /**
3144     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3145     *
3146     * @hide
3147     */
3148    @ViewDebug.ExportedProperty(category = "padding")
3149    protected int mUserPaddingBottom;
3150
3151    /**
3152     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3153     *
3154     * @hide
3155     */
3156    @ViewDebug.ExportedProperty(category = "padding")
3157    protected int mUserPaddingLeft;
3158
3159    /**
3160     * Cache the paddingStart set by the user to append to the scrollbar's size.
3161     *
3162     */
3163    @ViewDebug.ExportedProperty(category = "padding")
3164    int mUserPaddingStart;
3165
3166    /**
3167     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3168     *
3169     */
3170    @ViewDebug.ExportedProperty(category = "padding")
3171    int mUserPaddingEnd;
3172
3173    /**
3174     * Cache initial left padding.
3175     *
3176     * @hide
3177     */
3178    int mUserPaddingLeftInitial;
3179
3180    /**
3181     * Cache initial right padding.
3182     *
3183     * @hide
3184     */
3185    int mUserPaddingRightInitial;
3186
3187    /**
3188     * Default undefined padding
3189     */
3190    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3191
3192    /**
3193     * Cache if a left padding has been defined
3194     */
3195    private boolean mLeftPaddingDefined = false;
3196
3197    /**
3198     * Cache if a right padding has been defined
3199     */
3200    private boolean mRightPaddingDefined = false;
3201
3202    /**
3203     * @hide
3204     */
3205    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3206    /**
3207     * @hide
3208     */
3209    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3210
3211    private LongSparseLongArray mMeasureCache;
3212
3213    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3214    private Drawable mBackground;
3215    private TintInfo mBackgroundTint;
3216
3217    @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_")
3218    private ForegroundInfo mForegroundInfo;
3219
3220    /**
3221     * RenderNode used for backgrounds.
3222     * <p>
3223     * When non-null and valid, this is expected to contain an up-to-date copy
3224     * of the background drawable. It is cleared on temporary detach, and reset
3225     * on cleanup.
3226     */
3227    private RenderNode mBackgroundRenderNode;
3228
3229    private int mBackgroundResource;
3230    private boolean mBackgroundSizeChanged;
3231
3232    private String mTransitionName;
3233
3234    static class TintInfo {
3235        ColorStateList mTintList;
3236        PorterDuff.Mode mTintMode;
3237        boolean mHasTintMode;
3238        boolean mHasTintList;
3239    }
3240
3241    private static class ForegroundInfo {
3242        private Drawable mDrawable;
3243        private TintInfo mTintInfo;
3244        private int mGravity = Gravity.FILL;
3245        private boolean mInsidePadding = true;
3246        private boolean mBoundsChanged = true;
3247        private final Rect mSelfBounds = new Rect();
3248        private final Rect mOverlayBounds = new Rect();
3249    }
3250
3251    static class ListenerInfo {
3252        /**
3253         * Listener used to dispatch focus change events.
3254         * This field should be made private, so it is hidden from the SDK.
3255         * {@hide}
3256         */
3257        protected OnFocusChangeListener mOnFocusChangeListener;
3258
3259        /**
3260         * Listeners for layout change events.
3261         */
3262        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3263
3264        protected OnScrollChangeListener mOnScrollChangeListener;
3265
3266        /**
3267         * Listeners for attach events.
3268         */
3269        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3270
3271        /**
3272         * Listener used to dispatch click events.
3273         * This field should be made private, so it is hidden from the SDK.
3274         * {@hide}
3275         */
3276        public OnClickListener mOnClickListener;
3277
3278        /**
3279         * Listener used to dispatch long click events.
3280         * This field should be made private, so it is hidden from the SDK.
3281         * {@hide}
3282         */
3283        protected OnLongClickListener mOnLongClickListener;
3284
3285        /**
3286         * Listener used to dispatch stylus touch and button press events. This field should be made
3287         * private, so it is hidden from the SDK.
3288         * {@hide}
3289         */
3290        protected OnStylusButtonPressListener mOnStylusButtonPressListener;
3291
3292        /**
3293         * Listener used to build the context menu.
3294         * This field should be made private, so it is hidden from the SDK.
3295         * {@hide}
3296         */
3297        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3298
3299        private OnKeyListener mOnKeyListener;
3300
3301        private OnTouchListener mOnTouchListener;
3302
3303        private OnHoverListener mOnHoverListener;
3304
3305        private OnGenericMotionListener mOnGenericMotionListener;
3306
3307        private OnDragListener mOnDragListener;
3308
3309        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3310
3311        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3312    }
3313
3314    ListenerInfo mListenerInfo;
3315
3316    /**
3317     * The application environment this view lives in.
3318     * This field should be made private, so it is hidden from the SDK.
3319     * {@hide}
3320     */
3321    @ViewDebug.ExportedProperty(deepExport = true)
3322    protected Context mContext;
3323
3324    private final Resources mResources;
3325
3326    private ScrollabilityCache mScrollCache;
3327
3328    private int[] mDrawableState = null;
3329
3330    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3331
3332    /**
3333     * Animator that automatically runs based on state changes.
3334     */
3335    private StateListAnimator mStateListAnimator;
3336
3337    /**
3338     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3339     * the user may specify which view to go to next.
3340     */
3341    private int mNextFocusLeftId = View.NO_ID;
3342
3343    /**
3344     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3345     * the user may specify which view to go to next.
3346     */
3347    private int mNextFocusRightId = View.NO_ID;
3348
3349    /**
3350     * When this view has focus and the next focus is {@link #FOCUS_UP},
3351     * the user may specify which view to go to next.
3352     */
3353    private int mNextFocusUpId = View.NO_ID;
3354
3355    /**
3356     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3357     * the user may specify which view to go to next.
3358     */
3359    private int mNextFocusDownId = View.NO_ID;
3360
3361    /**
3362     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3363     * the user may specify which view to go to next.
3364     */
3365    int mNextFocusForwardId = View.NO_ID;
3366
3367    private CheckForLongPress mPendingCheckForLongPress;
3368    private CheckForTap mPendingCheckForTap = null;
3369    private PerformClick mPerformClick;
3370    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3371
3372    private UnsetPressedState mUnsetPressedState;
3373
3374    /**
3375     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3376     * up event while a long press is invoked as soon as the long press duration is reached, so
3377     * a long press could be performed before the tap is checked, in which case the tap's action
3378     * should not be invoked.
3379     */
3380    private boolean mHasPerformedLongPress;
3381
3382    /**
3383     * Whether the stylus button is currently pressed down. This is true when
3384     * the stylus is touching the screen and the button has been pressed, this
3385     * is false once the stylus has been lifted.
3386     */
3387    private boolean mInStylusButtonPress = false;
3388
3389    /**
3390     * The minimum height of the view. We'll try our best to have the height
3391     * of this view to at least this amount.
3392     */
3393    @ViewDebug.ExportedProperty(category = "measurement")
3394    private int mMinHeight;
3395
3396    /**
3397     * The minimum width of the view. We'll try our best to have the width
3398     * of this view to at least this amount.
3399     */
3400    @ViewDebug.ExportedProperty(category = "measurement")
3401    private int mMinWidth;
3402
3403    /**
3404     * The delegate to handle touch events that are physically in this view
3405     * but should be handled by another view.
3406     */
3407    private TouchDelegate mTouchDelegate = null;
3408
3409    /**
3410     * Solid color to use as a background when creating the drawing cache. Enables
3411     * the cache to use 16 bit bitmaps instead of 32 bit.
3412     */
3413    private int mDrawingCacheBackgroundColor = 0;
3414
3415    /**
3416     * Special tree observer used when mAttachInfo is null.
3417     */
3418    private ViewTreeObserver mFloatingTreeObserver;
3419
3420    /**
3421     * Cache the touch slop from the context that created the view.
3422     */
3423    private int mTouchSlop;
3424
3425    /**
3426     * Object that handles automatic animation of view properties.
3427     */
3428    private ViewPropertyAnimator mAnimator = null;
3429
3430    /**
3431     * Flag indicating that a drag can cross window boundaries.  When
3432     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3433     * with this flag set, all visible applications will be able to participate
3434     * in the drag operation and receive the dragged content.
3435     *
3436     * @hide
3437     */
3438    public static final int DRAG_FLAG_GLOBAL = 1;
3439
3440    /**
3441     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3442     */
3443    private float mVerticalScrollFactor;
3444
3445    /**
3446     * Position of the vertical scroll bar.
3447     */
3448    private int mVerticalScrollbarPosition;
3449
3450    /**
3451     * Position the scroll bar at the default position as determined by the system.
3452     */
3453    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3454
3455    /**
3456     * Position the scroll bar along the left edge.
3457     */
3458    public static final int SCROLLBAR_POSITION_LEFT = 1;
3459
3460    /**
3461     * Position the scroll bar along the right edge.
3462     */
3463    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3464
3465    /**
3466     * Indicates that the view does not have a layer.
3467     *
3468     * @see #getLayerType()
3469     * @see #setLayerType(int, android.graphics.Paint)
3470     * @see #LAYER_TYPE_SOFTWARE
3471     * @see #LAYER_TYPE_HARDWARE
3472     */
3473    public static final int LAYER_TYPE_NONE = 0;
3474
3475    /**
3476     * <p>Indicates that the view has a software layer. A software layer is backed
3477     * by a bitmap and causes the view to be rendered using Android's software
3478     * rendering pipeline, even if hardware acceleration is enabled.</p>
3479     *
3480     * <p>Software layers have various usages:</p>
3481     * <p>When the application is not using hardware acceleration, a software layer
3482     * is useful to apply a specific color filter and/or blending mode and/or
3483     * translucency to a view and all its children.</p>
3484     * <p>When the application is using hardware acceleration, a software layer
3485     * is useful to render drawing primitives not supported by the hardware
3486     * accelerated pipeline. It can also be used to cache a complex view tree
3487     * into a texture and reduce the complexity of drawing operations. For instance,
3488     * when animating a complex view tree with a translation, a software layer can
3489     * be used to render the view tree only once.</p>
3490     * <p>Software layers should be avoided when the affected view tree updates
3491     * often. Every update will require to re-render the software layer, which can
3492     * potentially be slow (particularly when hardware acceleration is turned on
3493     * since the layer will have to be uploaded into a hardware texture after every
3494     * update.)</p>
3495     *
3496     * @see #getLayerType()
3497     * @see #setLayerType(int, android.graphics.Paint)
3498     * @see #LAYER_TYPE_NONE
3499     * @see #LAYER_TYPE_HARDWARE
3500     */
3501    public static final int LAYER_TYPE_SOFTWARE = 1;
3502
3503    /**
3504     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3505     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3506     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3507     * rendering pipeline, but only if hardware acceleration is turned on for the
3508     * view hierarchy. When hardware acceleration is turned off, hardware layers
3509     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3510     *
3511     * <p>A hardware layer is useful to apply a specific color filter and/or
3512     * blending mode and/or translucency to a view and all its children.</p>
3513     * <p>A hardware layer can be used to cache a complex view tree into a
3514     * texture and reduce the complexity of drawing operations. For instance,
3515     * when animating a complex view tree with a translation, a hardware layer can
3516     * be used to render the view tree only once.</p>
3517     * <p>A hardware layer can also be used to increase the rendering quality when
3518     * rotation transformations are applied on a view. It can also be used to
3519     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3520     *
3521     * @see #getLayerType()
3522     * @see #setLayerType(int, android.graphics.Paint)
3523     * @see #LAYER_TYPE_NONE
3524     * @see #LAYER_TYPE_SOFTWARE
3525     */
3526    public static final int LAYER_TYPE_HARDWARE = 2;
3527
3528    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3529            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3530            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3531            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3532    })
3533    int mLayerType = LAYER_TYPE_NONE;
3534    Paint mLayerPaint;
3535
3536    /**
3537     * Set to true when drawing cache is enabled and cannot be created.
3538     *
3539     * @hide
3540     */
3541    public boolean mCachingFailed;
3542    private Bitmap mDrawingCache;
3543    private Bitmap mUnscaledDrawingCache;
3544
3545    /**
3546     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3547     * <p>
3548     * When non-null and valid, this is expected to contain an up-to-date copy
3549     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3550     * cleanup.
3551     */
3552    final RenderNode mRenderNode;
3553
3554    /**
3555     * Set to true when the view is sending hover accessibility events because it
3556     * is the innermost hovered view.
3557     */
3558    private boolean mSendingHoverAccessibilityEvents;
3559
3560    /**
3561     * Delegate for injecting accessibility functionality.
3562     */
3563    AccessibilityDelegate mAccessibilityDelegate;
3564
3565    /**
3566     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3567     * and add/remove objects to/from the overlay directly through the Overlay methods.
3568     */
3569    ViewOverlay mOverlay;
3570
3571    /**
3572     * The currently active parent view for receiving delegated nested scrolling events.
3573     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3574     * by {@link #stopNestedScroll()} at the same point where we clear
3575     * requestDisallowInterceptTouchEvent.
3576     */
3577    private ViewParent mNestedScrollingParent;
3578
3579    /**
3580     * Consistency verifier for debugging purposes.
3581     * @hide
3582     */
3583    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3584            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3585                    new InputEventConsistencyVerifier(this, 0) : null;
3586
3587    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3588
3589    private int[] mTempNestedScrollConsumed;
3590
3591    /**
3592     * An overlay is going to draw this View instead of being drawn as part of this
3593     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3594     * when this view is invalidated.
3595     */
3596    GhostView mGhostView;
3597
3598    /**
3599     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3600     * @hide
3601     */
3602    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3603    public String[] mAttributes;
3604
3605    /**
3606     * Maps a Resource id to its name.
3607     */
3608    private static SparseArray<String> mAttributeMap;
3609
3610    /**
3611     * @hide
3612     */
3613    String mStartActivityRequestWho;
3614
3615    /**
3616     * Simple constructor to use when creating a view from code.
3617     *
3618     * @param context The Context the view is running in, through which it can
3619     *        access the current theme, resources, etc.
3620     */
3621    public View(Context context) {
3622        mContext = context;
3623        mResources = context != null ? context.getResources() : null;
3624        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3625        // Set some flags defaults
3626        mPrivateFlags2 =
3627                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3628                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3629                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3630                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3631                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3632                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3633        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3634        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3635        mUserPaddingStart = UNDEFINED_PADDING;
3636        mUserPaddingEnd = UNDEFINED_PADDING;
3637        mRenderNode = RenderNode.create(getClass().getName(), this);
3638
3639        if (!sCompatibilityDone && context != null) {
3640            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3641
3642            // Older apps may need this compatibility hack for measurement.
3643            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3644
3645            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3646            // of whether a layout was requested on that View.
3647            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3648
3649            Canvas.sCompatibilityRestore = targetSdkVersion < MNC;
3650
3651            sCompatibilityDone = true;
3652        }
3653    }
3654
3655    /**
3656     * Constructor that is called when inflating a view from XML. This is called
3657     * when a view is being constructed from an XML file, supplying attributes
3658     * that were specified in the XML file. This version uses a default style of
3659     * 0, so the only attribute values applied are those in the Context's Theme
3660     * and the given AttributeSet.
3661     *
3662     * <p>
3663     * The method onFinishInflate() will be called after all children have been
3664     * added.
3665     *
3666     * @param context The Context the view is running in, through which it can
3667     *        access the current theme, resources, etc.
3668     * @param attrs The attributes of the XML tag that is inflating the view.
3669     * @see #View(Context, AttributeSet, int)
3670     */
3671    public View(Context context, @Nullable AttributeSet attrs) {
3672        this(context, attrs, 0);
3673    }
3674
3675    /**
3676     * Perform inflation from XML and apply a class-specific base style from a
3677     * theme attribute. This constructor of View allows subclasses to use their
3678     * own base style when they are inflating. For example, a Button class's
3679     * constructor would call this version of the super class constructor and
3680     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3681     * allows the theme's button style to modify all of the base view attributes
3682     * (in particular its background) as well as the Button class's attributes.
3683     *
3684     * @param context The Context the view is running in, through which it can
3685     *        access the current theme, resources, etc.
3686     * @param attrs The attributes of the XML tag that is inflating the view.
3687     * @param defStyleAttr An attribute in the current theme that contains a
3688     *        reference to a style resource that supplies default values for
3689     *        the view. Can be 0 to not look for defaults.
3690     * @see #View(Context, AttributeSet)
3691     */
3692    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
3693        this(context, attrs, defStyleAttr, 0);
3694    }
3695
3696    /**
3697     * Perform inflation from XML and apply a class-specific base style from a
3698     * theme attribute or style resource. This constructor of View allows
3699     * subclasses to use their own base style when they are inflating.
3700     * <p>
3701     * When determining the final value of a particular attribute, there are
3702     * four inputs that come into play:
3703     * <ol>
3704     * <li>Any attribute values in the given AttributeSet.
3705     * <li>The style resource specified in the AttributeSet (named "style").
3706     * <li>The default style specified by <var>defStyleAttr</var>.
3707     * <li>The default style specified by <var>defStyleRes</var>.
3708     * <li>The base values in this theme.
3709     * </ol>
3710     * <p>
3711     * Each of these inputs is considered in-order, with the first listed taking
3712     * precedence over the following ones. In other words, if in the
3713     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3714     * , then the button's text will <em>always</em> be black, regardless of
3715     * what is specified in any of the styles.
3716     *
3717     * @param context The Context the view is running in, through which it can
3718     *        access the current theme, resources, etc.
3719     * @param attrs The attributes of the XML tag that is inflating the view.
3720     * @param defStyleAttr An attribute in the current theme that contains a
3721     *        reference to a style resource that supplies default values for
3722     *        the view. Can be 0 to not look for defaults.
3723     * @param defStyleRes A resource identifier of a style resource that
3724     *        supplies default values for the view, used only if
3725     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3726     *        to not look for defaults.
3727     * @see #View(Context, AttributeSet, int)
3728     */
3729    public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3730        this(context);
3731
3732        final TypedArray a = context.obtainStyledAttributes(
3733                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3734
3735        if (mDebugViewAttributes) {
3736            saveAttributeData(attrs, a);
3737        }
3738
3739        Drawable background = null;
3740
3741        int leftPadding = -1;
3742        int topPadding = -1;
3743        int rightPadding = -1;
3744        int bottomPadding = -1;
3745        int startPadding = UNDEFINED_PADDING;
3746        int endPadding = UNDEFINED_PADDING;
3747
3748        int padding = -1;
3749
3750        int viewFlagValues = 0;
3751        int viewFlagMasks = 0;
3752
3753        boolean setScrollContainer = false;
3754
3755        int x = 0;
3756        int y = 0;
3757
3758        float tx = 0;
3759        float ty = 0;
3760        float tz = 0;
3761        float elevation = 0;
3762        float rotation = 0;
3763        float rotationX = 0;
3764        float rotationY = 0;
3765        float sx = 1f;
3766        float sy = 1f;
3767        boolean transformSet = false;
3768
3769        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3770        int overScrollMode = mOverScrollMode;
3771        boolean initializeScrollbars = false;
3772
3773        boolean startPaddingDefined = false;
3774        boolean endPaddingDefined = false;
3775        boolean leftPaddingDefined = false;
3776        boolean rightPaddingDefined = false;
3777
3778        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3779
3780        final int N = a.getIndexCount();
3781        for (int i = 0; i < N; i++) {
3782            int attr = a.getIndex(i);
3783            switch (attr) {
3784                case com.android.internal.R.styleable.View_background:
3785                    background = a.getDrawable(attr);
3786                    break;
3787                case com.android.internal.R.styleable.View_padding:
3788                    padding = a.getDimensionPixelSize(attr, -1);
3789                    mUserPaddingLeftInitial = padding;
3790                    mUserPaddingRightInitial = padding;
3791                    leftPaddingDefined = true;
3792                    rightPaddingDefined = true;
3793                    break;
3794                 case com.android.internal.R.styleable.View_paddingLeft:
3795                    leftPadding = a.getDimensionPixelSize(attr, -1);
3796                    mUserPaddingLeftInitial = leftPadding;
3797                    leftPaddingDefined = true;
3798                    break;
3799                case com.android.internal.R.styleable.View_paddingTop:
3800                    topPadding = a.getDimensionPixelSize(attr, -1);
3801                    break;
3802                case com.android.internal.R.styleable.View_paddingRight:
3803                    rightPadding = a.getDimensionPixelSize(attr, -1);
3804                    mUserPaddingRightInitial = rightPadding;
3805                    rightPaddingDefined = true;
3806                    break;
3807                case com.android.internal.R.styleable.View_paddingBottom:
3808                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3809                    break;
3810                case com.android.internal.R.styleable.View_paddingStart:
3811                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3812                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3813                    break;
3814                case com.android.internal.R.styleable.View_paddingEnd:
3815                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3816                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3817                    break;
3818                case com.android.internal.R.styleable.View_scrollX:
3819                    x = a.getDimensionPixelOffset(attr, 0);
3820                    break;
3821                case com.android.internal.R.styleable.View_scrollY:
3822                    y = a.getDimensionPixelOffset(attr, 0);
3823                    break;
3824                case com.android.internal.R.styleable.View_alpha:
3825                    setAlpha(a.getFloat(attr, 1f));
3826                    break;
3827                case com.android.internal.R.styleable.View_transformPivotX:
3828                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3829                    break;
3830                case com.android.internal.R.styleable.View_transformPivotY:
3831                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3832                    break;
3833                case com.android.internal.R.styleable.View_translationX:
3834                    tx = a.getDimensionPixelOffset(attr, 0);
3835                    transformSet = true;
3836                    break;
3837                case com.android.internal.R.styleable.View_translationY:
3838                    ty = a.getDimensionPixelOffset(attr, 0);
3839                    transformSet = true;
3840                    break;
3841                case com.android.internal.R.styleable.View_translationZ:
3842                    tz = a.getDimensionPixelOffset(attr, 0);
3843                    transformSet = true;
3844                    break;
3845                case com.android.internal.R.styleable.View_elevation:
3846                    elevation = a.getDimensionPixelOffset(attr, 0);
3847                    transformSet = true;
3848                    break;
3849                case com.android.internal.R.styleable.View_rotation:
3850                    rotation = a.getFloat(attr, 0);
3851                    transformSet = true;
3852                    break;
3853                case com.android.internal.R.styleable.View_rotationX:
3854                    rotationX = a.getFloat(attr, 0);
3855                    transformSet = true;
3856                    break;
3857                case com.android.internal.R.styleable.View_rotationY:
3858                    rotationY = a.getFloat(attr, 0);
3859                    transformSet = true;
3860                    break;
3861                case com.android.internal.R.styleable.View_scaleX:
3862                    sx = a.getFloat(attr, 1f);
3863                    transformSet = true;
3864                    break;
3865                case com.android.internal.R.styleable.View_scaleY:
3866                    sy = a.getFloat(attr, 1f);
3867                    transformSet = true;
3868                    break;
3869                case com.android.internal.R.styleable.View_id:
3870                    mID = a.getResourceId(attr, NO_ID);
3871                    break;
3872                case com.android.internal.R.styleable.View_tag:
3873                    mTag = a.getText(attr);
3874                    break;
3875                case com.android.internal.R.styleable.View_fitsSystemWindows:
3876                    if (a.getBoolean(attr, false)) {
3877                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3878                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3879                    }
3880                    break;
3881                case com.android.internal.R.styleable.View_focusable:
3882                    if (a.getBoolean(attr, false)) {
3883                        viewFlagValues |= FOCUSABLE;
3884                        viewFlagMasks |= FOCUSABLE_MASK;
3885                    }
3886                    break;
3887                case com.android.internal.R.styleable.View_focusableInTouchMode:
3888                    if (a.getBoolean(attr, false)) {
3889                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3890                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3891                    }
3892                    break;
3893                case com.android.internal.R.styleable.View_clickable:
3894                    if (a.getBoolean(attr, false)) {
3895                        viewFlagValues |= CLICKABLE;
3896                        viewFlagMasks |= CLICKABLE;
3897                    }
3898                    break;
3899                case com.android.internal.R.styleable.View_longClickable:
3900                    if (a.getBoolean(attr, false)) {
3901                        viewFlagValues |= LONG_CLICKABLE;
3902                        viewFlagMasks |= LONG_CLICKABLE;
3903                    }
3904                    break;
3905                case com.android.internal.R.styleable.View_stylusButtonPressable:
3906                    if (a.getBoolean(attr, false)) {
3907                        viewFlagValues |= STYLUS_BUTTON_PRESSABLE;
3908                        viewFlagMasks |= STYLUS_BUTTON_PRESSABLE;
3909                    }
3910                    break;
3911                case com.android.internal.R.styleable.View_saveEnabled:
3912                    if (!a.getBoolean(attr, true)) {
3913                        viewFlagValues |= SAVE_DISABLED;
3914                        viewFlagMasks |= SAVE_DISABLED_MASK;
3915                    }
3916                    break;
3917                case com.android.internal.R.styleable.View_assistBlocked:
3918                    if (a.getBoolean(attr, false)) {
3919                        mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
3920                    }
3921                    break;
3922                case com.android.internal.R.styleable.View_duplicateParentState:
3923                    if (a.getBoolean(attr, false)) {
3924                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3925                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3926                    }
3927                    break;
3928                case com.android.internal.R.styleable.View_visibility:
3929                    final int visibility = a.getInt(attr, 0);
3930                    if (visibility != 0) {
3931                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3932                        viewFlagMasks |= VISIBILITY_MASK;
3933                    }
3934                    break;
3935                case com.android.internal.R.styleable.View_layoutDirection:
3936                    // Clear any layout direction flags (included resolved bits) already set
3937                    mPrivateFlags2 &=
3938                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3939                    // Set the layout direction flags depending on the value of the attribute
3940                    final int layoutDirection = a.getInt(attr, -1);
3941                    final int value = (layoutDirection != -1) ?
3942                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3943                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3944                    break;
3945                case com.android.internal.R.styleable.View_drawingCacheQuality:
3946                    final int cacheQuality = a.getInt(attr, 0);
3947                    if (cacheQuality != 0) {
3948                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3949                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3950                    }
3951                    break;
3952                case com.android.internal.R.styleable.View_contentDescription:
3953                    setContentDescription(a.getString(attr));
3954                    break;
3955                case com.android.internal.R.styleable.View_accessibilityTraversalBefore:
3956                    setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID));
3957                    break;
3958                case com.android.internal.R.styleable.View_accessibilityTraversalAfter:
3959                    setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID));
3960                    break;
3961                case com.android.internal.R.styleable.View_labelFor:
3962                    setLabelFor(a.getResourceId(attr, NO_ID));
3963                    break;
3964                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3965                    if (!a.getBoolean(attr, true)) {
3966                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3967                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3968                    }
3969                    break;
3970                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3971                    if (!a.getBoolean(attr, true)) {
3972                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3973                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3974                    }
3975                    break;
3976                case R.styleable.View_scrollbars:
3977                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3978                    if (scrollbars != SCROLLBARS_NONE) {
3979                        viewFlagValues |= scrollbars;
3980                        viewFlagMasks |= SCROLLBARS_MASK;
3981                        initializeScrollbars = true;
3982                    }
3983                    break;
3984                //noinspection deprecation
3985                case R.styleable.View_fadingEdge:
3986                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3987                        // Ignore the attribute starting with ICS
3988                        break;
3989                    }
3990                    // With builds < ICS, fall through and apply fading edges
3991                case R.styleable.View_requiresFadingEdge:
3992                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3993                    if (fadingEdge != FADING_EDGE_NONE) {
3994                        viewFlagValues |= fadingEdge;
3995                        viewFlagMasks |= FADING_EDGE_MASK;
3996                        initializeFadingEdgeInternal(a);
3997                    }
3998                    break;
3999                case R.styleable.View_scrollbarStyle:
4000                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
4001                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4002                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
4003                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
4004                    }
4005                    break;
4006                case R.styleable.View_isScrollContainer:
4007                    setScrollContainer = true;
4008                    if (a.getBoolean(attr, false)) {
4009                        setScrollContainer(true);
4010                    }
4011                    break;
4012                case com.android.internal.R.styleable.View_keepScreenOn:
4013                    if (a.getBoolean(attr, false)) {
4014                        viewFlagValues |= KEEP_SCREEN_ON;
4015                        viewFlagMasks |= KEEP_SCREEN_ON;
4016                    }
4017                    break;
4018                case R.styleable.View_filterTouchesWhenObscured:
4019                    if (a.getBoolean(attr, false)) {
4020                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
4021                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
4022                    }
4023                    break;
4024                case R.styleable.View_nextFocusLeft:
4025                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
4026                    break;
4027                case R.styleable.View_nextFocusRight:
4028                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
4029                    break;
4030                case R.styleable.View_nextFocusUp:
4031                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
4032                    break;
4033                case R.styleable.View_nextFocusDown:
4034                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
4035                    break;
4036                case R.styleable.View_nextFocusForward:
4037                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
4038                    break;
4039                case R.styleable.View_minWidth:
4040                    mMinWidth = a.getDimensionPixelSize(attr, 0);
4041                    break;
4042                case R.styleable.View_minHeight:
4043                    mMinHeight = a.getDimensionPixelSize(attr, 0);
4044                    break;
4045                case R.styleable.View_onClick:
4046                    if (context.isRestricted()) {
4047                        throw new IllegalStateException("The android:onClick attribute cannot "
4048                                + "be used within a restricted context");
4049                    }
4050
4051                    final String handlerName = a.getString(attr);
4052                    if (handlerName != null) {
4053                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
4054                    }
4055                    break;
4056                case R.styleable.View_overScrollMode:
4057                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4058                    break;
4059                case R.styleable.View_verticalScrollbarPosition:
4060                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4061                    break;
4062                case R.styleable.View_layerType:
4063                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4064                    break;
4065                case R.styleable.View_textDirection:
4066                    // Clear any text direction flag already set
4067                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4068                    // Set the text direction flags depending on the value of the attribute
4069                    final int textDirection = a.getInt(attr, -1);
4070                    if (textDirection != -1) {
4071                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4072                    }
4073                    break;
4074                case R.styleable.View_textAlignment:
4075                    // Clear any text alignment flag already set
4076                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4077                    // Set the text alignment flag depending on the value of the attribute
4078                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4079                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4080                    break;
4081                case R.styleable.View_importantForAccessibility:
4082                    setImportantForAccessibility(a.getInt(attr,
4083                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4084                    break;
4085                case R.styleable.View_accessibilityLiveRegion:
4086                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4087                    break;
4088                case R.styleable.View_transitionName:
4089                    setTransitionName(a.getString(attr));
4090                    break;
4091                case R.styleable.View_nestedScrollingEnabled:
4092                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4093                    break;
4094                case R.styleable.View_stateListAnimator:
4095                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4096                            a.getResourceId(attr, 0)));
4097                    break;
4098                case R.styleable.View_backgroundTint:
4099                    // This will get applied later during setBackground().
4100                    if (mBackgroundTint == null) {
4101                        mBackgroundTint = new TintInfo();
4102                    }
4103                    mBackgroundTint.mTintList = a.getColorStateList(
4104                            R.styleable.View_backgroundTint);
4105                    mBackgroundTint.mHasTintList = true;
4106                    break;
4107                case R.styleable.View_backgroundTintMode:
4108                    // This will get applied later during setBackground().
4109                    if (mBackgroundTint == null) {
4110                        mBackgroundTint = new TintInfo();
4111                    }
4112                    mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt(
4113                            R.styleable.View_backgroundTintMode, -1), null);
4114                    mBackgroundTint.mHasTintMode = true;
4115                    break;
4116                case R.styleable.View_outlineProvider:
4117                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4118                            PROVIDER_BACKGROUND));
4119                    break;
4120                case R.styleable.View_foreground:
4121                    setForeground(a.getDrawable(attr));
4122                    break;
4123                case R.styleable.View_foregroundGravity:
4124                    setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY));
4125                    break;
4126                case R.styleable.View_foregroundTintMode:
4127                    setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null));
4128                    break;
4129                case R.styleable.View_foregroundTint:
4130                    setForegroundTintList(a.getColorStateList(attr));
4131                    break;
4132                case R.styleable.View_foregroundInsidePadding:
4133                    if (mForegroundInfo == null) {
4134                        mForegroundInfo = new ForegroundInfo();
4135                    }
4136                    mForegroundInfo.mInsidePadding = a.getBoolean(attr,
4137                            mForegroundInfo.mInsidePadding);
4138                    break;
4139            }
4140        }
4141
4142        setOverScrollMode(overScrollMode);
4143
4144        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4145        // the resolved layout direction). Those cached values will be used later during padding
4146        // resolution.
4147        mUserPaddingStart = startPadding;
4148        mUserPaddingEnd = endPadding;
4149
4150        if (background != null) {
4151            setBackground(background);
4152        }
4153
4154        // setBackground above will record that padding is currently provided by the background.
4155        // If we have padding specified via xml, record that here instead and use it.
4156        mLeftPaddingDefined = leftPaddingDefined;
4157        mRightPaddingDefined = rightPaddingDefined;
4158
4159        if (padding >= 0) {
4160            leftPadding = padding;
4161            topPadding = padding;
4162            rightPadding = padding;
4163            bottomPadding = padding;
4164            mUserPaddingLeftInitial = padding;
4165            mUserPaddingRightInitial = padding;
4166        }
4167
4168        if (isRtlCompatibilityMode()) {
4169            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4170            // left / right padding are used if defined (meaning here nothing to do). If they are not
4171            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4172            // start / end and resolve them as left / right (layout direction is not taken into account).
4173            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4174            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4175            // defined.
4176            if (!mLeftPaddingDefined && startPaddingDefined) {
4177                leftPadding = startPadding;
4178            }
4179            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4180            if (!mRightPaddingDefined && endPaddingDefined) {
4181                rightPadding = endPadding;
4182            }
4183            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4184        } else {
4185            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4186            // values defined. Otherwise, left /right values are used.
4187            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4188            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4189            // defined.
4190            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4191
4192            if (mLeftPaddingDefined && !hasRelativePadding) {
4193                mUserPaddingLeftInitial = leftPadding;
4194            }
4195            if (mRightPaddingDefined && !hasRelativePadding) {
4196                mUserPaddingRightInitial = rightPadding;
4197            }
4198        }
4199
4200        internalSetPadding(
4201                mUserPaddingLeftInitial,
4202                topPadding >= 0 ? topPadding : mPaddingTop,
4203                mUserPaddingRightInitial,
4204                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4205
4206        if (viewFlagMasks != 0) {
4207            setFlags(viewFlagValues, viewFlagMasks);
4208        }
4209
4210        if (initializeScrollbars) {
4211            initializeScrollbarsInternal(a);
4212        }
4213
4214        a.recycle();
4215
4216        // Needs to be called after mViewFlags is set
4217        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4218            recomputePadding();
4219        }
4220
4221        if (x != 0 || y != 0) {
4222            scrollTo(x, y);
4223        }
4224
4225        if (transformSet) {
4226            setTranslationX(tx);
4227            setTranslationY(ty);
4228            setTranslationZ(tz);
4229            setElevation(elevation);
4230            setRotation(rotation);
4231            setRotationX(rotationX);
4232            setRotationY(rotationY);
4233            setScaleX(sx);
4234            setScaleY(sy);
4235        }
4236
4237        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4238            setScrollContainer(true);
4239        }
4240
4241        computeOpaqueFlags();
4242    }
4243
4244    /**
4245     * An implementation of OnClickListener that attempts to lazily load a
4246     * named click handling method from a parent or ancestor context.
4247     */
4248    private static class DeclaredOnClickListener implements OnClickListener {
4249        private final View mHostView;
4250        private final String mMethodName;
4251
4252        private Method mMethod;
4253
4254        public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
4255            mHostView = hostView;
4256            mMethodName = methodName;
4257        }
4258
4259        @Override
4260        public void onClick(@NonNull View v) {
4261            if (mMethod == null) {
4262                mMethod = resolveMethod(mHostView.getContext(), mMethodName);
4263            }
4264
4265            try {
4266                mMethod.invoke(mHostView.getContext(), v);
4267            } catch (IllegalAccessException e) {
4268                throw new IllegalStateException(
4269                        "Could not execute non-public method for android:onClick", e);
4270            } catch (InvocationTargetException e) {
4271                throw new IllegalStateException(
4272                        "Could not execute method for android:onClick", e);
4273            }
4274        }
4275
4276        @NonNull
4277        private Method resolveMethod(@Nullable Context context, @NonNull String name) {
4278            while (context != null) {
4279                try {
4280                    if (!context.isRestricted()) {
4281                        return context.getClass().getMethod(mMethodName, View.class);
4282                    }
4283                } catch (NoSuchMethodException e) {
4284                    // Failed to find method, keep searching up the hierarchy.
4285                }
4286
4287                if (context instanceof ContextWrapper) {
4288                    context = ((ContextWrapper) context).getBaseContext();
4289                } else {
4290                    // Can't search up the hierarchy, null out and fail.
4291                    context = null;
4292                }
4293            }
4294
4295            final int id = mHostView.getId();
4296            final String idText = id == NO_ID ? "" : " with id '"
4297                    + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
4298            throw new IllegalStateException("Could not find method " + mMethodName
4299                    + "(View) in a parent or ancestor Context for android:onClick "
4300                    + "attribute defined on view " + mHostView.getClass() + idText);
4301        }
4302    }
4303
4304    /**
4305     * Non-public constructor for use in testing
4306     */
4307    View() {
4308        mResources = null;
4309        mRenderNode = RenderNode.create(getClass().getName(), this);
4310    }
4311
4312    private static SparseArray<String> getAttributeMap() {
4313        if (mAttributeMap == null) {
4314            mAttributeMap = new SparseArray<String>();
4315        }
4316        return mAttributeMap;
4317    }
4318
4319    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4320        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4321        mAttributes = new String[length];
4322
4323        int i = 0;
4324        if (attrs != null) {
4325            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4326                mAttributes[i] = attrs.getAttributeName(i);
4327                mAttributes[i + 1] = attrs.getAttributeValue(i);
4328            }
4329
4330        }
4331
4332        SparseArray<String> attributeMap = getAttributeMap();
4333        for (int j = 0; j < a.length(); ++j) {
4334            if (a.hasValue(j)) {
4335                try {
4336                    int resourceId = a.getResourceId(j, 0);
4337                    if (resourceId == 0) {
4338                        continue;
4339                    }
4340
4341                    String resourceName = attributeMap.get(resourceId);
4342                    if (resourceName == null) {
4343                        resourceName = a.getResources().getResourceName(resourceId);
4344                        attributeMap.put(resourceId, resourceName);
4345                    }
4346
4347                    mAttributes[i] = resourceName;
4348                    mAttributes[i + 1] = a.getText(j).toString();
4349                    i += 2;
4350                } catch (Resources.NotFoundException e) {
4351                    // if we can't get the resource name, we just ignore it
4352                }
4353            }
4354        }
4355    }
4356
4357    public String toString() {
4358        StringBuilder out = new StringBuilder(128);
4359        out.append(getClass().getName());
4360        out.append('{');
4361        out.append(Integer.toHexString(System.identityHashCode(this)));
4362        out.append(' ');
4363        switch (mViewFlags&VISIBILITY_MASK) {
4364            case VISIBLE: out.append('V'); break;
4365            case INVISIBLE: out.append('I'); break;
4366            case GONE: out.append('G'); break;
4367            default: out.append('.'); break;
4368        }
4369        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4370        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4371        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4372        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4373        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4374        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4375        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4376        out.append((mViewFlags & STYLUS_BUTTON_PRESSABLE) != 0 ? 'S' : '.');
4377        out.append(' ');
4378        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4379        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4380        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4381        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4382            out.append('p');
4383        } else {
4384            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4385        }
4386        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4387        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4388        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4389        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4390        out.append(' ');
4391        out.append(mLeft);
4392        out.append(',');
4393        out.append(mTop);
4394        out.append('-');
4395        out.append(mRight);
4396        out.append(',');
4397        out.append(mBottom);
4398        final int id = getId();
4399        if (id != NO_ID) {
4400            out.append(" #");
4401            out.append(Integer.toHexString(id));
4402            final Resources r = mResources;
4403            if (Resources.resourceHasPackage(id) && r != null) {
4404                try {
4405                    String pkgname;
4406                    switch (id&0xff000000) {
4407                        case 0x7f000000:
4408                            pkgname="app";
4409                            break;
4410                        case 0x01000000:
4411                            pkgname="android";
4412                            break;
4413                        default:
4414                            pkgname = r.getResourcePackageName(id);
4415                            break;
4416                    }
4417                    String typename = r.getResourceTypeName(id);
4418                    String entryname = r.getResourceEntryName(id);
4419                    out.append(" ");
4420                    out.append(pkgname);
4421                    out.append(":");
4422                    out.append(typename);
4423                    out.append("/");
4424                    out.append(entryname);
4425                } catch (Resources.NotFoundException e) {
4426                }
4427            }
4428        }
4429        out.append("}");
4430        return out.toString();
4431    }
4432
4433    /**
4434     * <p>
4435     * Initializes the fading edges from a given set of styled attributes. This
4436     * method should be called by subclasses that need fading edges and when an
4437     * instance of these subclasses is created programmatically rather than
4438     * being inflated from XML. This method is automatically called when the XML
4439     * is inflated.
4440     * </p>
4441     *
4442     * @param a the styled attributes set to initialize the fading edges from
4443     *
4444     * @removed
4445     */
4446    protected void initializeFadingEdge(TypedArray a) {
4447        // This method probably shouldn't have been included in the SDK to begin with.
4448        // It relies on 'a' having been initialized using an attribute filter array that is
4449        // not publicly available to the SDK. The old method has been renamed
4450        // to initializeFadingEdgeInternal and hidden for framework use only;
4451        // this one initializes using defaults to make it safe to call for apps.
4452
4453        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4454
4455        initializeFadingEdgeInternal(arr);
4456
4457        arr.recycle();
4458    }
4459
4460    /**
4461     * <p>
4462     * Initializes the fading edges from a given set of styled attributes. This
4463     * method should be called by subclasses that need fading edges and when an
4464     * instance of these subclasses is created programmatically rather than
4465     * being inflated from XML. This method is automatically called when the XML
4466     * is inflated.
4467     * </p>
4468     *
4469     * @param a the styled attributes set to initialize the fading edges from
4470     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4471     */
4472    protected void initializeFadingEdgeInternal(TypedArray a) {
4473        initScrollCache();
4474
4475        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4476                R.styleable.View_fadingEdgeLength,
4477                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4478    }
4479
4480    /**
4481     * Returns the size of the vertical faded edges used to indicate that more
4482     * content in this view is visible.
4483     *
4484     * @return The size in pixels of the vertical faded edge or 0 if vertical
4485     *         faded edges are not enabled for this view.
4486     * @attr ref android.R.styleable#View_fadingEdgeLength
4487     */
4488    public int getVerticalFadingEdgeLength() {
4489        if (isVerticalFadingEdgeEnabled()) {
4490            ScrollabilityCache cache = mScrollCache;
4491            if (cache != null) {
4492                return cache.fadingEdgeLength;
4493            }
4494        }
4495        return 0;
4496    }
4497
4498    /**
4499     * Set the size of the faded edge used to indicate that more content in this
4500     * view is available.  Will not change whether the fading edge is enabled; use
4501     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4502     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4503     * for the vertical or horizontal fading edges.
4504     *
4505     * @param length The size in pixels of the faded edge used to indicate that more
4506     *        content in this view is visible.
4507     */
4508    public void setFadingEdgeLength(int length) {
4509        initScrollCache();
4510        mScrollCache.fadingEdgeLength = length;
4511    }
4512
4513    /**
4514     * Returns the size of the horizontal faded edges used to indicate that more
4515     * content in this view is visible.
4516     *
4517     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4518     *         faded edges are not enabled for this view.
4519     * @attr ref android.R.styleable#View_fadingEdgeLength
4520     */
4521    public int getHorizontalFadingEdgeLength() {
4522        if (isHorizontalFadingEdgeEnabled()) {
4523            ScrollabilityCache cache = mScrollCache;
4524            if (cache != null) {
4525                return cache.fadingEdgeLength;
4526            }
4527        }
4528        return 0;
4529    }
4530
4531    /**
4532     * Returns the width of the vertical scrollbar.
4533     *
4534     * @return The width in pixels of the vertical scrollbar or 0 if there
4535     *         is no vertical scrollbar.
4536     */
4537    public int getVerticalScrollbarWidth() {
4538        ScrollabilityCache cache = mScrollCache;
4539        if (cache != null) {
4540            ScrollBarDrawable scrollBar = cache.scrollBar;
4541            if (scrollBar != null) {
4542                int size = scrollBar.getSize(true);
4543                if (size <= 0) {
4544                    size = cache.scrollBarSize;
4545                }
4546                return size;
4547            }
4548            return 0;
4549        }
4550        return 0;
4551    }
4552
4553    /**
4554     * Returns the height of the horizontal scrollbar.
4555     *
4556     * @return The height in pixels of the horizontal scrollbar or 0 if
4557     *         there is no horizontal scrollbar.
4558     */
4559    protected int getHorizontalScrollbarHeight() {
4560        ScrollabilityCache cache = mScrollCache;
4561        if (cache != null) {
4562            ScrollBarDrawable scrollBar = cache.scrollBar;
4563            if (scrollBar != null) {
4564                int size = scrollBar.getSize(false);
4565                if (size <= 0) {
4566                    size = cache.scrollBarSize;
4567                }
4568                return size;
4569            }
4570            return 0;
4571        }
4572        return 0;
4573    }
4574
4575    /**
4576     * <p>
4577     * Initializes the scrollbars from a given set of styled attributes. This
4578     * method should be called by subclasses that need scrollbars and when an
4579     * instance of these subclasses is created programmatically rather than
4580     * being inflated from XML. This method is automatically called when the XML
4581     * is inflated.
4582     * </p>
4583     *
4584     * @param a the styled attributes set to initialize the scrollbars from
4585     *
4586     * @removed
4587     */
4588    protected void initializeScrollbars(TypedArray a) {
4589        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4590        // using the View filter array which is not available to the SDK. As such, internal
4591        // framework usage now uses initializeScrollbarsInternal and we grab a default
4592        // TypedArray with the right filter instead here.
4593        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4594
4595        initializeScrollbarsInternal(arr);
4596
4597        // We ignored the method parameter. Recycle the one we actually did use.
4598        arr.recycle();
4599    }
4600
4601    /**
4602     * <p>
4603     * Initializes the scrollbars from a given set of styled attributes. This
4604     * method should be called by subclasses that need scrollbars and when an
4605     * instance of these subclasses is created programmatically rather than
4606     * being inflated from XML. This method is automatically called when the XML
4607     * is inflated.
4608     * </p>
4609     *
4610     * @param a the styled attributes set to initialize the scrollbars from
4611     * @hide
4612     */
4613    protected void initializeScrollbarsInternal(TypedArray a) {
4614        initScrollCache();
4615
4616        final ScrollabilityCache scrollabilityCache = mScrollCache;
4617
4618        if (scrollabilityCache.scrollBar == null) {
4619            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4620            scrollabilityCache.scrollBar.setCallback(this);
4621            scrollabilityCache.scrollBar.setState(getDrawableState());
4622        }
4623
4624        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4625
4626        if (!fadeScrollbars) {
4627            scrollabilityCache.state = ScrollabilityCache.ON;
4628        }
4629        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4630
4631
4632        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4633                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4634                        .getScrollBarFadeDuration());
4635        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4636                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4637                ViewConfiguration.getScrollDefaultDelay());
4638
4639
4640        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4641                com.android.internal.R.styleable.View_scrollbarSize,
4642                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4643
4644        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4645        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4646
4647        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4648        if (thumb != null) {
4649            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4650        }
4651
4652        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4653                false);
4654        if (alwaysDraw) {
4655            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4656        }
4657
4658        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4659        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4660
4661        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4662        if (thumb != null) {
4663            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4664        }
4665
4666        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4667                false);
4668        if (alwaysDraw) {
4669            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4670        }
4671
4672        // Apply layout direction to the new Drawables if needed
4673        final int layoutDirection = getLayoutDirection();
4674        if (track != null) {
4675            track.setLayoutDirection(layoutDirection);
4676        }
4677        if (thumb != null) {
4678            thumb.setLayoutDirection(layoutDirection);
4679        }
4680
4681        // Re-apply user/background padding so that scrollbar(s) get added
4682        resolvePadding();
4683    }
4684
4685    /**
4686     * <p>
4687     * Initalizes the scrollability cache if necessary.
4688     * </p>
4689     */
4690    private void initScrollCache() {
4691        if (mScrollCache == null) {
4692            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4693        }
4694    }
4695
4696    private ScrollabilityCache getScrollCache() {
4697        initScrollCache();
4698        return mScrollCache;
4699    }
4700
4701    /**
4702     * Set the position of the vertical scroll bar. Should be one of
4703     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4704     * {@link #SCROLLBAR_POSITION_RIGHT}.
4705     *
4706     * @param position Where the vertical scroll bar should be positioned.
4707     */
4708    public void setVerticalScrollbarPosition(int position) {
4709        if (mVerticalScrollbarPosition != position) {
4710            mVerticalScrollbarPosition = position;
4711            computeOpaqueFlags();
4712            resolvePadding();
4713        }
4714    }
4715
4716    /**
4717     * @return The position where the vertical scroll bar will show, if applicable.
4718     * @see #setVerticalScrollbarPosition(int)
4719     */
4720    public int getVerticalScrollbarPosition() {
4721        return mVerticalScrollbarPosition;
4722    }
4723
4724    ListenerInfo getListenerInfo() {
4725        if (mListenerInfo != null) {
4726            return mListenerInfo;
4727        }
4728        mListenerInfo = new ListenerInfo();
4729        return mListenerInfo;
4730    }
4731
4732    /**
4733     * Register a callback to be invoked when the scroll X or Y positions of
4734     * this view change.
4735     * <p>
4736     * <b>Note:</b> Some views handle scrolling independently from View and may
4737     * have their own separate listeners for scroll-type events. For example,
4738     * {@link android.widget.ListView ListView} allows clients to register an
4739     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
4740     * to listen for changes in list scroll position.
4741     *
4742     * @param l The listener to notify when the scroll X or Y position changes.
4743     * @see android.view.View#getScrollX()
4744     * @see android.view.View#getScrollY()
4745     */
4746    public void setOnScrollChangeListener(OnScrollChangeListener l) {
4747        getListenerInfo().mOnScrollChangeListener = l;
4748    }
4749
4750    /**
4751     * Register a callback to be invoked when focus of this view changed.
4752     *
4753     * @param l The callback that will run.
4754     */
4755    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4756        getListenerInfo().mOnFocusChangeListener = l;
4757    }
4758
4759    /**
4760     * Add a listener that will be called when the bounds of the view change due to
4761     * layout processing.
4762     *
4763     * @param listener The listener that will be called when layout bounds change.
4764     */
4765    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4766        ListenerInfo li = getListenerInfo();
4767        if (li.mOnLayoutChangeListeners == null) {
4768            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4769        }
4770        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4771            li.mOnLayoutChangeListeners.add(listener);
4772        }
4773    }
4774
4775    /**
4776     * Remove a listener for layout changes.
4777     *
4778     * @param listener The listener for layout bounds change.
4779     */
4780    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4781        ListenerInfo li = mListenerInfo;
4782        if (li == null || li.mOnLayoutChangeListeners == null) {
4783            return;
4784        }
4785        li.mOnLayoutChangeListeners.remove(listener);
4786    }
4787
4788    /**
4789     * Add a listener for attach state changes.
4790     *
4791     * This listener will be called whenever this view is attached or detached
4792     * from a window. Remove the listener using
4793     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4794     *
4795     * @param listener Listener to attach
4796     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4797     */
4798    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4799        ListenerInfo li = getListenerInfo();
4800        if (li.mOnAttachStateChangeListeners == null) {
4801            li.mOnAttachStateChangeListeners
4802                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4803        }
4804        li.mOnAttachStateChangeListeners.add(listener);
4805    }
4806
4807    /**
4808     * Remove a listener for attach state changes. The listener will receive no further
4809     * notification of window attach/detach events.
4810     *
4811     * @param listener Listener to remove
4812     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4813     */
4814    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4815        ListenerInfo li = mListenerInfo;
4816        if (li == null || li.mOnAttachStateChangeListeners == null) {
4817            return;
4818        }
4819        li.mOnAttachStateChangeListeners.remove(listener);
4820    }
4821
4822    /**
4823     * Returns the focus-change callback registered for this view.
4824     *
4825     * @return The callback, or null if one is not registered.
4826     */
4827    public OnFocusChangeListener getOnFocusChangeListener() {
4828        ListenerInfo li = mListenerInfo;
4829        return li != null ? li.mOnFocusChangeListener : null;
4830    }
4831
4832    /**
4833     * Register a callback to be invoked when this view is clicked. If this view is not
4834     * clickable, it becomes clickable.
4835     *
4836     * @param l The callback that will run
4837     *
4838     * @see #setClickable(boolean)
4839     */
4840    public void setOnClickListener(@Nullable OnClickListener l) {
4841        if (!isClickable()) {
4842            setClickable(true);
4843        }
4844        getListenerInfo().mOnClickListener = l;
4845    }
4846
4847    /**
4848     * Return whether this view has an attached OnClickListener.  Returns
4849     * true if there is a listener, false if there is none.
4850     */
4851    public boolean hasOnClickListeners() {
4852        ListenerInfo li = mListenerInfo;
4853        return (li != null && li.mOnClickListener != null);
4854    }
4855
4856    /**
4857     * Register a callback to be invoked when this view is clicked and held. If this view is not
4858     * long clickable, it becomes long clickable.
4859     *
4860     * @param l The callback that will run
4861     *
4862     * @see #setLongClickable(boolean)
4863     */
4864    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
4865        if (!isLongClickable()) {
4866            setLongClickable(true);
4867        }
4868        getListenerInfo().mOnLongClickListener = l;
4869    }
4870
4871    /**
4872     * Register a callback to be invoked when this view is touched with a stylus and the button is
4873     * pressed.
4874     *
4875     * @param l The callback that will run
4876     * @see #setStylusButtonPressable(boolean)
4877     */
4878    public void setOnStylusButtonPressListener(@Nullable OnStylusButtonPressListener l) {
4879        if (!isStylusButtonPressable()) {
4880            setStylusButtonPressable(true);
4881        }
4882        getListenerInfo().mOnStylusButtonPressListener = l;
4883    }
4884
4885    /**
4886     * Register a callback to be invoked when the context menu for this view is
4887     * being built. If this view is not long clickable, it becomes long clickable.
4888     *
4889     * @param l The callback that will run
4890     *
4891     */
4892    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4893        if (!isLongClickable()) {
4894            setLongClickable(true);
4895        }
4896        getListenerInfo().mOnCreateContextMenuListener = l;
4897    }
4898
4899    /**
4900     * Call this view's OnClickListener, if it is defined.  Performs all normal
4901     * actions associated with clicking: reporting accessibility event, playing
4902     * a sound, etc.
4903     *
4904     * @return True there was an assigned OnClickListener that was called, false
4905     *         otherwise is returned.
4906     */
4907    public boolean performClick() {
4908        final boolean result;
4909        final ListenerInfo li = mListenerInfo;
4910        if (li != null && li.mOnClickListener != null) {
4911            playSoundEffect(SoundEffectConstants.CLICK);
4912            li.mOnClickListener.onClick(this);
4913            result = true;
4914        } else {
4915            result = false;
4916        }
4917
4918        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4919        return result;
4920    }
4921
4922    /**
4923     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4924     * this only calls the listener, and does not do any associated clicking
4925     * actions like reporting an accessibility event.
4926     *
4927     * @return True there was an assigned OnClickListener that was called, false
4928     *         otherwise is returned.
4929     */
4930    public boolean callOnClick() {
4931        ListenerInfo li = mListenerInfo;
4932        if (li != null && li.mOnClickListener != null) {
4933            li.mOnClickListener.onClick(this);
4934            return true;
4935        }
4936        return false;
4937    }
4938
4939    /**
4940     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4941     * OnLongClickListener did not consume the event.
4942     *
4943     * @return True if one of the above receivers consumed the event, false otherwise.
4944     */
4945    public boolean performLongClick() {
4946        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4947
4948        boolean handled = false;
4949        ListenerInfo li = mListenerInfo;
4950        if (li != null && li.mOnLongClickListener != null) {
4951            handled = li.mOnLongClickListener.onLongClick(View.this);
4952        }
4953        if (!handled) {
4954            handled = showContextMenu();
4955        }
4956        if (handled) {
4957            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4958        }
4959        return handled;
4960    }
4961
4962    /**
4963     * Call this view's OnStylusButtonPressListener, if it is defined.
4964     *
4965     * @return True if there was an assigned OnStylusButtonPressListener that consumed the event,
4966     *         false otherwise.
4967     */
4968    public boolean performStylusButtonPress() {
4969        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_STYLUS_BUTTON_PRESSED);
4970
4971        boolean handled = false;
4972        ListenerInfo li = mListenerInfo;
4973        if (li != null && li.mOnStylusButtonPressListener != null) {
4974            handled = li.mOnStylusButtonPressListener.onStylusButtonPress(View.this);
4975        }
4976        if (handled) {
4977            performHapticFeedback(HapticFeedbackConstants.STYLUS_BUTTON_PRESS);
4978        }
4979        return handled;
4980    }
4981
4982    /**
4983     * Checks for a stylus button press and calls the listener.
4984     *
4985     * @param event The event.
4986     * @return True if the event was consumed.
4987     */
4988    private boolean performStylusActionOnButtonPress(MotionEvent event) {
4989        if (isStylusButtonPressable() && !mInStylusButtonPress
4990                && !mHasPerformedLongPress && event.isStylusButtonPressed()) {
4991            if (performStylusButtonPress()) {
4992                mInStylusButtonPress = true;
4993                setPressed(true, event.getX(), event.getY());
4994                removeTapCallback();
4995                removeLongPressCallback();
4996                return true;
4997            }
4998        }
4999        return false;
5000    }
5001
5002    /**
5003     * Performs button-related actions during a touch down event.
5004     *
5005     * @param event The event.
5006     * @return True if the down was consumed.
5007     *
5008     * @hide
5009     */
5010    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
5011        if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE &&
5012            (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
5013            showContextMenu(event.getX(), event.getY(), event.getMetaState());
5014            mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
5015            return true;
5016        }
5017        return false;
5018    }
5019
5020    /**
5021     * Bring up the context menu for this view.
5022     *
5023     * @return Whether a context menu was displayed.
5024     */
5025    public boolean showContextMenu() {
5026        return getParent().showContextMenuForChild(this);
5027    }
5028
5029    /**
5030     * Bring up the context menu for this view, referring to the item under the specified point.
5031     *
5032     * @param x The referenced x coordinate.
5033     * @param y The referenced y coordinate.
5034     * @param metaState The keyboard modifiers that were pressed.
5035     * @return Whether a context menu was displayed.
5036     *
5037     * @hide
5038     */
5039    public boolean showContextMenu(float x, float y, int metaState) {
5040        return showContextMenu();
5041    }
5042
5043    /**
5044     * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}.
5045     *
5046     * @param callback Callback that will control the lifecycle of the action mode
5047     * @return The new action mode if it is started, null otherwise
5048     *
5049     * @see ActionMode
5050     * @see #startActionMode(android.view.ActionMode.Callback, int)
5051     */
5052    public ActionMode startActionMode(ActionMode.Callback callback) {
5053        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
5054    }
5055
5056    /**
5057     * Start an action mode with the given type.
5058     *
5059     * @param callback Callback that will control the lifecycle of the action mode
5060     * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}.
5061     * @return The new action mode if it is started, null otherwise
5062     *
5063     * @see ActionMode
5064     */
5065    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
5066        ViewParent parent = getParent();
5067        if (parent == null) return null;
5068        try {
5069            return parent.startActionModeForChild(this, callback, type);
5070        } catch (AbstractMethodError ame) {
5071            // Older implementations of custom views might not implement this.
5072            return parent.startActionModeForChild(this, callback);
5073        }
5074    }
5075
5076    /**
5077     * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's
5078     * Context, creating a unique View identifier to retrieve the result.
5079     *
5080     * @param intent The Intent to be started.
5081     * @param requestCode The request code to use.
5082     * @hide
5083     */
5084    public void startActivityForResult(Intent intent, int requestCode) {
5085        mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this);
5086        getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null);
5087    }
5088
5089    /**
5090     * If this View corresponds to the calling who, dispatches the activity result.
5091     * @param who The identifier for the targeted View to receive the result.
5092     * @param requestCode The integer request code originally supplied to
5093     *                    startActivityForResult(), allowing you to identify who this
5094     *                    result came from.
5095     * @param resultCode The integer result code returned by the child activity
5096     *                   through its setResult().
5097     * @param data An Intent, which can return result data to the caller
5098     *               (various data can be attached to Intent "extras").
5099     * @return {@code true} if the activity result was dispatched.
5100     * @hide
5101     */
5102    public boolean dispatchActivityResult(
5103            String who, int requestCode, int resultCode, Intent data) {
5104        if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) {
5105            onActivityResult(requestCode, resultCode, data);
5106            mStartActivityRequestWho = null;
5107            return true;
5108        }
5109        return false;
5110    }
5111
5112    /**
5113     * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}.
5114     *
5115     * @param requestCode The integer request code originally supplied to
5116     *                    startActivityForResult(), allowing you to identify who this
5117     *                    result came from.
5118     * @param resultCode The integer result code returned by the child activity
5119     *                   through its setResult().
5120     * @param data An Intent, which can return result data to the caller
5121     *               (various data can be attached to Intent "extras").
5122     * @hide
5123     */
5124    public void onActivityResult(int requestCode, int resultCode, Intent data) {
5125        // Do nothing.
5126    }
5127
5128    /**
5129     * Register a callback to be invoked when a hardware key is pressed in this view.
5130     * Key presses in software input methods will generally not trigger the methods of
5131     * this listener.
5132     * @param l the key listener to attach to this view
5133     */
5134    public void setOnKeyListener(OnKeyListener l) {
5135        getListenerInfo().mOnKeyListener = l;
5136    }
5137
5138    /**
5139     * Register a callback to be invoked when a touch event is sent to this view.
5140     * @param l the touch listener to attach to this view
5141     */
5142    public void setOnTouchListener(OnTouchListener l) {
5143        getListenerInfo().mOnTouchListener = l;
5144    }
5145
5146    /**
5147     * Register a callback to be invoked when a generic motion event is sent to this view.
5148     * @param l the generic motion listener to attach to this view
5149     */
5150    public void setOnGenericMotionListener(OnGenericMotionListener l) {
5151        getListenerInfo().mOnGenericMotionListener = l;
5152    }
5153
5154    /**
5155     * Register a callback to be invoked when a hover event is sent to this view.
5156     * @param l the hover listener to attach to this view
5157     */
5158    public void setOnHoverListener(OnHoverListener l) {
5159        getListenerInfo().mOnHoverListener = l;
5160    }
5161
5162    /**
5163     * Register a drag event listener callback object for this View. The parameter is
5164     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
5165     * View, the system calls the
5166     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
5167     * @param l An implementation of {@link android.view.View.OnDragListener}.
5168     */
5169    public void setOnDragListener(OnDragListener l) {
5170        getListenerInfo().mOnDragListener = l;
5171    }
5172
5173    /**
5174     * Give this view focus. This will cause
5175     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
5176     *
5177     * Note: this does not check whether this {@link View} should get focus, it just
5178     * gives it focus no matter what.  It should only be called internally by framework
5179     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
5180     *
5181     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
5182     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
5183     *        focus moved when requestFocus() is called. It may not always
5184     *        apply, in which case use the default View.FOCUS_DOWN.
5185     * @param previouslyFocusedRect The rectangle of the view that had focus
5186     *        prior in this View's coordinate system.
5187     */
5188    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
5189        if (DBG) {
5190            System.out.println(this + " requestFocus()");
5191        }
5192
5193        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
5194            mPrivateFlags |= PFLAG_FOCUSED;
5195
5196            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
5197
5198            if (mParent != null) {
5199                mParent.requestChildFocus(this, this);
5200            }
5201
5202            if (mAttachInfo != null) {
5203                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
5204            }
5205
5206            onFocusChanged(true, direction, previouslyFocusedRect);
5207            refreshDrawableState();
5208        }
5209    }
5210
5211    /**
5212     * Populates <code>outRect</code> with the hotspot bounds. By default,
5213     * the hotspot bounds are identical to the screen bounds.
5214     *
5215     * @param outRect rect to populate with hotspot bounds
5216     * @hide Only for internal use by views and widgets.
5217     */
5218    public void getHotspotBounds(Rect outRect) {
5219        final Drawable background = getBackground();
5220        if (background != null) {
5221            background.getHotspotBounds(outRect);
5222        } else {
5223            getBoundsOnScreen(outRect);
5224        }
5225    }
5226
5227    /**
5228     * Request that a rectangle of this view be visible on the screen,
5229     * scrolling if necessary just enough.
5230     *
5231     * <p>A View should call this if it maintains some notion of which part
5232     * of its content is interesting.  For example, a text editing view
5233     * should call this when its cursor moves.
5234     *
5235     * @param rectangle The rectangle.
5236     * @return Whether any parent scrolled.
5237     */
5238    public boolean requestRectangleOnScreen(Rect rectangle) {
5239        return requestRectangleOnScreen(rectangle, false);
5240    }
5241
5242    /**
5243     * Request that a rectangle of this view be visible on the screen,
5244     * scrolling if necessary just enough.
5245     *
5246     * <p>A View should call this if it maintains some notion of which part
5247     * of its content is interesting.  For example, a text editing view
5248     * should call this when its cursor moves.
5249     *
5250     * <p>When <code>immediate</code> is set to true, scrolling will not be
5251     * animated.
5252     *
5253     * @param rectangle The rectangle.
5254     * @param immediate True to forbid animated scrolling, false otherwise
5255     * @return Whether any parent scrolled.
5256     */
5257    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
5258        if (mParent == null) {
5259            return false;
5260        }
5261
5262        View child = this;
5263
5264        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
5265        position.set(rectangle);
5266
5267        ViewParent parent = mParent;
5268        boolean scrolled = false;
5269        while (parent != null) {
5270            rectangle.set((int) position.left, (int) position.top,
5271                    (int) position.right, (int) position.bottom);
5272
5273            scrolled |= parent.requestChildRectangleOnScreen(child,
5274                    rectangle, immediate);
5275
5276            if (!child.hasIdentityMatrix()) {
5277                child.getMatrix().mapRect(position);
5278            }
5279
5280            position.offset(child.mLeft, child.mTop);
5281
5282            if (!(parent instanceof View)) {
5283                break;
5284            }
5285
5286            View parentView = (View) parent;
5287
5288            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5289
5290            child = parentView;
5291            parent = child.getParent();
5292        }
5293
5294        return scrolled;
5295    }
5296
5297    /**
5298     * Called when this view wants to give up focus. If focus is cleared
5299     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5300     * <p>
5301     * <strong>Note:</strong> When a View clears focus the framework is trying
5302     * to give focus to the first focusable View from the top. Hence, if this
5303     * View is the first from the top that can take focus, then all callbacks
5304     * related to clearing focus will be invoked after which the framework will
5305     * give focus to this view.
5306     * </p>
5307     */
5308    public void clearFocus() {
5309        if (DBG) {
5310            System.out.println(this + " clearFocus()");
5311        }
5312
5313        clearFocusInternal(null, true, true);
5314    }
5315
5316    /**
5317     * Clears focus from the view, optionally propagating the change up through
5318     * the parent hierarchy and requesting that the root view place new focus.
5319     *
5320     * @param propagate whether to propagate the change up through the parent
5321     *            hierarchy
5322     * @param refocus when propagate is true, specifies whether to request the
5323     *            root view place new focus
5324     */
5325    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5326        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5327            mPrivateFlags &= ~PFLAG_FOCUSED;
5328
5329            if (propagate && mParent != null) {
5330                mParent.clearChildFocus(this);
5331            }
5332
5333            onFocusChanged(false, 0, null);
5334            refreshDrawableState();
5335
5336            if (propagate && (!refocus || !rootViewRequestFocus())) {
5337                notifyGlobalFocusCleared(this);
5338            }
5339        }
5340    }
5341
5342    void notifyGlobalFocusCleared(View oldFocus) {
5343        if (oldFocus != null && mAttachInfo != null) {
5344            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5345        }
5346    }
5347
5348    boolean rootViewRequestFocus() {
5349        final View root = getRootView();
5350        return root != null && root.requestFocus();
5351    }
5352
5353    /**
5354     * Called internally by the view system when a new view is getting focus.
5355     * This is what clears the old focus.
5356     * <p>
5357     * <b>NOTE:</b> The parent view's focused child must be updated manually
5358     * after calling this method. Otherwise, the view hierarchy may be left in
5359     * an inconstent state.
5360     */
5361    void unFocus(View focused) {
5362        if (DBG) {
5363            System.out.println(this + " unFocus()");
5364        }
5365
5366        clearFocusInternal(focused, false, false);
5367    }
5368
5369    /**
5370     * Returns true if this view has focus itself, or is the ancestor of the
5371     * view that has focus.
5372     *
5373     * @return True if this view has or contains focus, false otherwise.
5374     */
5375    @ViewDebug.ExportedProperty(category = "focus")
5376    public boolean hasFocus() {
5377        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5378    }
5379
5380    /**
5381     * Returns true if this view is focusable or if it contains a reachable View
5382     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5383     * is a View whose parents do not block descendants focus.
5384     *
5385     * Only {@link #VISIBLE} views are considered focusable.
5386     *
5387     * @return True if the view is focusable or if the view contains a focusable
5388     *         View, false otherwise.
5389     *
5390     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5391     * @see ViewGroup#getTouchscreenBlocksFocus()
5392     */
5393    public boolean hasFocusable() {
5394        if (!isFocusableInTouchMode()) {
5395            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5396                final ViewGroup g = (ViewGroup) p;
5397                if (g.shouldBlockFocusForTouchscreen()) {
5398                    return false;
5399                }
5400            }
5401        }
5402        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5403    }
5404
5405    /**
5406     * Called by the view system when the focus state of this view changes.
5407     * When the focus change event is caused by directional navigation, direction
5408     * and previouslyFocusedRect provide insight into where the focus is coming from.
5409     * When overriding, be sure to call up through to the super class so that
5410     * the standard focus handling will occur.
5411     *
5412     * @param gainFocus True if the View has focus; false otherwise.
5413     * @param direction The direction focus has moved when requestFocus()
5414     *                  is called to give this view focus. Values are
5415     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5416     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5417     *                  It may not always apply, in which case use the default.
5418     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5419     *        system, of the previously focused view.  If applicable, this will be
5420     *        passed in as finer grained information about where the focus is coming
5421     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5422     */
5423    @CallSuper
5424    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5425            @Nullable Rect previouslyFocusedRect) {
5426        if (gainFocus) {
5427            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5428        } else {
5429            notifyViewAccessibilityStateChangedIfNeeded(
5430                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5431        }
5432
5433        InputMethodManager imm = InputMethodManager.peekInstance();
5434        if (!gainFocus) {
5435            if (isPressed()) {
5436                setPressed(false);
5437            }
5438            if (imm != null && mAttachInfo != null
5439                    && mAttachInfo.mHasWindowFocus) {
5440                imm.focusOut(this);
5441            }
5442            onFocusLost();
5443        } else if (imm != null && mAttachInfo != null
5444                && mAttachInfo.mHasWindowFocus) {
5445            imm.focusIn(this);
5446        }
5447
5448        invalidate(true);
5449        ListenerInfo li = mListenerInfo;
5450        if (li != null && li.mOnFocusChangeListener != null) {
5451            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5452        }
5453
5454        if (mAttachInfo != null) {
5455            mAttachInfo.mKeyDispatchState.reset(this);
5456        }
5457    }
5458
5459    /**
5460     * Sends an accessibility event of the given type. If accessibility is
5461     * not enabled this method has no effect. The default implementation calls
5462     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5463     * to populate information about the event source (this View), then calls
5464     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5465     * populate the text content of the event source including its descendants,
5466     * and last calls
5467     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5468     * on its parent to request sending of the event to interested parties.
5469     * <p>
5470     * If an {@link AccessibilityDelegate} has been specified via calling
5471     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5472     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5473     * responsible for handling this call.
5474     * </p>
5475     *
5476     * @param eventType The type of the event to send, as defined by several types from
5477     * {@link android.view.accessibility.AccessibilityEvent}, such as
5478     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5479     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5480     *
5481     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5482     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5483     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5484     * @see AccessibilityDelegate
5485     */
5486    public void sendAccessibilityEvent(int eventType) {
5487        if (mAccessibilityDelegate != null) {
5488            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5489        } else {
5490            sendAccessibilityEventInternal(eventType);
5491        }
5492    }
5493
5494    /**
5495     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5496     * {@link AccessibilityEvent} to make an announcement which is related to some
5497     * sort of a context change for which none of the events representing UI transitions
5498     * is a good fit. For example, announcing a new page in a book. If accessibility
5499     * is not enabled this method does nothing.
5500     *
5501     * @param text The announcement text.
5502     */
5503    public void announceForAccessibility(CharSequence text) {
5504        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5505            AccessibilityEvent event = AccessibilityEvent.obtain(
5506                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5507            onInitializeAccessibilityEvent(event);
5508            event.getText().add(text);
5509            event.setContentDescription(null);
5510            mParent.requestSendAccessibilityEvent(this, event);
5511        }
5512    }
5513
5514    /**
5515     * @see #sendAccessibilityEvent(int)
5516     *
5517     * Note: Called from the default {@link AccessibilityDelegate}.
5518     *
5519     * @hide
5520     */
5521    public void sendAccessibilityEventInternal(int eventType) {
5522        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5523            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5524        }
5525    }
5526
5527    /**
5528     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5529     * takes as an argument an empty {@link AccessibilityEvent} and does not
5530     * perform a check whether accessibility is enabled.
5531     * <p>
5532     * If an {@link AccessibilityDelegate} has been specified via calling
5533     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5534     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5535     * is responsible for handling this call.
5536     * </p>
5537     *
5538     * @param event The event to send.
5539     *
5540     * @see #sendAccessibilityEvent(int)
5541     */
5542    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5543        if (mAccessibilityDelegate != null) {
5544            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5545        } else {
5546            sendAccessibilityEventUncheckedInternal(event);
5547        }
5548    }
5549
5550    /**
5551     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5552     *
5553     * Note: Called from the default {@link AccessibilityDelegate}.
5554     *
5555     * @hide
5556     */
5557    public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5558        if (!isShown()) {
5559            return;
5560        }
5561        onInitializeAccessibilityEvent(event);
5562        // Only a subset of accessibility events populates text content.
5563        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5564            dispatchPopulateAccessibilityEvent(event);
5565        }
5566        // In the beginning we called #isShown(), so we know that getParent() is not null.
5567        getParent().requestSendAccessibilityEvent(this, event);
5568    }
5569
5570    /**
5571     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5572     * to its children for adding their text content to the event. Note that the
5573     * event text is populated in a separate dispatch path since we add to the
5574     * event not only the text of the source but also the text of all its descendants.
5575     * A typical implementation will call
5576     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5577     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5578     * on each child. Override this method if custom population of the event text
5579     * content is required.
5580     * <p>
5581     * If an {@link AccessibilityDelegate} has been specified via calling
5582     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5583     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5584     * is responsible for handling this call.
5585     * </p>
5586     * <p>
5587     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5588     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5589     * </p>
5590     *
5591     * @param event The event.
5592     *
5593     * @return True if the event population was completed.
5594     */
5595    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5596        if (mAccessibilityDelegate != null) {
5597            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5598        } else {
5599            return dispatchPopulateAccessibilityEventInternal(event);
5600        }
5601    }
5602
5603    /**
5604     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5605     *
5606     * Note: Called from the default {@link AccessibilityDelegate}.
5607     *
5608     * @hide
5609     */
5610    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5611        onPopulateAccessibilityEvent(event);
5612        return false;
5613    }
5614
5615    /**
5616     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5617     * giving a chance to this View to populate the accessibility event with its
5618     * text content. While this method is free to modify event
5619     * attributes other than text content, doing so should normally be performed in
5620     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5621     * <p>
5622     * Example: Adding formatted date string to an accessibility event in addition
5623     *          to the text added by the super implementation:
5624     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5625     *     super.onPopulateAccessibilityEvent(event);
5626     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5627     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5628     *         mCurrentDate.getTimeInMillis(), flags);
5629     *     event.getText().add(selectedDateUtterance);
5630     * }</pre>
5631     * <p>
5632     * If an {@link AccessibilityDelegate} has been specified via calling
5633     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5634     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5635     * is responsible for handling this call.
5636     * </p>
5637     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5638     * information to the event, in case the default implementation has basic information to add.
5639     * </p>
5640     *
5641     * @param event The accessibility event which to populate.
5642     *
5643     * @see #sendAccessibilityEvent(int)
5644     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5645     */
5646    @CallSuper
5647    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5648        if (mAccessibilityDelegate != null) {
5649            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5650        } else {
5651            onPopulateAccessibilityEventInternal(event);
5652        }
5653    }
5654
5655    /**
5656     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5657     *
5658     * Note: Called from the default {@link AccessibilityDelegate}.
5659     *
5660     * @hide
5661     */
5662    public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5663    }
5664
5665    /**
5666     * Initializes an {@link AccessibilityEvent} with information about
5667     * this View which is the event source. In other words, the source of
5668     * an accessibility event is the view whose state change triggered firing
5669     * the event.
5670     * <p>
5671     * Example: Setting the password property of an event in addition
5672     *          to properties set by the super implementation:
5673     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5674     *     super.onInitializeAccessibilityEvent(event);
5675     *     event.setPassword(true);
5676     * }</pre>
5677     * <p>
5678     * If an {@link AccessibilityDelegate} has been specified via calling
5679     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5680     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5681     * is responsible for handling this call.
5682     * </p>
5683     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5684     * information to the event, in case the default implementation has basic information to add.
5685     * </p>
5686     * @param event The event to initialize.
5687     *
5688     * @see #sendAccessibilityEvent(int)
5689     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5690     */
5691    @CallSuper
5692    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5693        if (mAccessibilityDelegate != null) {
5694            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5695        } else {
5696            onInitializeAccessibilityEventInternal(event);
5697        }
5698    }
5699
5700    /**
5701     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5702     *
5703     * Note: Called from the default {@link AccessibilityDelegate}.
5704     *
5705     * @hide
5706     */
5707    public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5708        event.setSource(this);
5709        event.setClassName(getAccessibilityClassName());
5710        event.setPackageName(getContext().getPackageName());
5711        event.setEnabled(isEnabled());
5712        event.setContentDescription(mContentDescription);
5713
5714        switch (event.getEventType()) {
5715            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5716                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5717                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5718                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5719                event.setItemCount(focusablesTempList.size());
5720                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5721                if (mAttachInfo != null) {
5722                    focusablesTempList.clear();
5723                }
5724            } break;
5725            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5726                CharSequence text = getIterableTextForAccessibility();
5727                if (text != null && text.length() > 0) {
5728                    event.setFromIndex(getAccessibilitySelectionStart());
5729                    event.setToIndex(getAccessibilitySelectionEnd());
5730                    event.setItemCount(text.length());
5731                }
5732            } break;
5733        }
5734    }
5735
5736    /**
5737     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5738     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5739     * This method is responsible for obtaining an accessibility node info from a
5740     * pool of reusable instances and calling
5741     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5742     * initialize the former.
5743     * <p>
5744     * Note: The client is responsible for recycling the obtained instance by calling
5745     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5746     * </p>
5747     *
5748     * @return A populated {@link AccessibilityNodeInfo}.
5749     *
5750     * @see AccessibilityNodeInfo
5751     */
5752    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5753        if (mAccessibilityDelegate != null) {
5754            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5755        } else {
5756            return createAccessibilityNodeInfoInternal();
5757        }
5758    }
5759
5760    /**
5761     * @see #createAccessibilityNodeInfo()
5762     *
5763     * @hide
5764     */
5765    public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5766        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5767        if (provider != null) {
5768            return provider.createAccessibilityNodeInfo(View.NO_ID);
5769        } else {
5770            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5771            onInitializeAccessibilityNodeInfo(info);
5772            return info;
5773        }
5774    }
5775
5776    /**
5777     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5778     * The base implementation sets:
5779     * <ul>
5780     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5781     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5782     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5783     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5784     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5785     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5786     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5787     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5788     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5789     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5790     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5791     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5792     *   <li>{@link AccessibilityNodeInfo#setStylusButtonPressable(boolean)}</li>
5793     * </ul>
5794     * <p>
5795     * Subclasses should override this method, call the super implementation,
5796     * and set additional attributes.
5797     * </p>
5798     * <p>
5799     * If an {@link AccessibilityDelegate} has been specified via calling
5800     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5801     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5802     * is responsible for handling this call.
5803     * </p>
5804     *
5805     * @param info The instance to initialize.
5806     */
5807    @CallSuper
5808    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5809        if (mAccessibilityDelegate != null) {
5810            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5811        } else {
5812            onInitializeAccessibilityNodeInfoInternal(info);
5813        }
5814    }
5815
5816    /**
5817     * Gets the location of this view in screen coordinates.
5818     *
5819     * @param outRect The output location
5820     * @hide
5821     */
5822    public void getBoundsOnScreen(Rect outRect) {
5823        getBoundsOnScreen(outRect, false);
5824    }
5825
5826    /**
5827     * Gets the location of this view in screen coordinates.
5828     *
5829     * @param outRect The output location
5830     * @param clipToParent Whether to clip child bounds to the parent ones.
5831     * @hide
5832     */
5833    public void getBoundsOnScreen(Rect outRect, boolean clipToParent) {
5834        if (mAttachInfo == null) {
5835            return;
5836        }
5837
5838        RectF position = mAttachInfo.mTmpTransformRect;
5839        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5840
5841        if (!hasIdentityMatrix()) {
5842            getMatrix().mapRect(position);
5843        }
5844
5845        position.offset(mLeft, mTop);
5846
5847        ViewParent parent = mParent;
5848        while (parent instanceof View) {
5849            View parentView = (View) parent;
5850
5851            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5852
5853            if (clipToParent) {
5854                position.left = Math.max(position.left, 0);
5855                position.top = Math.max(position.top, 0);
5856                position.right = Math.min(position.right, parentView.getWidth());
5857                position.bottom = Math.min(position.bottom, parentView.getHeight());
5858            }
5859
5860            if (!parentView.hasIdentityMatrix()) {
5861                parentView.getMatrix().mapRect(position);
5862            }
5863
5864            position.offset(parentView.mLeft, parentView.mTop);
5865
5866            parent = parentView.mParent;
5867        }
5868
5869        if (parent instanceof ViewRootImpl) {
5870            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5871            position.offset(0, -viewRootImpl.mCurScrollY);
5872        }
5873
5874        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5875
5876        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5877                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5878    }
5879
5880    /**
5881     * Return the class name of this object to be used for accessibility purposes.
5882     * Subclasses should only override this if they are implementing something that
5883     * should be seen as a completely new class of view when used by accessibility,
5884     * unrelated to the class it is deriving from.  This is used to fill in
5885     * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}.
5886     */
5887    public CharSequence getAccessibilityClassName() {
5888        return View.class.getName();
5889    }
5890
5891    /**
5892     * Called when assist structure is being retrieved from a view as part of
5893     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
5894     * @param structure Fill in with structured view data.  The default implementation
5895     * fills in all data that can be inferred from the view itself.
5896     */
5897    public void onProvideAssistStructure(ViewAssistStructure structure) {
5898        final int id = mID;
5899        if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0
5900                && (id&0x0000ffff) != 0) {
5901            String pkg, type, entry;
5902            try {
5903                final Resources res = getResources();
5904                entry = res.getResourceEntryName(id);
5905                type = res.getResourceTypeName(id);
5906                pkg = res.getResourcePackageName(id);
5907            } catch (Resources.NotFoundException e) {
5908                entry = type = pkg = null;
5909            }
5910            structure.setId(id, pkg, type, entry);
5911        } else {
5912            structure.setId(id, null, null, null);
5913        }
5914        structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop);
5915        structure.setVisibility(getVisibility());
5916        structure.setEnabled(isEnabled());
5917        if (isClickable()) {
5918            structure.setClickable(true);
5919        }
5920        if (isFocusable()) {
5921            structure.setFocusable(true);
5922        }
5923        if (isFocused()) {
5924            structure.setFocused(true);
5925        }
5926        if (isAccessibilityFocused()) {
5927            structure.setAccessibilityFocused(true);
5928        }
5929        if (isSelected()) {
5930            structure.setSelected(true);
5931        }
5932        if (isActivated()) {
5933            structure.setActivated(true);
5934        }
5935        if (isLongClickable()) {
5936            structure.setLongClickable(true);
5937        }
5938        if (this instanceof Checkable) {
5939            structure.setCheckable(true);
5940            if (((Checkable)this).isChecked()) {
5941                structure.setChecked(true);
5942            }
5943        }
5944        if (isStylusButtonPressable()) {
5945            structure.setStylusButtonPressable(true);
5946        }
5947        structure.setClassName(getAccessibilityClassName().toString());
5948        structure.setContentDescription(getContentDescription());
5949    }
5950
5951    /**
5952     * Called when assist structure is being retrieved from a view as part of
5953     * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to
5954     * generate additional virtual structure under this view.  The defaullt implementation
5955     * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the
5956     * view's virtual accessibility nodes, if any.  You can override this for a more
5957     * optimal implementation providing this data.
5958     */
5959    public void onProvideVirtualAssistStructure(ViewAssistStructure structure) {
5960        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5961        if (provider != null) {
5962            AccessibilityNodeInfo info = createAccessibilityNodeInfo();
5963            Log.i("View", "Provider of " + this + ": children=" + info.getChildCount());
5964            structure.setChildCount(1);
5965            ViewAssistStructure root = structure.newChild(0);
5966            populateVirtualAssistStructure(root, provider, info);
5967            info.recycle();
5968        }
5969    }
5970
5971    private void populateVirtualAssistStructure(ViewAssistStructure structure,
5972            AccessibilityNodeProvider provider, AccessibilityNodeInfo info) {
5973        structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()),
5974                null, null, null);
5975        Rect rect = structure.getTempRect();
5976        info.getBoundsInParent(rect);
5977        structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height());
5978        structure.setVisibility(VISIBLE);
5979        structure.setEnabled(info.isEnabled());
5980        if (info.isClickable()) {
5981            structure.setClickable(true);
5982        }
5983        if (info.isFocusable()) {
5984            structure.setFocusable(true);
5985        }
5986        if (info.isFocused()) {
5987            structure.setFocused(true);
5988        }
5989        if (info.isAccessibilityFocused()) {
5990            structure.setAccessibilityFocused(true);
5991        }
5992        if (info.isSelected()) {
5993            structure.setSelected(true);
5994        }
5995        if (info.isLongClickable()) {
5996            structure.setLongClickable(true);
5997        }
5998        if (info.isCheckable()) {
5999            structure.setCheckable(true);
6000            if (info.isChecked()) {
6001                structure.setChecked(true);
6002            }
6003        }
6004        if (info.isStylusButtonPressable()) {
6005            structure.setStylusButtonPressable(true);
6006        }
6007        CharSequence cname = info.getClassName();
6008        structure.setClassName(cname != null ? cname.toString() : null);
6009        structure.setContentDescription(info.getContentDescription());
6010        Log.i("View", "vassist " + cname + " @ " + rect.toShortString()
6011                + " text=" + info.getText() + " cd=" + info.getContentDescription());
6012        if (info.getText() != null || info.getError() != null) {
6013            structure.setText(info.getText(), info.getTextSelectionStart(),
6014                    info.getTextSelectionEnd());
6015        }
6016        final int NCHILDREN = info.getChildCount();
6017        if (NCHILDREN > 0) {
6018            structure.setChildCount(NCHILDREN);
6019            for (int i=0; i<NCHILDREN; i++) {
6020                AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo(
6021                        AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i)));
6022                ViewAssistStructure child = structure.newChild(i);
6023                populateVirtualAssistStructure(child, provider, cinfo);
6024                cinfo.recycle();
6025            }
6026        }
6027    }
6028
6029    /**
6030     * Dispatch creation of {@link ViewAssistStructure} down the hierarchy.  The default
6031     * implementation calls {@link #onProvideAssistStructure} and
6032     * {@link #onProvideVirtualAssistStructure}.
6033     */
6034    public void dispatchProvideAssistStructure(ViewAssistStructure structure) {
6035        if (!isAssistBlocked()) {
6036            onProvideAssistStructure(structure);
6037            onProvideVirtualAssistStructure(structure);
6038        } else {
6039            structure.setClassName(getAccessibilityClassName().toString());
6040            structure.setAssistBlocked(true);
6041        }
6042    }
6043
6044    /**
6045     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
6046     *
6047     * Note: Called from the default {@link AccessibilityDelegate}.
6048     *
6049     * @hide
6050     */
6051    public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
6052        Rect bounds = mAttachInfo.mTmpInvalRect;
6053
6054        getDrawingRect(bounds);
6055        info.setBoundsInParent(bounds);
6056
6057        getBoundsOnScreen(bounds, true);
6058        info.setBoundsInScreen(bounds);
6059
6060        ViewParent parent = getParentForAccessibility();
6061        if (parent instanceof View) {
6062            info.setParent((View) parent);
6063        }
6064
6065        if (mID != View.NO_ID) {
6066            View rootView = getRootView();
6067            if (rootView == null) {
6068                rootView = this;
6069            }
6070
6071            View label = rootView.findLabelForView(this, mID);
6072            if (label != null) {
6073                info.setLabeledBy(label);
6074            }
6075
6076            if ((mAttachInfo.mAccessibilityFetchFlags
6077                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
6078                    && Resources.resourceHasPackage(mID)) {
6079                try {
6080                    String viewId = getResources().getResourceName(mID);
6081                    info.setViewIdResourceName(viewId);
6082                } catch (Resources.NotFoundException nfe) {
6083                    /* ignore */
6084                }
6085            }
6086        }
6087
6088        if (mLabelForId != View.NO_ID) {
6089            View rootView = getRootView();
6090            if (rootView == null) {
6091                rootView = this;
6092            }
6093            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
6094            if (labeled != null) {
6095                info.setLabelFor(labeled);
6096            }
6097        }
6098
6099        if (mAccessibilityTraversalBeforeId != View.NO_ID) {
6100            View rootView = getRootView();
6101            if (rootView == null) {
6102                rootView = this;
6103            }
6104            View next = rootView.findViewInsideOutShouldExist(this,
6105                    mAccessibilityTraversalBeforeId);
6106            if (next != null) {
6107                info.setTraversalBefore(next);
6108            }
6109        }
6110
6111        if (mAccessibilityTraversalAfterId != View.NO_ID) {
6112            View rootView = getRootView();
6113            if (rootView == null) {
6114                rootView = this;
6115            }
6116            View next = rootView.findViewInsideOutShouldExist(this,
6117                    mAccessibilityTraversalAfterId);
6118            if (next != null) {
6119                info.setTraversalAfter(next);
6120            }
6121        }
6122
6123        info.setVisibleToUser(isVisibleToUser());
6124
6125        info.setPackageName(mContext.getPackageName());
6126        info.setClassName(getAccessibilityClassName());
6127        info.setContentDescription(getContentDescription());
6128
6129        info.setEnabled(isEnabled());
6130        info.setClickable(isClickable());
6131        info.setFocusable(isFocusable());
6132        info.setFocused(isFocused());
6133        info.setAccessibilityFocused(isAccessibilityFocused());
6134        info.setSelected(isSelected());
6135        info.setLongClickable(isLongClickable());
6136        info.setStylusButtonPressable(isStylusButtonPressable());
6137        info.setLiveRegion(getAccessibilityLiveRegion());
6138
6139        // TODO: These make sense only if we are in an AdapterView but all
6140        // views can be selected. Maybe from accessibility perspective
6141        // we should report as selectable view in an AdapterView.
6142        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
6143        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
6144
6145        if (isFocusable()) {
6146            if (isFocused()) {
6147                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
6148            } else {
6149                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
6150            }
6151        }
6152
6153        if (!isAccessibilityFocused()) {
6154            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
6155        } else {
6156            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
6157        }
6158
6159        if (isClickable() && isEnabled()) {
6160            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
6161        }
6162
6163        if (isLongClickable() && isEnabled()) {
6164            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
6165        }
6166
6167        if (isStylusButtonPressable() && isEnabled()) {
6168            info.addAction(AccessibilityAction.ACTION_STYLUS_BUTTON_PRESS);
6169        }
6170
6171        CharSequence text = getIterableTextForAccessibility();
6172        if (text != null && text.length() > 0) {
6173            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
6174
6175            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
6176            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
6177            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
6178            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
6179                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
6180                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
6181        }
6182
6183        info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN);
6184    }
6185
6186    private View findLabelForView(View view, int labeledId) {
6187        if (mMatchLabelForPredicate == null) {
6188            mMatchLabelForPredicate = new MatchLabelForPredicate();
6189        }
6190        mMatchLabelForPredicate.mLabeledId = labeledId;
6191        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
6192    }
6193
6194    /**
6195     * Computes whether this view is visible to the user. Such a view is
6196     * attached, visible, all its predecessors are visible, it is not clipped
6197     * entirely by its predecessors, and has an alpha greater than zero.
6198     *
6199     * @return Whether the view is visible on the screen.
6200     *
6201     * @hide
6202     */
6203    protected boolean isVisibleToUser() {
6204        return isVisibleToUser(null);
6205    }
6206
6207    /**
6208     * Computes whether the given portion of this view is visible to the user.
6209     * Such a view is attached, visible, all its predecessors are visible,
6210     * has an alpha greater than zero, and the specified portion is not
6211     * clipped entirely by its predecessors.
6212     *
6213     * @param boundInView the portion of the view to test; coordinates should be relative; may be
6214     *                    <code>null</code>, and the entire view will be tested in this case.
6215     *                    When <code>true</code> is returned by the function, the actual visible
6216     *                    region will be stored in this parameter; that is, if boundInView is fully
6217     *                    contained within the view, no modification will be made, otherwise regions
6218     *                    outside of the visible area of the view will be clipped.
6219     *
6220     * @return Whether the specified portion of the view is visible on the screen.
6221     *
6222     * @hide
6223     */
6224    protected boolean isVisibleToUser(Rect boundInView) {
6225        if (mAttachInfo != null) {
6226            // Attached to invisible window means this view is not visible.
6227            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
6228                return false;
6229            }
6230            // An invisible predecessor or one with alpha zero means
6231            // that this view is not visible to the user.
6232            Object current = this;
6233            while (current instanceof View) {
6234                View view = (View) current;
6235                // We have attach info so this view is attached and there is no
6236                // need to check whether we reach to ViewRootImpl on the way up.
6237                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
6238                        view.getVisibility() != VISIBLE) {
6239                    return false;
6240                }
6241                current = view.mParent;
6242            }
6243            // Check if the view is entirely covered by its predecessors.
6244            Rect visibleRect = mAttachInfo.mTmpInvalRect;
6245            Point offset = mAttachInfo.mPoint;
6246            if (!getGlobalVisibleRect(visibleRect, offset)) {
6247                return false;
6248            }
6249            // Check if the visible portion intersects the rectangle of interest.
6250            if (boundInView != null) {
6251                visibleRect.offset(-offset.x, -offset.y);
6252                return boundInView.intersect(visibleRect);
6253            }
6254            return true;
6255        }
6256        return false;
6257    }
6258
6259    /**
6260     * Returns the delegate for implementing accessibility support via
6261     * composition. For more details see {@link AccessibilityDelegate}.
6262     *
6263     * @return The delegate, or null if none set.
6264     *
6265     * @hide
6266     */
6267    public AccessibilityDelegate getAccessibilityDelegate() {
6268        return mAccessibilityDelegate;
6269    }
6270
6271    /**
6272     * Sets a delegate for implementing accessibility support via composition as
6273     * opposed to inheritance. The delegate's primary use is for implementing
6274     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
6275     *
6276     * @param delegate The delegate instance.
6277     *
6278     * @see AccessibilityDelegate
6279     */
6280    public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) {
6281        mAccessibilityDelegate = delegate;
6282    }
6283
6284    /**
6285     * Gets the provider for managing a virtual view hierarchy rooted at this View
6286     * and reported to {@link android.accessibilityservice.AccessibilityService}s
6287     * that explore the window content.
6288     * <p>
6289     * If this method returns an instance, this instance is responsible for managing
6290     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
6291     * View including the one representing the View itself. Similarly the returned
6292     * instance is responsible for performing accessibility actions on any virtual
6293     * view or the root view itself.
6294     * </p>
6295     * <p>
6296     * If an {@link AccessibilityDelegate} has been specified via calling
6297     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6298     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
6299     * is responsible for handling this call.
6300     * </p>
6301     *
6302     * @return The provider.
6303     *
6304     * @see AccessibilityNodeProvider
6305     */
6306    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
6307        if (mAccessibilityDelegate != null) {
6308            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
6309        } else {
6310            return null;
6311        }
6312    }
6313
6314    /**
6315     * Gets the unique identifier of this view on the screen for accessibility purposes.
6316     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
6317     *
6318     * @return The view accessibility id.
6319     *
6320     * @hide
6321     */
6322    public int getAccessibilityViewId() {
6323        if (mAccessibilityViewId == NO_ID) {
6324            mAccessibilityViewId = sNextAccessibilityViewId++;
6325        }
6326        return mAccessibilityViewId;
6327    }
6328
6329    /**
6330     * Gets the unique identifier of the window in which this View reseides.
6331     *
6332     * @return The window accessibility id.
6333     *
6334     * @hide
6335     */
6336    public int getAccessibilityWindowId() {
6337        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
6338                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
6339    }
6340
6341    /**
6342     * Gets the {@link View} description. It briefly describes the view and is
6343     * primarily used for accessibility support. Set this property to enable
6344     * better accessibility support for your application. This is especially
6345     * true for views that do not have textual representation (For example,
6346     * ImageButton).
6347     *
6348     * @return The content description.
6349     *
6350     * @attr ref android.R.styleable#View_contentDescription
6351     */
6352    @ViewDebug.ExportedProperty(category = "accessibility")
6353    public CharSequence getContentDescription() {
6354        return mContentDescription;
6355    }
6356
6357    /**
6358     * Sets the {@link View} description. It briefly describes the view and is
6359     * primarily used for accessibility support. Set this property to enable
6360     * better accessibility support for your application. This is especially
6361     * true for views that do not have textual representation (For example,
6362     * ImageButton).
6363     *
6364     * @param contentDescription The content description.
6365     *
6366     * @attr ref android.R.styleable#View_contentDescription
6367     */
6368    @RemotableViewMethod
6369    public void setContentDescription(CharSequence contentDescription) {
6370        if (mContentDescription == null) {
6371            if (contentDescription == null) {
6372                return;
6373            }
6374        } else if (mContentDescription.equals(contentDescription)) {
6375            return;
6376        }
6377        mContentDescription = contentDescription;
6378        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
6379        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
6380            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
6381            notifySubtreeAccessibilityStateChangedIfNeeded();
6382        } else {
6383            notifyViewAccessibilityStateChangedIfNeeded(
6384                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
6385        }
6386    }
6387
6388    /**
6389     * Sets the id of a view before which this one is visited in accessibility traversal.
6390     * A screen-reader must visit the content of this view before the content of the one
6391     * it precedes. For example, if view B is set to be before view A, then a screen-reader
6392     * will traverse the entire content of B before traversing the entire content of A,
6393     * regardles of what traversal strategy it is using.
6394     * <p>
6395     * Views that do not have specified before/after relationships are traversed in order
6396     * determined by the screen-reader.
6397     * </p>
6398     * <p>
6399     * Setting that this view is before a view that is not important for accessibility
6400     * or if this view is not important for accessibility will have no effect as the
6401     * screen-reader is not aware of unimportant views.
6402     * </p>
6403     *
6404     * @param beforeId The id of a view this one precedes in accessibility traversal.
6405     *
6406     * @attr ref android.R.styleable#View_accessibilityTraversalBefore
6407     *
6408     * @see #setImportantForAccessibility(int)
6409     */
6410    @RemotableViewMethod
6411    public void setAccessibilityTraversalBefore(int beforeId) {
6412        if (mAccessibilityTraversalBeforeId == beforeId) {
6413            return;
6414        }
6415        mAccessibilityTraversalBeforeId = beforeId;
6416        notifyViewAccessibilityStateChangedIfNeeded(
6417                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6418    }
6419
6420    /**
6421     * Gets the id of a view before which this one is visited in accessibility traversal.
6422     *
6423     * @return The id of a view this one precedes in accessibility traversal if
6424     *         specified, otherwise {@link #NO_ID}.
6425     *
6426     * @see #setAccessibilityTraversalBefore(int)
6427     */
6428    public int getAccessibilityTraversalBefore() {
6429        return mAccessibilityTraversalBeforeId;
6430    }
6431
6432    /**
6433     * Sets the id of a view after which this one is visited in accessibility traversal.
6434     * A screen-reader must visit the content of the other view before the content of this
6435     * one. For example, if view B is set to be after view A, then a screen-reader
6436     * will traverse the entire content of A before traversing the entire content of B,
6437     * regardles of what traversal strategy it is using.
6438     * <p>
6439     * Views that do not have specified before/after relationships are traversed in order
6440     * determined by the screen-reader.
6441     * </p>
6442     * <p>
6443     * Setting that this view is after a view that is not important for accessibility
6444     * or if this view is not important for accessibility will have no effect as the
6445     * screen-reader is not aware of unimportant views.
6446     * </p>
6447     *
6448     * @param afterId The id of a view this one succedees in accessibility traversal.
6449     *
6450     * @attr ref android.R.styleable#View_accessibilityTraversalAfter
6451     *
6452     * @see #setImportantForAccessibility(int)
6453     */
6454    @RemotableViewMethod
6455    public void setAccessibilityTraversalAfter(int afterId) {
6456        if (mAccessibilityTraversalAfterId == afterId) {
6457            return;
6458        }
6459        mAccessibilityTraversalAfterId = afterId;
6460        notifyViewAccessibilityStateChangedIfNeeded(
6461                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6462    }
6463
6464    /**
6465     * Gets the id of a view after which this one is visited in accessibility traversal.
6466     *
6467     * @return The id of a view this one succeedes in accessibility traversal if
6468     *         specified, otherwise {@link #NO_ID}.
6469     *
6470     * @see #setAccessibilityTraversalAfter(int)
6471     */
6472    public int getAccessibilityTraversalAfter() {
6473        return mAccessibilityTraversalAfterId;
6474    }
6475
6476    /**
6477     * Gets the id of a view for which this view serves as a label for
6478     * accessibility purposes.
6479     *
6480     * @return The labeled view id.
6481     */
6482    @ViewDebug.ExportedProperty(category = "accessibility")
6483    public int getLabelFor() {
6484        return mLabelForId;
6485    }
6486
6487    /**
6488     * Sets the id of a view for which this view serves as a label for
6489     * accessibility purposes.
6490     *
6491     * @param id The labeled view id.
6492     */
6493    @RemotableViewMethod
6494    public void setLabelFor(@IdRes int id) {
6495        if (mLabelForId == id) {
6496            return;
6497        }
6498        mLabelForId = id;
6499        if (mLabelForId != View.NO_ID
6500                && mID == View.NO_ID) {
6501            mID = generateViewId();
6502        }
6503        notifyViewAccessibilityStateChangedIfNeeded(
6504                AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
6505    }
6506
6507    /**
6508     * Invoked whenever this view loses focus, either by losing window focus or by losing
6509     * focus within its window. This method can be used to clear any state tied to the
6510     * focus. For instance, if a button is held pressed with the trackball and the window
6511     * loses focus, this method can be used to cancel the press.
6512     *
6513     * Subclasses of View overriding this method should always call super.onFocusLost().
6514     *
6515     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
6516     * @see #onWindowFocusChanged(boolean)
6517     *
6518     * @hide pending API council approval
6519     */
6520    @CallSuper
6521    protected void onFocusLost() {
6522        resetPressedState();
6523    }
6524
6525    private void resetPressedState() {
6526        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6527            return;
6528        }
6529
6530        if (isPressed()) {
6531            setPressed(false);
6532
6533            if (!mHasPerformedLongPress) {
6534                removeLongPressCallback();
6535            }
6536        }
6537    }
6538
6539    /**
6540     * Returns true if this view has focus
6541     *
6542     * @return True if this view has focus, false otherwise.
6543     */
6544    @ViewDebug.ExportedProperty(category = "focus")
6545    public boolean isFocused() {
6546        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
6547    }
6548
6549    /**
6550     * Find the view in the hierarchy rooted at this view that currently has
6551     * focus.
6552     *
6553     * @return The view that currently has focus, or null if no focused view can
6554     *         be found.
6555     */
6556    public View findFocus() {
6557        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
6558    }
6559
6560    /**
6561     * Indicates whether this view is one of the set of scrollable containers in
6562     * its window.
6563     *
6564     * @return whether this view is one of the set of scrollable containers in
6565     * its window
6566     *
6567     * @attr ref android.R.styleable#View_isScrollContainer
6568     */
6569    public boolean isScrollContainer() {
6570        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
6571    }
6572
6573    /**
6574     * Change whether this view is one of the set of scrollable containers in
6575     * its window.  This will be used to determine whether the window can
6576     * resize or must pan when a soft input area is open -- scrollable
6577     * containers allow the window to use resize mode since the container
6578     * will appropriately shrink.
6579     *
6580     * @attr ref android.R.styleable#View_isScrollContainer
6581     */
6582    public void setScrollContainer(boolean isScrollContainer) {
6583        if (isScrollContainer) {
6584            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
6585                mAttachInfo.mScrollContainers.add(this);
6586                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
6587            }
6588            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
6589        } else {
6590            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
6591                mAttachInfo.mScrollContainers.remove(this);
6592            }
6593            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
6594        }
6595    }
6596
6597    /**
6598     * Returns the quality of the drawing cache.
6599     *
6600     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6601     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6602     *
6603     * @see #setDrawingCacheQuality(int)
6604     * @see #setDrawingCacheEnabled(boolean)
6605     * @see #isDrawingCacheEnabled()
6606     *
6607     * @attr ref android.R.styleable#View_drawingCacheQuality
6608     */
6609    @DrawingCacheQuality
6610    public int getDrawingCacheQuality() {
6611        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6612    }
6613
6614    /**
6615     * Set the drawing cache quality of this view. This value is used only when the
6616     * drawing cache is enabled
6617     *
6618     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6619     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6620     *
6621     * @see #getDrawingCacheQuality()
6622     * @see #setDrawingCacheEnabled(boolean)
6623     * @see #isDrawingCacheEnabled()
6624     *
6625     * @attr ref android.R.styleable#View_drawingCacheQuality
6626     */
6627    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6628        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6629    }
6630
6631    /**
6632     * Returns whether the screen should remain on, corresponding to the current
6633     * value of {@link #KEEP_SCREEN_ON}.
6634     *
6635     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6636     *
6637     * @see #setKeepScreenOn(boolean)
6638     *
6639     * @attr ref android.R.styleable#View_keepScreenOn
6640     */
6641    public boolean getKeepScreenOn() {
6642        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6643    }
6644
6645    /**
6646     * Controls whether the screen should remain on, modifying the
6647     * value of {@link #KEEP_SCREEN_ON}.
6648     *
6649     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6650     *
6651     * @see #getKeepScreenOn()
6652     *
6653     * @attr ref android.R.styleable#View_keepScreenOn
6654     */
6655    public void setKeepScreenOn(boolean keepScreenOn) {
6656        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6657    }
6658
6659    /**
6660     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6661     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6662     *
6663     * @attr ref android.R.styleable#View_nextFocusLeft
6664     */
6665    public int getNextFocusLeftId() {
6666        return mNextFocusLeftId;
6667    }
6668
6669    /**
6670     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6671     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6672     * decide automatically.
6673     *
6674     * @attr ref android.R.styleable#View_nextFocusLeft
6675     */
6676    public void setNextFocusLeftId(int nextFocusLeftId) {
6677        mNextFocusLeftId = nextFocusLeftId;
6678    }
6679
6680    /**
6681     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6682     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6683     *
6684     * @attr ref android.R.styleable#View_nextFocusRight
6685     */
6686    public int getNextFocusRightId() {
6687        return mNextFocusRightId;
6688    }
6689
6690    /**
6691     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6692     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6693     * decide automatically.
6694     *
6695     * @attr ref android.R.styleable#View_nextFocusRight
6696     */
6697    public void setNextFocusRightId(int nextFocusRightId) {
6698        mNextFocusRightId = nextFocusRightId;
6699    }
6700
6701    /**
6702     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6703     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6704     *
6705     * @attr ref android.R.styleable#View_nextFocusUp
6706     */
6707    public int getNextFocusUpId() {
6708        return mNextFocusUpId;
6709    }
6710
6711    /**
6712     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6713     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6714     * decide automatically.
6715     *
6716     * @attr ref android.R.styleable#View_nextFocusUp
6717     */
6718    public void setNextFocusUpId(int nextFocusUpId) {
6719        mNextFocusUpId = nextFocusUpId;
6720    }
6721
6722    /**
6723     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6724     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6725     *
6726     * @attr ref android.R.styleable#View_nextFocusDown
6727     */
6728    public int getNextFocusDownId() {
6729        return mNextFocusDownId;
6730    }
6731
6732    /**
6733     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6734     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6735     * decide automatically.
6736     *
6737     * @attr ref android.R.styleable#View_nextFocusDown
6738     */
6739    public void setNextFocusDownId(int nextFocusDownId) {
6740        mNextFocusDownId = nextFocusDownId;
6741    }
6742
6743    /**
6744     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6745     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6746     *
6747     * @attr ref android.R.styleable#View_nextFocusForward
6748     */
6749    public int getNextFocusForwardId() {
6750        return mNextFocusForwardId;
6751    }
6752
6753    /**
6754     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6755     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6756     * decide automatically.
6757     *
6758     * @attr ref android.R.styleable#View_nextFocusForward
6759     */
6760    public void setNextFocusForwardId(int nextFocusForwardId) {
6761        mNextFocusForwardId = nextFocusForwardId;
6762    }
6763
6764    /**
6765     * Returns the visibility of this view and all of its ancestors
6766     *
6767     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6768     */
6769    public boolean isShown() {
6770        View current = this;
6771        //noinspection ConstantConditions
6772        do {
6773            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6774                return false;
6775            }
6776            ViewParent parent = current.mParent;
6777            if (parent == null) {
6778                return false; // We are not attached to the view root
6779            }
6780            if (!(parent instanceof View)) {
6781                return true;
6782            }
6783            current = (View) parent;
6784        } while (current != null);
6785
6786        return false;
6787    }
6788
6789    /**
6790     * Called by the view hierarchy when the content insets for a window have
6791     * changed, to allow it to adjust its content to fit within those windows.
6792     * The content insets tell you the space that the status bar, input method,
6793     * and other system windows infringe on the application's window.
6794     *
6795     * <p>You do not normally need to deal with this function, since the default
6796     * window decoration given to applications takes care of applying it to the
6797     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6798     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6799     * and your content can be placed under those system elements.  You can then
6800     * use this method within your view hierarchy if you have parts of your UI
6801     * which you would like to ensure are not being covered.
6802     *
6803     * <p>The default implementation of this method simply applies the content
6804     * insets to the view's padding, consuming that content (modifying the
6805     * insets to be 0), and returning true.  This behavior is off by default, but can
6806     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6807     *
6808     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6809     * insets object is propagated down the hierarchy, so any changes made to it will
6810     * be seen by all following views (including potentially ones above in
6811     * the hierarchy since this is a depth-first traversal).  The first view
6812     * that returns true will abort the entire traversal.
6813     *
6814     * <p>The default implementation works well for a situation where it is
6815     * used with a container that covers the entire window, allowing it to
6816     * apply the appropriate insets to its content on all edges.  If you need
6817     * a more complicated layout (such as two different views fitting system
6818     * windows, one on the top of the window, and one on the bottom),
6819     * you can override the method and handle the insets however you would like.
6820     * Note that the insets provided by the framework are always relative to the
6821     * far edges of the window, not accounting for the location of the called view
6822     * within that window.  (In fact when this method is called you do not yet know
6823     * where the layout will place the view, as it is done before layout happens.)
6824     *
6825     * <p>Note: unlike many View methods, there is no dispatch phase to this
6826     * call.  If you are overriding it in a ViewGroup and want to allow the
6827     * call to continue to your children, you must be sure to call the super
6828     * implementation.
6829     *
6830     * <p>Here is a sample layout that makes use of fitting system windows
6831     * to have controls for a video view placed inside of the window decorations
6832     * that it hides and shows.  This can be used with code like the second
6833     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6834     *
6835     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6836     *
6837     * @param insets Current content insets of the window.  Prior to
6838     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6839     * the insets or else you and Android will be unhappy.
6840     *
6841     * @return {@code true} if this view applied the insets and it should not
6842     * continue propagating further down the hierarchy, {@code false} otherwise.
6843     * @see #getFitsSystemWindows()
6844     * @see #setFitsSystemWindows(boolean)
6845     * @see #setSystemUiVisibility(int)
6846     *
6847     * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6848     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6849     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6850     * to implement handling their own insets.
6851     */
6852    protected boolean fitSystemWindows(Rect insets) {
6853        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6854            if (insets == null) {
6855                // Null insets by definition have already been consumed.
6856                // This call cannot apply insets since there are none to apply,
6857                // so return false.
6858                return false;
6859            }
6860            // If we're not in the process of dispatching the newer apply insets call,
6861            // that means we're not in the compatibility path. Dispatch into the newer
6862            // apply insets path and take things from there.
6863            try {
6864                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6865                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6866            } finally {
6867                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6868            }
6869        } else {
6870            // We're being called from the newer apply insets path.
6871            // Perform the standard fallback behavior.
6872            return fitSystemWindowsInt(insets);
6873        }
6874    }
6875
6876    private boolean fitSystemWindowsInt(Rect insets) {
6877        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6878            mUserPaddingStart = UNDEFINED_PADDING;
6879            mUserPaddingEnd = UNDEFINED_PADDING;
6880            Rect localInsets = sThreadLocal.get();
6881            if (localInsets == null) {
6882                localInsets = new Rect();
6883                sThreadLocal.set(localInsets);
6884            }
6885            boolean res = computeFitSystemWindows(insets, localInsets);
6886            mUserPaddingLeftInitial = localInsets.left;
6887            mUserPaddingRightInitial = localInsets.right;
6888            internalSetPadding(localInsets.left, localInsets.top,
6889                    localInsets.right, localInsets.bottom);
6890            return res;
6891        }
6892        return false;
6893    }
6894
6895    /**
6896     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6897     *
6898     * <p>This method should be overridden by views that wish to apply a policy different from or
6899     * in addition to the default behavior. Clients that wish to force a view subtree
6900     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6901     *
6902     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6903     * it will be called during dispatch instead of this method. The listener may optionally
6904     * call this method from its own implementation if it wishes to apply the view's default
6905     * insets policy in addition to its own.</p>
6906     *
6907     * <p>Implementations of this method should either return the insets parameter unchanged
6908     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6909     * that this view applied itself. This allows new inset types added in future platform
6910     * versions to pass through existing implementations unchanged without being erroneously
6911     * consumed.</p>
6912     *
6913     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6914     * property is set then the view will consume the system window insets and apply them
6915     * as padding for the view.</p>
6916     *
6917     * @param insets Insets to apply
6918     * @return The supplied insets with any applied insets consumed
6919     */
6920    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6921        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6922            // We weren't called from within a direct call to fitSystemWindows,
6923            // call into it as a fallback in case we're in a class that overrides it
6924            // and has logic to perform.
6925            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6926                return insets.consumeSystemWindowInsets();
6927            }
6928        } else {
6929            // We were called from within a direct call to fitSystemWindows.
6930            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6931                return insets.consumeSystemWindowInsets();
6932            }
6933        }
6934        return insets;
6935    }
6936
6937    /**
6938     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6939     * window insets to this view. The listener's
6940     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6941     * method will be called instead of the view's
6942     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6943     *
6944     * @param listener Listener to set
6945     *
6946     * @see #onApplyWindowInsets(WindowInsets)
6947     */
6948    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6949        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6950    }
6951
6952    /**
6953     * Request to apply the given window insets to this view or another view in its subtree.
6954     *
6955     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6956     * obscured by window decorations or overlays. This can include the status and navigation bars,
6957     * action bars, input methods and more. New inset categories may be added in the future.
6958     * The method returns the insets provided minus any that were applied by this view or its
6959     * children.</p>
6960     *
6961     * <p>Clients wishing to provide custom behavior should override the
6962     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6963     * {@link OnApplyWindowInsetsListener} via the
6964     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6965     * method.</p>
6966     *
6967     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6968     * </p>
6969     *
6970     * @param insets Insets to apply
6971     * @return The provided insets minus the insets that were consumed
6972     */
6973    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6974        try {
6975            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6976            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6977                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6978            } else {
6979                return onApplyWindowInsets(insets);
6980            }
6981        } finally {
6982            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6983        }
6984    }
6985
6986    /**
6987     * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are
6988     * only available if the view is attached.
6989     *
6990     * @return WindowInsets from the top of the view hierarchy or null if View is detached
6991     */
6992    public WindowInsets getRootWindowInsets() {
6993        if (mAttachInfo != null) {
6994            return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */);
6995        }
6996        return null;
6997    }
6998
6999    /**
7000     * @hide Compute the insets that should be consumed by this view and the ones
7001     * that should propagate to those under it.
7002     */
7003    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
7004        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7005                || mAttachInfo == null
7006                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
7007                        && !mAttachInfo.mOverscanRequested)) {
7008            outLocalInsets.set(inoutInsets);
7009            inoutInsets.set(0, 0, 0, 0);
7010            return true;
7011        } else {
7012            // The application wants to take care of fitting system window for
7013            // the content...  however we still need to take care of any overscan here.
7014            final Rect overscan = mAttachInfo.mOverscanInsets;
7015            outLocalInsets.set(overscan);
7016            inoutInsets.left -= overscan.left;
7017            inoutInsets.top -= overscan.top;
7018            inoutInsets.right -= overscan.right;
7019            inoutInsets.bottom -= overscan.bottom;
7020            return false;
7021        }
7022    }
7023
7024    /**
7025     * Compute insets that should be consumed by this view and the ones that should propagate
7026     * to those under it.
7027     *
7028     * @param in Insets currently being processed by this View, likely received as a parameter
7029     *           to {@link #onApplyWindowInsets(WindowInsets)}.
7030     * @param outLocalInsets A Rect that will receive the insets that should be consumed
7031     *                       by this view
7032     * @return Insets that should be passed along to views under this one
7033     */
7034    public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) {
7035        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
7036                || mAttachInfo == null
7037                || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
7038            outLocalInsets.set(in.getSystemWindowInsets());
7039            return in.consumeSystemWindowInsets();
7040        } else {
7041            outLocalInsets.set(0, 0, 0, 0);
7042            return in;
7043        }
7044    }
7045
7046    /**
7047     * Sets whether or not this view should account for system screen decorations
7048     * such as the status bar and inset its content; that is, controlling whether
7049     * the default implementation of {@link #fitSystemWindows(Rect)} will be
7050     * executed.  See that method for more details.
7051     *
7052     * <p>Note that if you are providing your own implementation of
7053     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
7054     * flag to true -- your implementation will be overriding the default
7055     * implementation that checks this flag.
7056     *
7057     * @param fitSystemWindows If true, then the default implementation of
7058     * {@link #fitSystemWindows(Rect)} will be executed.
7059     *
7060     * @attr ref android.R.styleable#View_fitsSystemWindows
7061     * @see #getFitsSystemWindows()
7062     * @see #fitSystemWindows(Rect)
7063     * @see #setSystemUiVisibility(int)
7064     */
7065    public void setFitsSystemWindows(boolean fitSystemWindows) {
7066        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
7067    }
7068
7069    /**
7070     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
7071     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
7072     * will be executed.
7073     *
7074     * @return {@code true} if the default implementation of
7075     * {@link #fitSystemWindows(Rect)} will be executed.
7076     *
7077     * @attr ref android.R.styleable#View_fitsSystemWindows
7078     * @see #setFitsSystemWindows(boolean)
7079     * @see #fitSystemWindows(Rect)
7080     * @see #setSystemUiVisibility(int)
7081     */
7082    @ViewDebug.ExportedProperty
7083    public boolean getFitsSystemWindows() {
7084        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
7085    }
7086
7087    /** @hide */
7088    public boolean fitsSystemWindows() {
7089        return getFitsSystemWindows();
7090    }
7091
7092    /**
7093     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
7094     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
7095     */
7096    public void requestFitSystemWindows() {
7097        if (mParent != null) {
7098            mParent.requestFitSystemWindows();
7099        }
7100    }
7101
7102    /**
7103     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
7104     */
7105    public void requestApplyInsets() {
7106        requestFitSystemWindows();
7107    }
7108
7109    /**
7110     * For use by PhoneWindow to make its own system window fitting optional.
7111     * @hide
7112     */
7113    public void makeOptionalFitsSystemWindows() {
7114        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
7115    }
7116
7117    /**
7118     * Returns the visibility status for this view.
7119     *
7120     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7121     * @attr ref android.R.styleable#View_visibility
7122     */
7123    @ViewDebug.ExportedProperty(mapping = {
7124        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
7125        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
7126        @ViewDebug.IntToString(from = GONE,      to = "GONE")
7127    })
7128    @Visibility
7129    public int getVisibility() {
7130        return mViewFlags & VISIBILITY_MASK;
7131    }
7132
7133    /**
7134     * Set the enabled state of this view.
7135     *
7136     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
7137     * @attr ref android.R.styleable#View_visibility
7138     */
7139    @RemotableViewMethod
7140    public void setVisibility(@Visibility int visibility) {
7141        setFlags(visibility, VISIBILITY_MASK);
7142    }
7143
7144    /**
7145     * Returns the enabled status for this view. The interpretation of the
7146     * enabled state varies by subclass.
7147     *
7148     * @return True if this view is enabled, false otherwise.
7149     */
7150    @ViewDebug.ExportedProperty
7151    public boolean isEnabled() {
7152        return (mViewFlags & ENABLED_MASK) == ENABLED;
7153    }
7154
7155    /**
7156     * Set the enabled state of this view. The interpretation of the enabled
7157     * state varies by subclass.
7158     *
7159     * @param enabled True if this view is enabled, false otherwise.
7160     */
7161    @RemotableViewMethod
7162    public void setEnabled(boolean enabled) {
7163        if (enabled == isEnabled()) return;
7164
7165        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
7166
7167        /*
7168         * The View most likely has to change its appearance, so refresh
7169         * the drawable state.
7170         */
7171        refreshDrawableState();
7172
7173        // Invalidate too, since the default behavior for views is to be
7174        // be drawn at 50% alpha rather than to change the drawable.
7175        invalidate(true);
7176
7177        if (!enabled) {
7178            cancelPendingInputEvents();
7179        }
7180    }
7181
7182    /**
7183     * Set whether this view can receive the focus.
7184     *
7185     * Setting this to false will also ensure that this view is not focusable
7186     * in touch mode.
7187     *
7188     * @param focusable If true, this view can receive the focus.
7189     *
7190     * @see #setFocusableInTouchMode(boolean)
7191     * @attr ref android.R.styleable#View_focusable
7192     */
7193    public void setFocusable(boolean focusable) {
7194        if (!focusable) {
7195            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
7196        }
7197        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
7198    }
7199
7200    /**
7201     * Set whether this view can receive focus while in touch mode.
7202     *
7203     * Setting this to true will also ensure that this view is focusable.
7204     *
7205     * @param focusableInTouchMode If true, this view can receive the focus while
7206     *   in touch mode.
7207     *
7208     * @see #setFocusable(boolean)
7209     * @attr ref android.R.styleable#View_focusableInTouchMode
7210     */
7211    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
7212        // Focusable in touch mode should always be set before the focusable flag
7213        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
7214        // which, in touch mode, will not successfully request focus on this view
7215        // because the focusable in touch mode flag is not set
7216        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
7217        if (focusableInTouchMode) {
7218            setFlags(FOCUSABLE, FOCUSABLE_MASK);
7219        }
7220    }
7221
7222    /**
7223     * Set whether this view should have sound effects enabled for events such as
7224     * clicking and touching.
7225     *
7226     * <p>You may wish to disable sound effects for a view if you already play sounds,
7227     * for instance, a dial key that plays dtmf tones.
7228     *
7229     * @param soundEffectsEnabled whether sound effects are enabled for this view.
7230     * @see #isSoundEffectsEnabled()
7231     * @see #playSoundEffect(int)
7232     * @attr ref android.R.styleable#View_soundEffectsEnabled
7233     */
7234    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
7235        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
7236    }
7237
7238    /**
7239     * @return whether this view should have sound effects enabled for events such as
7240     *     clicking and touching.
7241     *
7242     * @see #setSoundEffectsEnabled(boolean)
7243     * @see #playSoundEffect(int)
7244     * @attr ref android.R.styleable#View_soundEffectsEnabled
7245     */
7246    @ViewDebug.ExportedProperty
7247    public boolean isSoundEffectsEnabled() {
7248        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
7249    }
7250
7251    /**
7252     * Set whether this view should have haptic feedback for events such as
7253     * long presses.
7254     *
7255     * <p>You may wish to disable haptic feedback if your view already controls
7256     * its own haptic feedback.
7257     *
7258     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
7259     * @see #isHapticFeedbackEnabled()
7260     * @see #performHapticFeedback(int)
7261     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7262     */
7263    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
7264        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
7265    }
7266
7267    /**
7268     * @return whether this view should have haptic feedback enabled for events
7269     * long presses.
7270     *
7271     * @see #setHapticFeedbackEnabled(boolean)
7272     * @see #performHapticFeedback(int)
7273     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
7274     */
7275    @ViewDebug.ExportedProperty
7276    public boolean isHapticFeedbackEnabled() {
7277        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
7278    }
7279
7280    /**
7281     * Returns the layout direction for this view.
7282     *
7283     * @return One of {@link #LAYOUT_DIRECTION_LTR},
7284     *   {@link #LAYOUT_DIRECTION_RTL},
7285     *   {@link #LAYOUT_DIRECTION_INHERIT} or
7286     *   {@link #LAYOUT_DIRECTION_LOCALE}.
7287     *
7288     * @attr ref android.R.styleable#View_layoutDirection
7289     *
7290     * @hide
7291     */
7292    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7293        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
7294        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
7295        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
7296        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
7297    })
7298    @LayoutDir
7299    public int getRawLayoutDirection() {
7300        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
7301    }
7302
7303    /**
7304     * Set the layout direction for this view. This will propagate a reset of layout direction
7305     * resolution to the view's children and resolve layout direction for this view.
7306     *
7307     * @param layoutDirection the layout direction to set. Should be one of:
7308     *
7309     * {@link #LAYOUT_DIRECTION_LTR},
7310     * {@link #LAYOUT_DIRECTION_RTL},
7311     * {@link #LAYOUT_DIRECTION_INHERIT},
7312     * {@link #LAYOUT_DIRECTION_LOCALE}.
7313     *
7314     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
7315     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
7316     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
7317     *
7318     * @attr ref android.R.styleable#View_layoutDirection
7319     */
7320    @RemotableViewMethod
7321    public void setLayoutDirection(@LayoutDir int layoutDirection) {
7322        if (getRawLayoutDirection() != layoutDirection) {
7323            // Reset the current layout direction and the resolved one
7324            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
7325            resetRtlProperties();
7326            // Set the new layout direction (filtered)
7327            mPrivateFlags2 |=
7328                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
7329            // We need to resolve all RTL properties as they all depend on layout direction
7330            resolveRtlPropertiesIfNeeded();
7331            requestLayout();
7332            invalidate(true);
7333        }
7334    }
7335
7336    /**
7337     * Returns the resolved layout direction for this view.
7338     *
7339     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
7340     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
7341     *
7342     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
7343     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
7344     *
7345     * @attr ref android.R.styleable#View_layoutDirection
7346     */
7347    @ViewDebug.ExportedProperty(category = "layout", mapping = {
7348        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
7349        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
7350    })
7351    @ResolvedLayoutDir
7352    public int getLayoutDirection() {
7353        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
7354        if (targetSdkVersion < JELLY_BEAN_MR1) {
7355            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
7356            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
7357        }
7358        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
7359                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
7360    }
7361
7362    /**
7363     * Indicates whether or not this view's layout is right-to-left. This is resolved from
7364     * layout attribute and/or the inherited value from the parent
7365     *
7366     * @return true if the layout is right-to-left.
7367     *
7368     * @hide
7369     */
7370    @ViewDebug.ExportedProperty(category = "layout")
7371    public boolean isLayoutRtl() {
7372        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
7373    }
7374
7375    /**
7376     * Indicates whether the view is currently tracking transient state that the
7377     * app should not need to concern itself with saving and restoring, but that
7378     * the framework should take special note to preserve when possible.
7379     *
7380     * <p>A view with transient state cannot be trivially rebound from an external
7381     * data source, such as an adapter binding item views in a list. This may be
7382     * because the view is performing an animation, tracking user selection
7383     * of content, or similar.</p>
7384     *
7385     * @return true if the view has transient state
7386     */
7387    @ViewDebug.ExportedProperty(category = "layout")
7388    public boolean hasTransientState() {
7389        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
7390    }
7391
7392    /**
7393     * Set whether this view is currently tracking transient state that the
7394     * framework should attempt to preserve when possible. This flag is reference counted,
7395     * so every call to setHasTransientState(true) should be paired with a later call
7396     * to setHasTransientState(false).
7397     *
7398     * <p>A view with transient state cannot be trivially rebound from an external
7399     * data source, such as an adapter binding item views in a list. This may be
7400     * because the view is performing an animation, tracking user selection
7401     * of content, or similar.</p>
7402     *
7403     * @param hasTransientState true if this view has transient state
7404     */
7405    public void setHasTransientState(boolean hasTransientState) {
7406        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
7407                mTransientStateCount - 1;
7408        if (mTransientStateCount < 0) {
7409            mTransientStateCount = 0;
7410            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
7411                    "unmatched pair of setHasTransientState calls");
7412        } else if ((hasTransientState && mTransientStateCount == 1) ||
7413                (!hasTransientState && mTransientStateCount == 0)) {
7414            // update flag if we've just incremented up from 0 or decremented down to 0
7415            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
7416                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
7417            if (mParent != null) {
7418                try {
7419                    mParent.childHasTransientStateChanged(this, hasTransientState);
7420                } catch (AbstractMethodError e) {
7421                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7422                            " does not fully implement ViewParent", e);
7423                }
7424            }
7425        }
7426    }
7427
7428    /**
7429     * Returns true if this view is currently attached to a window.
7430     */
7431    public boolean isAttachedToWindow() {
7432        return mAttachInfo != null;
7433    }
7434
7435    /**
7436     * Returns true if this view has been through at least one layout since it
7437     * was last attached to or detached from a window.
7438     */
7439    public boolean isLaidOut() {
7440        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
7441    }
7442
7443    /**
7444     * If this view doesn't do any drawing on its own, set this flag to
7445     * allow further optimizations. By default, this flag is not set on
7446     * View, but could be set on some View subclasses such as ViewGroup.
7447     *
7448     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
7449     * you should clear this flag.
7450     *
7451     * @param willNotDraw whether or not this View draw on its own
7452     */
7453    public void setWillNotDraw(boolean willNotDraw) {
7454        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
7455    }
7456
7457    /**
7458     * Returns whether or not this View draws on its own.
7459     *
7460     * @return true if this view has nothing to draw, false otherwise
7461     */
7462    @ViewDebug.ExportedProperty(category = "drawing")
7463    public boolean willNotDraw() {
7464        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
7465    }
7466
7467    /**
7468     * When a View's drawing cache is enabled, drawing is redirected to an
7469     * offscreen bitmap. Some views, like an ImageView, must be able to
7470     * bypass this mechanism if they already draw a single bitmap, to avoid
7471     * unnecessary usage of the memory.
7472     *
7473     * @param willNotCacheDrawing true if this view does not cache its
7474     *        drawing, false otherwise
7475     */
7476    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
7477        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
7478    }
7479
7480    /**
7481     * Returns whether or not this View can cache its drawing or not.
7482     *
7483     * @return true if this view does not cache its drawing, false otherwise
7484     */
7485    @ViewDebug.ExportedProperty(category = "drawing")
7486    public boolean willNotCacheDrawing() {
7487        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
7488    }
7489
7490    /**
7491     * Indicates whether this view reacts to click events or not.
7492     *
7493     * @return true if the view is clickable, false otherwise
7494     *
7495     * @see #setClickable(boolean)
7496     * @attr ref android.R.styleable#View_clickable
7497     */
7498    @ViewDebug.ExportedProperty
7499    public boolean isClickable() {
7500        return (mViewFlags & CLICKABLE) == CLICKABLE;
7501    }
7502
7503    /**
7504     * Enables or disables click events for this view. When a view
7505     * is clickable it will change its state to "pressed" on every click.
7506     * Subclasses should set the view clickable to visually react to
7507     * user's clicks.
7508     *
7509     * @param clickable true to make the view clickable, false otherwise
7510     *
7511     * @see #isClickable()
7512     * @attr ref android.R.styleable#View_clickable
7513     */
7514    public void setClickable(boolean clickable) {
7515        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
7516    }
7517
7518    /**
7519     * Indicates whether this view reacts to long click events or not.
7520     *
7521     * @return true if the view is long clickable, false otherwise
7522     *
7523     * @see #setLongClickable(boolean)
7524     * @attr ref android.R.styleable#View_longClickable
7525     */
7526    public boolean isLongClickable() {
7527        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7528    }
7529
7530    /**
7531     * Enables or disables long click events for this view. When a view is long
7532     * clickable it reacts to the user holding down the button for a longer
7533     * duration than a tap. This event can either launch the listener or a
7534     * context menu.
7535     *
7536     * @param longClickable true to make the view long clickable, false otherwise
7537     * @see #isLongClickable()
7538     * @attr ref android.R.styleable#View_longClickable
7539     */
7540    public void setLongClickable(boolean longClickable) {
7541        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
7542    }
7543
7544    /**
7545     * Indicates whether this view reacts to stylus button press events or not.
7546     *
7547     * @return true if the view is stylus button pressable, false otherwise
7548     * @see #setStylusButtonPressable(boolean)
7549     * @attr ref android.R.styleable#View_stylusButtonPressable
7550     */
7551    public boolean isStylusButtonPressable() {
7552        return (mViewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE;
7553    }
7554
7555    /**
7556     * Enables or disables stylus button press events for this view. When a view is stylus button
7557     * pressable it reacts to the user touching the screen with a stylus and pressing the first
7558     * stylus button. This event can launch the listener.
7559     *
7560     * @param stylusButtonPressable true to make the view react to a stylus button press, false
7561     *            otherwise
7562     * @see #isStylusButtonPressable()
7563     * @attr ref android.R.styleable#View_stylusButtonPressable
7564     */
7565    public void setStylusButtonPressable(boolean stylusButtonPressable) {
7566        setFlags(stylusButtonPressable ? STYLUS_BUTTON_PRESSABLE : 0, STYLUS_BUTTON_PRESSABLE);
7567    }
7568
7569    /**
7570     * Sets the pressed state for this view and provides a touch coordinate for
7571     * animation hinting.
7572     *
7573     * @param pressed Pass true to set the View's internal state to "pressed",
7574     *            or false to reverts the View's internal state from a
7575     *            previously set "pressed" state.
7576     * @param x The x coordinate of the touch that caused the press
7577     * @param y The y coordinate of the touch that caused the press
7578     */
7579    private void setPressed(boolean pressed, float x, float y) {
7580        if (pressed) {
7581            drawableHotspotChanged(x, y);
7582        }
7583
7584        setPressed(pressed);
7585    }
7586
7587    /**
7588     * Sets the pressed state for this view.
7589     *
7590     * @see #isClickable()
7591     * @see #setClickable(boolean)
7592     *
7593     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
7594     *        the View's internal state from a previously set "pressed" state.
7595     */
7596    public void setPressed(boolean pressed) {
7597        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
7598
7599        if (pressed) {
7600            mPrivateFlags |= PFLAG_PRESSED;
7601        } else {
7602            mPrivateFlags &= ~PFLAG_PRESSED;
7603        }
7604
7605        if (needsRefresh) {
7606            refreshDrawableState();
7607        }
7608        dispatchSetPressed(pressed);
7609    }
7610
7611    /**
7612     * Dispatch setPressed to all of this View's children.
7613     *
7614     * @see #setPressed(boolean)
7615     *
7616     * @param pressed The new pressed state
7617     */
7618    protected void dispatchSetPressed(boolean pressed) {
7619    }
7620
7621    /**
7622     * Indicates whether the view is currently in pressed state. Unless
7623     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
7624     * the pressed state.
7625     *
7626     * @see #setPressed(boolean)
7627     * @see #isClickable()
7628     * @see #setClickable(boolean)
7629     *
7630     * @return true if the view is currently pressed, false otherwise
7631     */
7632    @ViewDebug.ExportedProperty
7633    public boolean isPressed() {
7634        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
7635    }
7636
7637    /**
7638     * Indicates whether this view will participate in data collection through
7639     * {@link android.view.ViewAssistStructure}.  If true, it will not provide any data
7640     * for itself or its children.  If false, the normal data collection will be allowed.
7641     *
7642     * @return Returns false if assist data collection is not blocked, else true.
7643     *
7644     * @see #setAssistBlocked(boolean)
7645     * @attr ref android.R.styleable#View_assistBlocked
7646     */
7647    public boolean isAssistBlocked() {
7648        return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0;
7649    }
7650
7651    /**
7652     * Controls whether assist data collection from this view and its children is enabled
7653     * (that is, whether {@link #onProvideAssistStructure} and
7654     * {@link #onProvideVirtualAssistStructure} will be called).  The default value is false,
7655     * allowing normal assist collection.  Setting this to false will disable assist collection.
7656     *
7657     * @param enabled Set to true to <em>disable</em> assist data collection, or false
7658     * (the default) to allow it.
7659     *
7660     * @see #isAssistBlocked()
7661     * @see #onProvideAssistStructure
7662     * @see #onProvideVirtualAssistStructure
7663     * @attr ref android.R.styleable#View_assistBlocked
7664     */
7665    public void setAssistBlocked(boolean enabled) {
7666        if (enabled) {
7667            mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED;
7668        } else {
7669            mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED;
7670        }
7671    }
7672
7673    /**
7674     * Indicates whether this view will save its state (that is,
7675     * whether its {@link #onSaveInstanceState} method will be called).
7676     *
7677     * @return Returns true if the view state saving is enabled, else false.
7678     *
7679     * @see #setSaveEnabled(boolean)
7680     * @attr ref android.R.styleable#View_saveEnabled
7681     */
7682    public boolean isSaveEnabled() {
7683        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
7684    }
7685
7686    /**
7687     * Controls whether the saving of this view's state is
7688     * enabled (that is, whether its {@link #onSaveInstanceState} method
7689     * will be called).  Note that even if freezing is enabled, the
7690     * view still must have an id assigned to it (via {@link #setId(int)})
7691     * for its state to be saved.  This flag can only disable the
7692     * saving of this view; any child views may still have their state saved.
7693     *
7694     * @param enabled Set to false to <em>disable</em> state saving, or true
7695     * (the default) to allow it.
7696     *
7697     * @see #isSaveEnabled()
7698     * @see #setId(int)
7699     * @see #onSaveInstanceState()
7700     * @attr ref android.R.styleable#View_saveEnabled
7701     */
7702    public void setSaveEnabled(boolean enabled) {
7703        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7704    }
7705
7706    /**
7707     * Gets whether the framework should discard touches when the view's
7708     * window is obscured by another visible window.
7709     * Refer to the {@link View} security documentation for more details.
7710     *
7711     * @return True if touch filtering is enabled.
7712     *
7713     * @see #setFilterTouchesWhenObscured(boolean)
7714     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7715     */
7716    @ViewDebug.ExportedProperty
7717    public boolean getFilterTouchesWhenObscured() {
7718        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7719    }
7720
7721    /**
7722     * Sets whether the framework should discard touches when the view's
7723     * window is obscured by another visible window.
7724     * Refer to the {@link View} security documentation for more details.
7725     *
7726     * @param enabled True if touch filtering should be enabled.
7727     *
7728     * @see #getFilterTouchesWhenObscured
7729     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7730     */
7731    public void setFilterTouchesWhenObscured(boolean enabled) {
7732        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7733                FILTER_TOUCHES_WHEN_OBSCURED);
7734    }
7735
7736    /**
7737     * Indicates whether the entire hierarchy under this view will save its
7738     * state when a state saving traversal occurs from its parent.  The default
7739     * is true; if false, these views will not be saved unless
7740     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7741     *
7742     * @return Returns true if the view state saving from parent is enabled, else false.
7743     *
7744     * @see #setSaveFromParentEnabled(boolean)
7745     */
7746    public boolean isSaveFromParentEnabled() {
7747        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7748    }
7749
7750    /**
7751     * Controls whether the entire hierarchy under this view will save its
7752     * state when a state saving traversal occurs from its parent.  The default
7753     * is true; if false, these views will not be saved unless
7754     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7755     *
7756     * @param enabled Set to false to <em>disable</em> state saving, or true
7757     * (the default) to allow it.
7758     *
7759     * @see #isSaveFromParentEnabled()
7760     * @see #setId(int)
7761     * @see #onSaveInstanceState()
7762     */
7763    public void setSaveFromParentEnabled(boolean enabled) {
7764        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7765    }
7766
7767
7768    /**
7769     * Returns whether this View is able to take focus.
7770     *
7771     * @return True if this view can take focus, or false otherwise.
7772     * @attr ref android.R.styleable#View_focusable
7773     */
7774    @ViewDebug.ExportedProperty(category = "focus")
7775    public final boolean isFocusable() {
7776        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7777    }
7778
7779    /**
7780     * When a view is focusable, it may not want to take focus when in touch mode.
7781     * For example, a button would like focus when the user is navigating via a D-pad
7782     * so that the user can click on it, but once the user starts touching the screen,
7783     * the button shouldn't take focus
7784     * @return Whether the view is focusable in touch mode.
7785     * @attr ref android.R.styleable#View_focusableInTouchMode
7786     */
7787    @ViewDebug.ExportedProperty
7788    public final boolean isFocusableInTouchMode() {
7789        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7790    }
7791
7792    /**
7793     * Find the nearest view in the specified direction that can take focus.
7794     * This does not actually give focus to that view.
7795     *
7796     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7797     *
7798     * @return The nearest focusable in the specified direction, or null if none
7799     *         can be found.
7800     */
7801    public View focusSearch(@FocusRealDirection int direction) {
7802        if (mParent != null) {
7803            return mParent.focusSearch(this, direction);
7804        } else {
7805            return null;
7806        }
7807    }
7808
7809    /**
7810     * This method is the last chance for the focused view and its ancestors to
7811     * respond to an arrow key. This is called when the focused view did not
7812     * consume the key internally, nor could the view system find a new view in
7813     * the requested direction to give focus to.
7814     *
7815     * @param focused The currently focused view.
7816     * @param direction The direction focus wants to move. One of FOCUS_UP,
7817     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7818     * @return True if the this view consumed this unhandled move.
7819     */
7820    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7821        return false;
7822    }
7823
7824    /**
7825     * If a user manually specified the next view id for a particular direction,
7826     * use the root to look up the view.
7827     * @param root The root view of the hierarchy containing this view.
7828     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7829     * or FOCUS_BACKWARD.
7830     * @return The user specified next view, or null if there is none.
7831     */
7832    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7833        switch (direction) {
7834            case FOCUS_LEFT:
7835                if (mNextFocusLeftId == View.NO_ID) return null;
7836                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7837            case FOCUS_RIGHT:
7838                if (mNextFocusRightId == View.NO_ID) return null;
7839                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7840            case FOCUS_UP:
7841                if (mNextFocusUpId == View.NO_ID) return null;
7842                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7843            case FOCUS_DOWN:
7844                if (mNextFocusDownId == View.NO_ID) return null;
7845                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7846            case FOCUS_FORWARD:
7847                if (mNextFocusForwardId == View.NO_ID) return null;
7848                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7849            case FOCUS_BACKWARD: {
7850                if (mID == View.NO_ID) return null;
7851                final int id = mID;
7852                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7853                    @Override
7854                    public boolean apply(View t) {
7855                        return t.mNextFocusForwardId == id;
7856                    }
7857                });
7858            }
7859        }
7860        return null;
7861    }
7862
7863    private View findViewInsideOutShouldExist(View root, int id) {
7864        if (mMatchIdPredicate == null) {
7865            mMatchIdPredicate = new MatchIdPredicate();
7866        }
7867        mMatchIdPredicate.mId = id;
7868        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7869        if (result == null) {
7870            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7871        }
7872        return result;
7873    }
7874
7875    /**
7876     * Find and return all focusable views that are descendants of this view,
7877     * possibly including this view if it is focusable itself.
7878     *
7879     * @param direction The direction of the focus
7880     * @return A list of focusable views
7881     */
7882    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7883        ArrayList<View> result = new ArrayList<View>(24);
7884        addFocusables(result, direction);
7885        return result;
7886    }
7887
7888    /**
7889     * Add any focusable views that are descendants of this view (possibly
7890     * including this view if it is focusable itself) to views.  If we are in touch mode,
7891     * only add views that are also focusable in touch mode.
7892     *
7893     * @param views Focusable views found so far
7894     * @param direction The direction of the focus
7895     */
7896    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7897        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7898    }
7899
7900    /**
7901     * Adds any focusable views that are descendants of this view (possibly
7902     * including this view if it is focusable itself) to views. This method
7903     * adds all focusable views regardless if we are in touch mode or
7904     * only views focusable in touch mode if we are in touch mode or
7905     * only views that can take accessibility focus if accessibility is enabled
7906     * depending on the focusable mode parameter.
7907     *
7908     * @param views Focusable views found so far or null if all we are interested is
7909     *        the number of focusables.
7910     * @param direction The direction of the focus.
7911     * @param focusableMode The type of focusables to be added.
7912     *
7913     * @see #FOCUSABLES_ALL
7914     * @see #FOCUSABLES_TOUCH_MODE
7915     */
7916    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7917            @FocusableMode int focusableMode) {
7918        if (views == null) {
7919            return;
7920        }
7921        if (!isFocusable()) {
7922            return;
7923        }
7924        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7925                && isInTouchMode() && !isFocusableInTouchMode()) {
7926            return;
7927        }
7928        views.add(this);
7929    }
7930
7931    /**
7932     * Finds the Views that contain given text. The containment is case insensitive.
7933     * The search is performed by either the text that the View renders or the content
7934     * description that describes the view for accessibility purposes and the view does
7935     * not render or both. Clients can specify how the search is to be performed via
7936     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7937     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7938     *
7939     * @param outViews The output list of matching Views.
7940     * @param searched The text to match against.
7941     *
7942     * @see #FIND_VIEWS_WITH_TEXT
7943     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7944     * @see #setContentDescription(CharSequence)
7945     */
7946    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7947            @FindViewFlags int flags) {
7948        if (getAccessibilityNodeProvider() != null) {
7949            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7950                outViews.add(this);
7951            }
7952        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7953                && (searched != null && searched.length() > 0)
7954                && (mContentDescription != null && mContentDescription.length() > 0)) {
7955            String searchedLowerCase = searched.toString().toLowerCase();
7956            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7957            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7958                outViews.add(this);
7959            }
7960        }
7961    }
7962
7963    /**
7964     * Find and return all touchable views that are descendants of this view,
7965     * possibly including this view if it is touchable itself.
7966     *
7967     * @return A list of touchable views
7968     */
7969    public ArrayList<View> getTouchables() {
7970        ArrayList<View> result = new ArrayList<View>();
7971        addTouchables(result);
7972        return result;
7973    }
7974
7975    /**
7976     * Add any touchable views that are descendants of this view (possibly
7977     * including this view if it is touchable itself) to views.
7978     *
7979     * @param views Touchable views found so far
7980     */
7981    public void addTouchables(ArrayList<View> views) {
7982        final int viewFlags = mViewFlags;
7983
7984        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
7985                || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE)
7986                && (viewFlags & ENABLED_MASK) == ENABLED) {
7987            views.add(this);
7988        }
7989    }
7990
7991    /**
7992     * Returns whether this View is accessibility focused.
7993     *
7994     * @return True if this View is accessibility focused.
7995     */
7996    public boolean isAccessibilityFocused() {
7997        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7998    }
7999
8000    /**
8001     * Call this to try to give accessibility focus to this view.
8002     *
8003     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
8004     * returns false or the view is no visible or the view already has accessibility
8005     * focus.
8006     *
8007     * See also {@link #focusSearch(int)}, which is what you call to say that you
8008     * have focus, and you want your parent to look for the next one.
8009     *
8010     * @return Whether this view actually took accessibility focus.
8011     *
8012     * @hide
8013     */
8014    public boolean requestAccessibilityFocus() {
8015        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
8016        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
8017            return false;
8018        }
8019        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8020            return false;
8021        }
8022        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
8023            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
8024            ViewRootImpl viewRootImpl = getViewRootImpl();
8025            if (viewRootImpl != null) {
8026                viewRootImpl.setAccessibilityFocus(this, null);
8027            }
8028            invalidate();
8029            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
8030            return true;
8031        }
8032        return false;
8033    }
8034
8035    /**
8036     * Call this to try to clear accessibility focus of this view.
8037     *
8038     * See also {@link #focusSearch(int)}, which is what you call to say that you
8039     * have focus, and you want your parent to look for the next one.
8040     *
8041     * @hide
8042     */
8043    public void clearAccessibilityFocus() {
8044        clearAccessibilityFocusNoCallbacks();
8045        // Clear the global reference of accessibility focus if this
8046        // view or any of its descendants had accessibility focus.
8047        ViewRootImpl viewRootImpl = getViewRootImpl();
8048        if (viewRootImpl != null) {
8049            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
8050            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
8051                viewRootImpl.setAccessibilityFocus(null, null);
8052            }
8053        }
8054    }
8055
8056    private void sendAccessibilityHoverEvent(int eventType) {
8057        // Since we are not delivering to a client accessibility events from not
8058        // important views (unless the clinet request that) we need to fire the
8059        // event from the deepest view exposed to the client. As a consequence if
8060        // the user crosses a not exposed view the client will see enter and exit
8061        // of the exposed predecessor followed by and enter and exit of that same
8062        // predecessor when entering and exiting the not exposed descendant. This
8063        // is fine since the client has a clear idea which view is hovered at the
8064        // price of a couple more events being sent. This is a simple and
8065        // working solution.
8066        View source = this;
8067        while (true) {
8068            if (source.includeForAccessibility()) {
8069                source.sendAccessibilityEvent(eventType);
8070                return;
8071            }
8072            ViewParent parent = source.getParent();
8073            if (parent instanceof View) {
8074                source = (View) parent;
8075            } else {
8076                return;
8077            }
8078        }
8079    }
8080
8081    /**
8082     * Clears accessibility focus without calling any callback methods
8083     * normally invoked in {@link #clearAccessibilityFocus()}. This method
8084     * is used for clearing accessibility focus when giving this focus to
8085     * another view.
8086     */
8087    void clearAccessibilityFocusNoCallbacks() {
8088        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
8089            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
8090            invalidate();
8091            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
8092        }
8093    }
8094
8095    /**
8096     * Call this to try to give focus to a specific view or to one of its
8097     * descendants.
8098     *
8099     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8100     * false), or if it is focusable and it is not focusable in touch mode
8101     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8102     *
8103     * See also {@link #focusSearch(int)}, which is what you call to say that you
8104     * have focus, and you want your parent to look for the next one.
8105     *
8106     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
8107     * {@link #FOCUS_DOWN} and <code>null</code>.
8108     *
8109     * @return Whether this view or one of its descendants actually took focus.
8110     */
8111    public final boolean requestFocus() {
8112        return requestFocus(View.FOCUS_DOWN);
8113    }
8114
8115    /**
8116     * Call this to try to give focus to a specific view or to one of its
8117     * descendants and give it a hint about what direction focus is heading.
8118     *
8119     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8120     * false), or if it is focusable and it is not focusable in touch mode
8121     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8122     *
8123     * See also {@link #focusSearch(int)}, which is what you call to say that you
8124     * have focus, and you want your parent to look for the next one.
8125     *
8126     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
8127     * <code>null</code> set for the previously focused rectangle.
8128     *
8129     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8130     * @return Whether this view or one of its descendants actually took focus.
8131     */
8132    public final boolean requestFocus(int direction) {
8133        return requestFocus(direction, null);
8134    }
8135
8136    /**
8137     * Call this to try to give focus to a specific view or to one of its descendants
8138     * and give it hints about the direction and a specific rectangle that the focus
8139     * is coming from.  The rectangle can help give larger views a finer grained hint
8140     * about where focus is coming from, and therefore, where to show selection, or
8141     * forward focus change internally.
8142     *
8143     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
8144     * false), or if it is focusable and it is not focusable in touch mode
8145     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
8146     *
8147     * A View will not take focus if it is not visible.
8148     *
8149     * A View will not take focus if one of its parents has
8150     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
8151     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
8152     *
8153     * See also {@link #focusSearch(int)}, which is what you call to say that you
8154     * have focus, and you want your parent to look for the next one.
8155     *
8156     * You may wish to override this method if your custom {@link View} has an internal
8157     * {@link View} that it wishes to forward the request to.
8158     *
8159     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
8160     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
8161     *        to give a finer grained hint about where focus is coming from.  May be null
8162     *        if there is no hint.
8163     * @return Whether this view or one of its descendants actually took focus.
8164     */
8165    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
8166        return requestFocusNoSearch(direction, previouslyFocusedRect);
8167    }
8168
8169    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
8170        // need to be focusable
8171        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
8172                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
8173            return false;
8174        }
8175
8176        // need to be focusable in touch mode if in touch mode
8177        if (isInTouchMode() &&
8178            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
8179               return false;
8180        }
8181
8182        // need to not have any parents blocking us
8183        if (hasAncestorThatBlocksDescendantFocus()) {
8184            return false;
8185        }
8186
8187        handleFocusGainInternal(direction, previouslyFocusedRect);
8188        return true;
8189    }
8190
8191    /**
8192     * Call this to try to give focus to a specific view or to one of its descendants. This is a
8193     * special variant of {@link #requestFocus() } that will allow views that are not focusable in
8194     * touch mode to request focus when they are touched.
8195     *
8196     * @return Whether this view or one of its descendants actually took focus.
8197     *
8198     * @see #isInTouchMode()
8199     *
8200     */
8201    public final boolean requestFocusFromTouch() {
8202        // Leave touch mode if we need to
8203        if (isInTouchMode()) {
8204            ViewRootImpl viewRoot = getViewRootImpl();
8205            if (viewRoot != null) {
8206                viewRoot.ensureTouchMode(false);
8207            }
8208        }
8209        return requestFocus(View.FOCUS_DOWN);
8210    }
8211
8212    /**
8213     * @return Whether any ancestor of this view blocks descendant focus.
8214     */
8215    private boolean hasAncestorThatBlocksDescendantFocus() {
8216        final boolean focusableInTouchMode = isFocusableInTouchMode();
8217        ViewParent ancestor = mParent;
8218        while (ancestor instanceof ViewGroup) {
8219            final ViewGroup vgAncestor = (ViewGroup) ancestor;
8220            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
8221                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
8222                return true;
8223            } else {
8224                ancestor = vgAncestor.getParent();
8225            }
8226        }
8227        return false;
8228    }
8229
8230    /**
8231     * Gets the mode for determining whether this View is important for accessibility
8232     * which is if it fires accessibility events and if it is reported to
8233     * accessibility services that query the screen.
8234     *
8235     * @return The mode for determining whether a View is important for accessibility.
8236     *
8237     * @attr ref android.R.styleable#View_importantForAccessibility
8238     *
8239     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8240     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8241     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8242     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8243     */
8244    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
8245            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
8246            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
8247            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
8248            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
8249                    to = "noHideDescendants")
8250        })
8251    public int getImportantForAccessibility() {
8252        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8253                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8254    }
8255
8256    /**
8257     * Sets the live region mode for this view. This indicates to accessibility
8258     * services whether they should automatically notify the user about changes
8259     * to the view's content description or text, or to the content descriptions
8260     * or text of the view's children (where applicable).
8261     * <p>
8262     * For example, in a login screen with a TextView that displays an "incorrect
8263     * password" notification, that view should be marked as a live region with
8264     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8265     * <p>
8266     * To disable change notifications for this view, use
8267     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
8268     * mode for most views.
8269     * <p>
8270     * To indicate that the user should be notified of changes, use
8271     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
8272     * <p>
8273     * If the view's changes should interrupt ongoing speech and notify the user
8274     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
8275     *
8276     * @param mode The live region mode for this view, one of:
8277     *        <ul>
8278     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
8279     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
8280     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
8281     *        </ul>
8282     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8283     */
8284    public void setAccessibilityLiveRegion(int mode) {
8285        if (mode != getAccessibilityLiveRegion()) {
8286            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8287            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
8288                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
8289            notifyViewAccessibilityStateChangedIfNeeded(
8290                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8291        }
8292    }
8293
8294    /**
8295     * Gets the live region mode for this View.
8296     *
8297     * @return The live region mode for the view.
8298     *
8299     * @attr ref android.R.styleable#View_accessibilityLiveRegion
8300     *
8301     * @see #setAccessibilityLiveRegion(int)
8302     */
8303    public int getAccessibilityLiveRegion() {
8304        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
8305                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
8306    }
8307
8308    /**
8309     * Sets how to determine whether this view is important for accessibility
8310     * which is if it fires accessibility events and if it is reported to
8311     * accessibility services that query the screen.
8312     *
8313     * @param mode How to determine whether this view is important for accessibility.
8314     *
8315     * @attr ref android.R.styleable#View_importantForAccessibility
8316     *
8317     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
8318     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
8319     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
8320     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
8321     */
8322    public void setImportantForAccessibility(int mode) {
8323        final int oldMode = getImportantForAccessibility();
8324        if (mode != oldMode) {
8325            // If we're moving between AUTO and another state, we might not need
8326            // to send a subtree changed notification. We'll store the computed
8327            // importance, since we'll need to check it later to make sure.
8328            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
8329                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8330            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
8331            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8332            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
8333                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
8334            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
8335                notifySubtreeAccessibilityStateChangedIfNeeded();
8336            } else {
8337                notifyViewAccessibilityStateChangedIfNeeded(
8338                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8339            }
8340        }
8341    }
8342
8343    /**
8344     * Computes whether this view should be exposed for accessibility. In
8345     * general, views that are interactive or provide information are exposed
8346     * while views that serve only as containers are hidden.
8347     * <p>
8348     * If an ancestor of this view has importance
8349     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
8350     * returns <code>false</code>.
8351     * <p>
8352     * Otherwise, the value is computed according to the view's
8353     * {@link #getImportantForAccessibility()} value:
8354     * <ol>
8355     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
8356     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
8357     * </code>
8358     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
8359     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
8360     * view satisfies any of the following:
8361     * <ul>
8362     * <li>Is actionable, e.g. {@link #isClickable()},
8363     * {@link #isLongClickable()}, or {@link #isFocusable()}
8364     * <li>Has an {@link AccessibilityDelegate}
8365     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
8366     * {@link OnKeyListener}, etc.
8367     * <li>Is an accessibility live region, e.g.
8368     * {@link #getAccessibilityLiveRegion()} is not
8369     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
8370     * </ul>
8371     * </ol>
8372     *
8373     * @return Whether the view is exposed for accessibility.
8374     * @see #setImportantForAccessibility(int)
8375     * @see #getImportantForAccessibility()
8376     */
8377    public boolean isImportantForAccessibility() {
8378        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
8379                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
8380        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
8381                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8382            return false;
8383        }
8384
8385        // Check parent mode to ensure we're not hidden.
8386        ViewParent parent = mParent;
8387        while (parent instanceof View) {
8388            if (((View) parent).getImportantForAccessibility()
8389                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
8390                return false;
8391            }
8392            parent = parent.getParent();
8393        }
8394
8395        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
8396                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
8397                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
8398    }
8399
8400    /**
8401     * Gets the parent for accessibility purposes. Note that the parent for
8402     * accessibility is not necessary the immediate parent. It is the first
8403     * predecessor that is important for accessibility.
8404     *
8405     * @return The parent for accessibility purposes.
8406     */
8407    public ViewParent getParentForAccessibility() {
8408        if (mParent instanceof View) {
8409            View parentView = (View) mParent;
8410            if (parentView.includeForAccessibility()) {
8411                return mParent;
8412            } else {
8413                return mParent.getParentForAccessibility();
8414            }
8415        }
8416        return null;
8417    }
8418
8419    /**
8420     * Adds the children of a given View for accessibility. Since some Views are
8421     * not important for accessibility the children for accessibility are not
8422     * necessarily direct children of the view, rather they are the first level of
8423     * descendants important for accessibility.
8424     *
8425     * @param children The list of children for accessibility.
8426     */
8427    public void addChildrenForAccessibility(ArrayList<View> children) {
8428
8429    }
8430
8431    /**
8432     * Whether to regard this view for accessibility. A view is regarded for
8433     * accessibility if it is important for accessibility or the querying
8434     * accessibility service has explicitly requested that view not
8435     * important for accessibility are regarded.
8436     *
8437     * @return Whether to regard the view for accessibility.
8438     *
8439     * @hide
8440     */
8441    public boolean includeForAccessibility() {
8442        if (mAttachInfo != null) {
8443            return (mAttachInfo.mAccessibilityFetchFlags
8444                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
8445                    || isImportantForAccessibility();
8446        }
8447        return false;
8448    }
8449
8450    /**
8451     * Returns whether the View is considered actionable from
8452     * accessibility perspective. Such view are important for
8453     * accessibility.
8454     *
8455     * @return True if the view is actionable for accessibility.
8456     *
8457     * @hide
8458     */
8459    public boolean isActionableForAccessibility() {
8460        return (isClickable() || isLongClickable() || isFocusable());
8461    }
8462
8463    /**
8464     * Returns whether the View has registered callbacks which makes it
8465     * important for accessibility.
8466     *
8467     * @return True if the view is actionable for accessibility.
8468     */
8469    private boolean hasListenersForAccessibility() {
8470        ListenerInfo info = getListenerInfo();
8471        return mTouchDelegate != null || info.mOnKeyListener != null
8472                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
8473                || info.mOnHoverListener != null || info.mOnDragListener != null;
8474    }
8475
8476    /**
8477     * Notifies that the accessibility state of this view changed. The change
8478     * is local to this view and does not represent structural changes such
8479     * as children and parent. For example, the view became focusable. The
8480     * notification is at at most once every
8481     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8482     * to avoid unnecessary load to the system. Also once a view has a pending
8483     * notification this method is a NOP until the notification has been sent.
8484     *
8485     * @hide
8486     */
8487    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
8488        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8489            return;
8490        }
8491        if (mSendViewStateChangedAccessibilityEvent == null) {
8492            mSendViewStateChangedAccessibilityEvent =
8493                    new SendViewStateChangedAccessibilityEvent();
8494        }
8495        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
8496    }
8497
8498    /**
8499     * Notifies that the accessibility state of this view changed. The change
8500     * is *not* local to this view and does represent structural changes such
8501     * as children and parent. For example, the view size changed. The
8502     * notification is at at most once every
8503     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
8504     * to avoid unnecessary load to the system. Also once a view has a pending
8505     * notification this method is a NOP until the notification has been sent.
8506     *
8507     * @hide
8508     */
8509    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
8510        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
8511            return;
8512        }
8513        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
8514            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8515            if (mParent != null) {
8516                try {
8517                    mParent.notifySubtreeAccessibilityStateChanged(
8518                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
8519                } catch (AbstractMethodError e) {
8520                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
8521                            " does not fully implement ViewParent", e);
8522                }
8523            }
8524        }
8525    }
8526
8527    /**
8528     * Reset the flag indicating the accessibility state of the subtree rooted
8529     * at this view changed.
8530     */
8531    void resetSubtreeAccessibilityStateChanged() {
8532        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
8533    }
8534
8535    /**
8536     * Report an accessibility action to this view's parents for delegated processing.
8537     *
8538     * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally
8539     * call this method to delegate an accessibility action to a supporting parent. If the parent
8540     * returns true from its
8541     * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)}
8542     * method this method will return true to signify that the action was consumed.</p>
8543     *
8544     * <p>This method is useful for implementing nested scrolling child views. If
8545     * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action
8546     * a custom view implementation may invoke this method to allow a parent to consume the
8547     * scroll first. If this method returns true the custom view should skip its own scrolling
8548     * behavior.</p>
8549     *
8550     * @param action Accessibility action to delegate
8551     * @param arguments Optional action arguments
8552     * @return true if the action was consumed by a parent
8553     */
8554    public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) {
8555        for (ViewParent p = getParent(); p != null; p = p.getParent()) {
8556            if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) {
8557                return true;
8558            }
8559        }
8560        return false;
8561    }
8562
8563    /**
8564     * Performs the specified accessibility action on the view. For
8565     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
8566     * <p>
8567     * If an {@link AccessibilityDelegate} has been specified via calling
8568     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
8569     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
8570     * is responsible for handling this call.
8571     * </p>
8572     *
8573     * <p>The default implementation will delegate
8574     * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and
8575     * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if
8576     * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p>
8577     *
8578     * @param action The action to perform.
8579     * @param arguments Optional action arguments.
8580     * @return Whether the action was performed.
8581     */
8582    public boolean performAccessibilityAction(int action, Bundle arguments) {
8583      if (mAccessibilityDelegate != null) {
8584          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
8585      } else {
8586          return performAccessibilityActionInternal(action, arguments);
8587      }
8588    }
8589
8590   /**
8591    * @see #performAccessibilityAction(int, Bundle)
8592    *
8593    * Note: Called from the default {@link AccessibilityDelegate}.
8594    *
8595    * @hide
8596    */
8597    public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
8598        if (isNestedScrollingEnabled()
8599                && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
8600                || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
8601                || action == R.id.accessibilityActionScrollUp
8602                || action == R.id.accessibilityActionScrollLeft
8603                || action == R.id.accessibilityActionScrollDown
8604                || action == R.id.accessibilityActionScrollRight)) {
8605            if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) {
8606                return true;
8607            }
8608        }
8609
8610        switch (action) {
8611            case AccessibilityNodeInfo.ACTION_CLICK: {
8612                if (isClickable()) {
8613                    performClick();
8614                    return true;
8615                }
8616            } break;
8617            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
8618                if (isLongClickable()) {
8619                    performLongClick();
8620                    return true;
8621                }
8622            } break;
8623            case AccessibilityNodeInfo.ACTION_FOCUS: {
8624                if (!hasFocus()) {
8625                    // Get out of touch mode since accessibility
8626                    // wants to move focus around.
8627                    getViewRootImpl().ensureTouchMode(false);
8628                    return requestFocus();
8629                }
8630            } break;
8631            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
8632                if (hasFocus()) {
8633                    clearFocus();
8634                    return !isFocused();
8635                }
8636            } break;
8637            case AccessibilityNodeInfo.ACTION_SELECT: {
8638                if (!isSelected()) {
8639                    setSelected(true);
8640                    return isSelected();
8641                }
8642            } break;
8643            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
8644                if (isSelected()) {
8645                    setSelected(false);
8646                    return !isSelected();
8647                }
8648            } break;
8649            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
8650                if (!isAccessibilityFocused()) {
8651                    return requestAccessibilityFocus();
8652                }
8653            } break;
8654            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
8655                if (isAccessibilityFocused()) {
8656                    clearAccessibilityFocus();
8657                    return true;
8658                }
8659            } break;
8660            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
8661                if (arguments != null) {
8662                    final int granularity = arguments.getInt(
8663                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8664                    final boolean extendSelection = arguments.getBoolean(
8665                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8666                    return traverseAtGranularity(granularity, true, extendSelection);
8667                }
8668            } break;
8669            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
8670                if (arguments != null) {
8671                    final int granularity = arguments.getInt(
8672                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
8673                    final boolean extendSelection = arguments.getBoolean(
8674                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
8675                    return traverseAtGranularity(granularity, false, extendSelection);
8676                }
8677            } break;
8678            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
8679                CharSequence text = getIterableTextForAccessibility();
8680                if (text == null) {
8681                    return false;
8682                }
8683                final int start = (arguments != null) ? arguments.getInt(
8684                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
8685                final int end = (arguments != null) ? arguments.getInt(
8686                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
8687                // Only cursor position can be specified (selection length == 0)
8688                if ((getAccessibilitySelectionStart() != start
8689                        || getAccessibilitySelectionEnd() != end)
8690                        && (start == end)) {
8691                    setAccessibilitySelection(start, end);
8692                    notifyViewAccessibilityStateChangedIfNeeded(
8693                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
8694                    return true;
8695                }
8696            } break;
8697            case R.id.accessibilityActionShowOnScreen: {
8698                if (mAttachInfo != null) {
8699                    final Rect r = mAttachInfo.mTmpInvalRect;
8700                    getDrawingRect(r);
8701                    return requestRectangleOnScreen(r, true);
8702                }
8703            } break;
8704            case R.id.accessibilityActionStylusButtonPress: {
8705                if (isStylusButtonPressable()) {
8706                    performStylusButtonPress();
8707                    return true;
8708                }
8709            } break;
8710        }
8711        return false;
8712    }
8713
8714    private boolean traverseAtGranularity(int granularity, boolean forward,
8715            boolean extendSelection) {
8716        CharSequence text = getIterableTextForAccessibility();
8717        if (text == null || text.length() == 0) {
8718            return false;
8719        }
8720        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
8721        if (iterator == null) {
8722            return false;
8723        }
8724        int current = getAccessibilitySelectionEnd();
8725        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8726            current = forward ? 0 : text.length();
8727        }
8728        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
8729        if (range == null) {
8730            return false;
8731        }
8732        final int segmentStart = range[0];
8733        final int segmentEnd = range[1];
8734        int selectionStart;
8735        int selectionEnd;
8736        if (extendSelection && isAccessibilitySelectionExtendable()) {
8737            selectionStart = getAccessibilitySelectionStart();
8738            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
8739                selectionStart = forward ? segmentStart : segmentEnd;
8740            }
8741            selectionEnd = forward ? segmentEnd : segmentStart;
8742        } else {
8743            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
8744        }
8745        setAccessibilitySelection(selectionStart, selectionEnd);
8746        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
8747                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
8748        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
8749        return true;
8750    }
8751
8752    /**
8753     * Gets the text reported for accessibility purposes.
8754     *
8755     * @return The accessibility text.
8756     *
8757     * @hide
8758     */
8759    public CharSequence getIterableTextForAccessibility() {
8760        return getContentDescription();
8761    }
8762
8763    /**
8764     * Gets whether accessibility selection can be extended.
8765     *
8766     * @return If selection is extensible.
8767     *
8768     * @hide
8769     */
8770    public boolean isAccessibilitySelectionExtendable() {
8771        return false;
8772    }
8773
8774    /**
8775     * @hide
8776     */
8777    public int getAccessibilitySelectionStart() {
8778        return mAccessibilityCursorPosition;
8779    }
8780
8781    /**
8782     * @hide
8783     */
8784    public int getAccessibilitySelectionEnd() {
8785        return getAccessibilitySelectionStart();
8786    }
8787
8788    /**
8789     * @hide
8790     */
8791    public void setAccessibilitySelection(int start, int end) {
8792        if (start ==  end && end == mAccessibilityCursorPosition) {
8793            return;
8794        }
8795        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8796            mAccessibilityCursorPosition = start;
8797        } else {
8798            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8799        }
8800        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8801    }
8802
8803    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8804            int fromIndex, int toIndex) {
8805        if (mParent == null) {
8806            return;
8807        }
8808        AccessibilityEvent event = AccessibilityEvent.obtain(
8809                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8810        onInitializeAccessibilityEvent(event);
8811        onPopulateAccessibilityEvent(event);
8812        event.setFromIndex(fromIndex);
8813        event.setToIndex(toIndex);
8814        event.setAction(action);
8815        event.setMovementGranularity(granularity);
8816        mParent.requestSendAccessibilityEvent(this, event);
8817    }
8818
8819    /**
8820     * @hide
8821     */
8822    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8823        switch (granularity) {
8824            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8825                CharSequence text = getIterableTextForAccessibility();
8826                if (text != null && text.length() > 0) {
8827                    CharacterTextSegmentIterator iterator =
8828                        CharacterTextSegmentIterator.getInstance(
8829                                mContext.getResources().getConfiguration().locale);
8830                    iterator.initialize(text.toString());
8831                    return iterator;
8832                }
8833            } break;
8834            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8835                CharSequence text = getIterableTextForAccessibility();
8836                if (text != null && text.length() > 0) {
8837                    WordTextSegmentIterator iterator =
8838                        WordTextSegmentIterator.getInstance(
8839                                mContext.getResources().getConfiguration().locale);
8840                    iterator.initialize(text.toString());
8841                    return iterator;
8842                }
8843            } break;
8844            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8845                CharSequence text = getIterableTextForAccessibility();
8846                if (text != null && text.length() > 0) {
8847                    ParagraphTextSegmentIterator iterator =
8848                        ParagraphTextSegmentIterator.getInstance();
8849                    iterator.initialize(text.toString());
8850                    return iterator;
8851                }
8852            } break;
8853        }
8854        return null;
8855    }
8856
8857    /**
8858     * @hide
8859     */
8860    public void dispatchStartTemporaryDetach() {
8861        onStartTemporaryDetach();
8862    }
8863
8864    /**
8865     * This is called when a container is going to temporarily detach a child, with
8866     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8867     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8868     * {@link #onDetachedFromWindow()} when the container is done.
8869     */
8870    public void onStartTemporaryDetach() {
8871        removeUnsetPressCallback();
8872        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8873    }
8874
8875    /**
8876     * @hide
8877     */
8878    public void dispatchFinishTemporaryDetach() {
8879        onFinishTemporaryDetach();
8880    }
8881
8882    /**
8883     * Called after {@link #onStartTemporaryDetach} when the container is done
8884     * changing the view.
8885     */
8886    public void onFinishTemporaryDetach() {
8887    }
8888
8889    /**
8890     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8891     * for this view's window.  Returns null if the view is not currently attached
8892     * to the window.  Normally you will not need to use this directly, but
8893     * just use the standard high-level event callbacks like
8894     * {@link #onKeyDown(int, KeyEvent)}.
8895     */
8896    public KeyEvent.DispatcherState getKeyDispatcherState() {
8897        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8898    }
8899
8900    /**
8901     * Dispatch a key event before it is processed by any input method
8902     * associated with the view hierarchy.  This can be used to intercept
8903     * key events in special situations before the IME consumes them; a
8904     * typical example would be handling the BACK key to update the application's
8905     * UI instead of allowing the IME to see it and close itself.
8906     *
8907     * @param event The key event to be dispatched.
8908     * @return True if the event was handled, false otherwise.
8909     */
8910    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8911        return onKeyPreIme(event.getKeyCode(), event);
8912    }
8913
8914    /**
8915     * Dispatch a key event to the next view on the focus path. This path runs
8916     * from the top of the view tree down to the currently focused view. If this
8917     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8918     * the next node down the focus path. This method also fires any key
8919     * listeners.
8920     *
8921     * @param event The key event to be dispatched.
8922     * @return True if the event was handled, false otherwise.
8923     */
8924    public boolean dispatchKeyEvent(KeyEvent event) {
8925        if (mInputEventConsistencyVerifier != null) {
8926            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8927        }
8928
8929        // Give any attached key listener a first crack at the event.
8930        //noinspection SimplifiableIfStatement
8931        ListenerInfo li = mListenerInfo;
8932        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8933                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8934            return true;
8935        }
8936
8937        if (event.dispatch(this, mAttachInfo != null
8938                ? mAttachInfo.mKeyDispatchState : null, this)) {
8939            return true;
8940        }
8941
8942        if (mInputEventConsistencyVerifier != null) {
8943            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8944        }
8945        return false;
8946    }
8947
8948    /**
8949     * Dispatches a key shortcut event.
8950     *
8951     * @param event The key event to be dispatched.
8952     * @return True if the event was handled by the view, false otherwise.
8953     */
8954    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8955        return onKeyShortcut(event.getKeyCode(), event);
8956    }
8957
8958    /**
8959     * Pass the touch screen motion event down to the target view, or this
8960     * view if it is the target.
8961     *
8962     * @param event The motion event to be dispatched.
8963     * @return True if the event was handled by the view, false otherwise.
8964     */
8965    public boolean dispatchTouchEvent(MotionEvent event) {
8966        // If the event should be handled by accessibility focus first.
8967        if (event.isTargetAccessibilityFocus()) {
8968            // We don't have focus or no virtual descendant has it, do not handle the event.
8969            if (!isAccessibilityFocusedViewOrHost()) {
8970                return false;
8971            }
8972            // We have focus and got the event, then use normal event dispatch.
8973            event.setTargetAccessibilityFocus(false);
8974        }
8975
8976        boolean result = false;
8977
8978        if (mInputEventConsistencyVerifier != null) {
8979            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8980        }
8981
8982        final int actionMasked = event.getActionMasked();
8983        if (actionMasked == MotionEvent.ACTION_DOWN) {
8984            // Defensive cleanup for new gesture
8985            stopNestedScroll();
8986        }
8987
8988        if (onFilterTouchEventForSecurity(event)) {
8989            //noinspection SimplifiableIfStatement
8990            ListenerInfo li = mListenerInfo;
8991            if (li != null && li.mOnTouchListener != null
8992                    && (mViewFlags & ENABLED_MASK) == ENABLED
8993                    && li.mOnTouchListener.onTouch(this, event)) {
8994                result = true;
8995            }
8996
8997            if (!result && onTouchEvent(event)) {
8998                result = true;
8999            }
9000        }
9001
9002        if (!result && mInputEventConsistencyVerifier != null) {
9003            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9004        }
9005
9006        // Clean up after nested scrolls if this is the end of a gesture;
9007        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
9008        // of the gesture.
9009        if (actionMasked == MotionEvent.ACTION_UP ||
9010                actionMasked == MotionEvent.ACTION_CANCEL ||
9011                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
9012            stopNestedScroll();
9013        }
9014
9015        return result;
9016    }
9017
9018    boolean isAccessibilityFocusedViewOrHost() {
9019        return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl()
9020                .getAccessibilityFocusedHost() == this);
9021    }
9022
9023    /**
9024     * Filter the touch event to apply security policies.
9025     *
9026     * @param event The motion event to be filtered.
9027     * @return True if the event should be dispatched, false if the event should be dropped.
9028     *
9029     * @see #getFilterTouchesWhenObscured
9030     */
9031    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
9032        //noinspection RedundantIfStatement
9033        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
9034                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
9035            // Window is obscured, drop this touch.
9036            return false;
9037        }
9038        return true;
9039    }
9040
9041    /**
9042     * Pass a trackball motion event down to the focused view.
9043     *
9044     * @param event The motion event to be dispatched.
9045     * @return True if the event was handled by the view, false otherwise.
9046     */
9047    public boolean dispatchTrackballEvent(MotionEvent event) {
9048        if (mInputEventConsistencyVerifier != null) {
9049            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
9050        }
9051
9052        return onTrackballEvent(event);
9053    }
9054
9055    /**
9056     * Dispatch a generic motion event.
9057     * <p>
9058     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9059     * are delivered to the view under the pointer.  All other generic motion events are
9060     * delivered to the focused view.  Hover events are handled specially and are delivered
9061     * to {@link #onHoverEvent(MotionEvent)}.
9062     * </p>
9063     *
9064     * @param event The motion event to be dispatched.
9065     * @return True if the event was handled by the view, false otherwise.
9066     */
9067    public boolean dispatchGenericMotionEvent(MotionEvent event) {
9068        if (mInputEventConsistencyVerifier != null) {
9069            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
9070        }
9071
9072        final int source = event.getSource();
9073        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
9074            final int action = event.getAction();
9075            if (action == MotionEvent.ACTION_HOVER_ENTER
9076                    || action == MotionEvent.ACTION_HOVER_MOVE
9077                    || action == MotionEvent.ACTION_HOVER_EXIT) {
9078                if (dispatchHoverEvent(event)) {
9079                    return true;
9080                }
9081            } else if (dispatchGenericPointerEvent(event)) {
9082                return true;
9083            }
9084        } else if (dispatchGenericFocusedEvent(event)) {
9085            return true;
9086        }
9087
9088        if (dispatchGenericMotionEventInternal(event)) {
9089            return true;
9090        }
9091
9092        if (mInputEventConsistencyVerifier != null) {
9093            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9094        }
9095        return false;
9096    }
9097
9098    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
9099        //noinspection SimplifiableIfStatement
9100        ListenerInfo li = mListenerInfo;
9101        if (li != null && li.mOnGenericMotionListener != null
9102                && (mViewFlags & ENABLED_MASK) == ENABLED
9103                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
9104            return true;
9105        }
9106
9107        if (onGenericMotionEvent(event)) {
9108            return true;
9109        }
9110
9111        if (mInputEventConsistencyVerifier != null) {
9112            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
9113        }
9114        return false;
9115    }
9116
9117    /**
9118     * Dispatch a hover event.
9119     * <p>
9120     * Do not call this method directly.
9121     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9122     * </p>
9123     *
9124     * @param event The motion event to be dispatched.
9125     * @return True if the event was handled by the view, false otherwise.
9126     */
9127    protected boolean dispatchHoverEvent(MotionEvent event) {
9128        ListenerInfo li = mListenerInfo;
9129        //noinspection SimplifiableIfStatement
9130        if (li != null && li.mOnHoverListener != null
9131                && (mViewFlags & ENABLED_MASK) == ENABLED
9132                && li.mOnHoverListener.onHover(this, event)) {
9133            return true;
9134        }
9135
9136        return onHoverEvent(event);
9137    }
9138
9139    /**
9140     * Returns true if the view has a child to which it has recently sent
9141     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
9142     * it does not have a hovered child, then it must be the innermost hovered view.
9143     * @hide
9144     */
9145    protected boolean hasHoveredChild() {
9146        return false;
9147    }
9148
9149    /**
9150     * Dispatch a generic motion event to the view under the first pointer.
9151     * <p>
9152     * Do not call this method directly.
9153     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9154     * </p>
9155     *
9156     * @param event The motion event to be dispatched.
9157     * @return True if the event was handled by the view, false otherwise.
9158     */
9159    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
9160        return false;
9161    }
9162
9163    /**
9164     * Dispatch a generic motion event to the currently focused view.
9165     * <p>
9166     * Do not call this method directly.
9167     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
9168     * </p>
9169     *
9170     * @param event The motion event to be dispatched.
9171     * @return True if the event was handled by the view, false otherwise.
9172     */
9173    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
9174        return false;
9175    }
9176
9177    /**
9178     * Dispatch a pointer event.
9179     * <p>
9180     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
9181     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
9182     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
9183     * and should not be expected to handle other pointing device features.
9184     * </p>
9185     *
9186     * @param event The motion event to be dispatched.
9187     * @return True if the event was handled by the view, false otherwise.
9188     * @hide
9189     */
9190    public final boolean dispatchPointerEvent(MotionEvent event) {
9191        if (event.isTouchEvent()) {
9192            return dispatchTouchEvent(event);
9193        } else {
9194            return dispatchGenericMotionEvent(event);
9195        }
9196    }
9197
9198    /**
9199     * Called when the window containing this view gains or loses window focus.
9200     * ViewGroups should override to route to their children.
9201     *
9202     * @param hasFocus True if the window containing this view now has focus,
9203     *        false otherwise.
9204     */
9205    public void dispatchWindowFocusChanged(boolean hasFocus) {
9206        onWindowFocusChanged(hasFocus);
9207    }
9208
9209    /**
9210     * Called when the window containing this view gains or loses focus.  Note
9211     * that this is separate from view focus: to receive key events, both
9212     * your view and its window must have focus.  If a window is displayed
9213     * on top of yours that takes input focus, then your own window will lose
9214     * focus but the view focus will remain unchanged.
9215     *
9216     * @param hasWindowFocus True if the window containing this view now has
9217     *        focus, false otherwise.
9218     */
9219    public void onWindowFocusChanged(boolean hasWindowFocus) {
9220        InputMethodManager imm = InputMethodManager.peekInstance();
9221        if (!hasWindowFocus) {
9222            if (isPressed()) {
9223                setPressed(false);
9224            }
9225            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9226                imm.focusOut(this);
9227            }
9228            removeLongPressCallback();
9229            removeTapCallback();
9230            onFocusLost();
9231        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
9232            imm.focusIn(this);
9233        }
9234        refreshDrawableState();
9235    }
9236
9237    /**
9238     * Returns true if this view is in a window that currently has window focus.
9239     * Note that this is not the same as the view itself having focus.
9240     *
9241     * @return True if this view is in a window that currently has window focus.
9242     */
9243    public boolean hasWindowFocus() {
9244        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
9245    }
9246
9247    /**
9248     * Dispatch a view visibility change down the view hierarchy.
9249     * ViewGroups should override to route to their children.
9250     * @param changedView The view whose visibility changed. Could be 'this' or
9251     * an ancestor view.
9252     * @param visibility The new visibility of changedView: {@link #VISIBLE},
9253     * {@link #INVISIBLE} or {@link #GONE}.
9254     */
9255    protected void dispatchVisibilityChanged(@NonNull View changedView,
9256            @Visibility int visibility) {
9257        onVisibilityChanged(changedView, visibility);
9258    }
9259
9260    /**
9261     * Called when the visibility of the view or an ancestor of the view has
9262     * changed.
9263     *
9264     * @param changedView The view whose visibility changed. May be
9265     *                    {@code this} or an ancestor view.
9266     * @param visibility The new visibility, one of {@link #VISIBLE},
9267     *                   {@link #INVISIBLE} or {@link #GONE}.
9268     */
9269    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
9270        final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE;
9271        if (visible) {
9272            if (mAttachInfo != null) {
9273                initialAwakenScrollBars();
9274            } else {
9275                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
9276            }
9277        }
9278
9279        final Drawable dr = mBackground;
9280        if (dr != null && visible != dr.isVisible()) {
9281            dr.setVisible(visible, false);
9282        }
9283        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
9284        if (fg != null && visible != fg.isVisible()) {
9285            fg.setVisible(visible, false);
9286        }
9287    }
9288
9289    /**
9290     * Dispatch a hint about whether this view is displayed. For instance, when
9291     * a View moves out of the screen, it might receives a display hint indicating
9292     * the view is not displayed. Applications should not <em>rely</em> on this hint
9293     * as there is no guarantee that they will receive one.
9294     *
9295     * @param hint A hint about whether or not this view is displayed:
9296     * {@link #VISIBLE} or {@link #INVISIBLE}.
9297     */
9298    public void dispatchDisplayHint(@Visibility int hint) {
9299        onDisplayHint(hint);
9300    }
9301
9302    /**
9303     * Gives this view a hint about whether is displayed or not. For instance, when
9304     * a View moves out of the screen, it might receives a display hint indicating
9305     * the view is not displayed. Applications should not <em>rely</em> on this hint
9306     * as there is no guarantee that they will receive one.
9307     *
9308     * @param hint A hint about whether or not this view is displayed:
9309     * {@link #VISIBLE} or {@link #INVISIBLE}.
9310     */
9311    protected void onDisplayHint(@Visibility int hint) {
9312    }
9313
9314    /**
9315     * Dispatch a window visibility change down the view hierarchy.
9316     * ViewGroups should override to route to their children.
9317     *
9318     * @param visibility The new visibility of the window.
9319     *
9320     * @see #onWindowVisibilityChanged(int)
9321     */
9322    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
9323        onWindowVisibilityChanged(visibility);
9324    }
9325
9326    /**
9327     * Called when the window containing has change its visibility
9328     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
9329     * that this tells you whether or not your window is being made visible
9330     * to the window manager; this does <em>not</em> tell you whether or not
9331     * your window is obscured by other windows on the screen, even if it
9332     * is itself visible.
9333     *
9334     * @param visibility The new visibility of the window.
9335     */
9336    protected void onWindowVisibilityChanged(@Visibility int visibility) {
9337        if (visibility == VISIBLE) {
9338            initialAwakenScrollBars();
9339        }
9340    }
9341
9342    /**
9343     * Returns the current visibility of the window this view is attached to
9344     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
9345     *
9346     * @return Returns the current visibility of the view's window.
9347     */
9348    @Visibility
9349    public int getWindowVisibility() {
9350        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
9351    }
9352
9353    /**
9354     * Retrieve the overall visible display size in which the window this view is
9355     * attached to has been positioned in.  This takes into account screen
9356     * decorations above the window, for both cases where the window itself
9357     * is being position inside of them or the window is being placed under
9358     * then and covered insets are used for the window to position its content
9359     * inside.  In effect, this tells you the available area where content can
9360     * be placed and remain visible to users.
9361     *
9362     * <p>This function requires an IPC back to the window manager to retrieve
9363     * the requested information, so should not be used in performance critical
9364     * code like drawing.
9365     *
9366     * @param outRect Filled in with the visible display frame.  If the view
9367     * is not attached to a window, this is simply the raw display size.
9368     */
9369    public void getWindowVisibleDisplayFrame(Rect outRect) {
9370        if (mAttachInfo != null) {
9371            try {
9372                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
9373            } catch (RemoteException e) {
9374                return;
9375            }
9376            // XXX This is really broken, and probably all needs to be done
9377            // in the window manager, and we need to know more about whether
9378            // we want the area behind or in front of the IME.
9379            final Rect insets = mAttachInfo.mVisibleInsets;
9380            outRect.left += insets.left;
9381            outRect.top += insets.top;
9382            outRect.right -= insets.right;
9383            outRect.bottom -= insets.bottom;
9384            return;
9385        }
9386        // The view is not attached to a display so we don't have a context.
9387        // Make a best guess about the display size.
9388        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
9389        d.getRectSize(outRect);
9390    }
9391
9392    /**
9393     * Dispatch a notification about a resource configuration change down
9394     * the view hierarchy.
9395     * ViewGroups should override to route to their children.
9396     *
9397     * @param newConfig The new resource configuration.
9398     *
9399     * @see #onConfigurationChanged(android.content.res.Configuration)
9400     */
9401    public void dispatchConfigurationChanged(Configuration newConfig) {
9402        onConfigurationChanged(newConfig);
9403    }
9404
9405    /**
9406     * Called when the current configuration of the resources being used
9407     * by the application have changed.  You can use this to decide when
9408     * to reload resources that can changed based on orientation and other
9409     * configuration characteristics.  You only need to use this if you are
9410     * not relying on the normal {@link android.app.Activity} mechanism of
9411     * recreating the activity instance upon a configuration change.
9412     *
9413     * @param newConfig The new resource configuration.
9414     */
9415    protected void onConfigurationChanged(Configuration newConfig) {
9416    }
9417
9418    /**
9419     * Private function to aggregate all per-view attributes in to the view
9420     * root.
9421     */
9422    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9423        performCollectViewAttributes(attachInfo, visibility);
9424    }
9425
9426    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
9427        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
9428            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
9429                attachInfo.mKeepScreenOn = true;
9430            }
9431            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
9432            ListenerInfo li = mListenerInfo;
9433            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
9434                attachInfo.mHasSystemUiListeners = true;
9435            }
9436        }
9437    }
9438
9439    void needGlobalAttributesUpdate(boolean force) {
9440        final AttachInfo ai = mAttachInfo;
9441        if (ai != null && !ai.mRecomputeGlobalAttributes) {
9442            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
9443                    || ai.mHasSystemUiListeners) {
9444                ai.mRecomputeGlobalAttributes = true;
9445            }
9446        }
9447    }
9448
9449    /**
9450     * Returns whether the device is currently in touch mode.  Touch mode is entered
9451     * once the user begins interacting with the device by touch, and affects various
9452     * things like whether focus is always visible to the user.
9453     *
9454     * @return Whether the device is in touch mode.
9455     */
9456    @ViewDebug.ExportedProperty
9457    public boolean isInTouchMode() {
9458        if (mAttachInfo != null) {
9459            return mAttachInfo.mInTouchMode;
9460        } else {
9461            return ViewRootImpl.isInTouchMode();
9462        }
9463    }
9464
9465    /**
9466     * Returns the context the view is running in, through which it can
9467     * access the current theme, resources, etc.
9468     *
9469     * @return The view's Context.
9470     */
9471    @ViewDebug.CapturedViewProperty
9472    public final Context getContext() {
9473        return mContext;
9474    }
9475
9476    /**
9477     * Handle a key event before it is processed by any input method
9478     * associated with the view hierarchy.  This can be used to intercept
9479     * key events in special situations before the IME consumes them; a
9480     * typical example would be handling the BACK key to update the application's
9481     * UI instead of allowing the IME to see it and close itself.
9482     *
9483     * @param keyCode The value in event.getKeyCode().
9484     * @param event Description of the key event.
9485     * @return If you handled the event, return true. If you want to allow the
9486     *         event to be handled by the next receiver, return false.
9487     */
9488    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
9489        return false;
9490    }
9491
9492    /**
9493     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
9494     * KeyEvent.Callback.onKeyDown()}: perform press of the view
9495     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
9496     * is released, if the view is enabled and clickable.
9497     *
9498     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9499     * although some may elect to do so in some situations. Do not rely on this to
9500     * catch software key presses.
9501     *
9502     * @param keyCode A key code that represents the button pressed, from
9503     *                {@link android.view.KeyEvent}.
9504     * @param event   The KeyEvent object that defines the button action.
9505     */
9506    public boolean onKeyDown(int keyCode, KeyEvent event) {
9507        boolean result = false;
9508
9509        if (KeyEvent.isConfirmKey(keyCode)) {
9510            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9511                return true;
9512            }
9513            // Long clickable items don't necessarily have to be clickable
9514            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
9515                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
9516                    (event.getRepeatCount() == 0)) {
9517                setPressed(true);
9518                checkForLongClick(0);
9519                return true;
9520            }
9521        }
9522        return result;
9523    }
9524
9525    /**
9526     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
9527     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
9528     * the event).
9529     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9530     * although some may elect to do so in some situations. Do not rely on this to
9531     * catch software key presses.
9532     */
9533    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
9534        return false;
9535    }
9536
9537    /**
9538     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
9539     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
9540     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
9541     * {@link KeyEvent#KEYCODE_ENTER} is released.
9542     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9543     * although some may elect to do so in some situations. Do not rely on this to
9544     * catch software key presses.
9545     *
9546     * @param keyCode A key code that represents the button pressed, from
9547     *                {@link android.view.KeyEvent}.
9548     * @param event   The KeyEvent object that defines the button action.
9549     */
9550    public boolean onKeyUp(int keyCode, KeyEvent event) {
9551        if (KeyEvent.isConfirmKey(keyCode)) {
9552            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
9553                return true;
9554            }
9555            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
9556                setPressed(false);
9557
9558                if (!mHasPerformedLongPress) {
9559                    // This is a tap, so remove the longpress check
9560                    removeLongPressCallback();
9561                    return performClick();
9562                }
9563            }
9564        }
9565        return false;
9566    }
9567
9568    /**
9569     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
9570     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
9571     * the event).
9572     * <p>Key presses in software keyboards will generally NOT trigger this listener,
9573     * although some may elect to do so in some situations. Do not rely on this to
9574     * catch software key presses.
9575     *
9576     * @param keyCode     A key code that represents the button pressed, from
9577     *                    {@link android.view.KeyEvent}.
9578     * @param repeatCount The number of times the action was made.
9579     * @param event       The KeyEvent object that defines the button action.
9580     */
9581    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
9582        return false;
9583    }
9584
9585    /**
9586     * Called on the focused view when a key shortcut event is not handled.
9587     * Override this method to implement local key shortcuts for the View.
9588     * Key shortcuts can also be implemented by setting the
9589     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
9590     *
9591     * @param keyCode The value in event.getKeyCode().
9592     * @param event Description of the key event.
9593     * @return If you handled the event, return true. If you want to allow the
9594     *         event to be handled by the next receiver, return false.
9595     */
9596    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
9597        return false;
9598    }
9599
9600    /**
9601     * Check whether the called view is a text editor, in which case it
9602     * would make sense to automatically display a soft input window for
9603     * it.  Subclasses should override this if they implement
9604     * {@link #onCreateInputConnection(EditorInfo)} to return true if
9605     * a call on that method would return a non-null InputConnection, and
9606     * they are really a first-class editor that the user would normally
9607     * start typing on when the go into a window containing your view.
9608     *
9609     * <p>The default implementation always returns false.  This does
9610     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
9611     * will not be called or the user can not otherwise perform edits on your
9612     * view; it is just a hint to the system that this is not the primary
9613     * purpose of this view.
9614     *
9615     * @return Returns true if this view is a text editor, else false.
9616     */
9617    public boolean onCheckIsTextEditor() {
9618        return false;
9619    }
9620
9621    /**
9622     * Create a new InputConnection for an InputMethod to interact
9623     * with the view.  The default implementation returns null, since it doesn't
9624     * support input methods.  You can override this to implement such support.
9625     * This is only needed for views that take focus and text input.
9626     *
9627     * <p>When implementing this, you probably also want to implement
9628     * {@link #onCheckIsTextEditor()} to indicate you will return a
9629     * non-null InputConnection.</p>
9630     *
9631     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
9632     * object correctly and in its entirety, so that the connected IME can rely
9633     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
9634     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
9635     * must be filled in with the correct cursor position for IMEs to work correctly
9636     * with your application.</p>
9637     *
9638     * @param outAttrs Fill in with attribute information about the connection.
9639     */
9640    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
9641        return null;
9642    }
9643
9644    /**
9645     * Called by the {@link android.view.inputmethod.InputMethodManager}
9646     * when a view who is not the current
9647     * input connection target is trying to make a call on the manager.  The
9648     * default implementation returns false; you can override this to return
9649     * true for certain views if you are performing InputConnection proxying
9650     * to them.
9651     * @param view The View that is making the InputMethodManager call.
9652     * @return Return true to allow the call, false to reject.
9653     */
9654    public boolean checkInputConnectionProxy(View view) {
9655        return false;
9656    }
9657
9658    /**
9659     * Show the context menu for this view. It is not safe to hold on to the
9660     * menu after returning from this method.
9661     *
9662     * You should normally not overload this method. Overload
9663     * {@link #onCreateContextMenu(ContextMenu)} or define an
9664     * {@link OnCreateContextMenuListener} to add items to the context menu.
9665     *
9666     * @param menu The context menu to populate
9667     */
9668    public void createContextMenu(ContextMenu menu) {
9669        ContextMenuInfo menuInfo = getContextMenuInfo();
9670
9671        // Sets the current menu info so all items added to menu will have
9672        // my extra info set.
9673        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
9674
9675        onCreateContextMenu(menu);
9676        ListenerInfo li = mListenerInfo;
9677        if (li != null && li.mOnCreateContextMenuListener != null) {
9678            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
9679        }
9680
9681        // Clear the extra information so subsequent items that aren't mine don't
9682        // have my extra info.
9683        ((MenuBuilder)menu).setCurrentMenuInfo(null);
9684
9685        if (mParent != null) {
9686            mParent.createContextMenu(menu);
9687        }
9688    }
9689
9690    /**
9691     * Views should implement this if they have extra information to associate
9692     * with the context menu. The return result is supplied as a parameter to
9693     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
9694     * callback.
9695     *
9696     * @return Extra information about the item for which the context menu
9697     *         should be shown. This information will vary across different
9698     *         subclasses of View.
9699     */
9700    protected ContextMenuInfo getContextMenuInfo() {
9701        return null;
9702    }
9703
9704    /**
9705     * Views should implement this if the view itself is going to add items to
9706     * the context menu.
9707     *
9708     * @param menu the context menu to populate
9709     */
9710    protected void onCreateContextMenu(ContextMenu menu) {
9711    }
9712
9713    /**
9714     * Implement this method to handle trackball motion events.  The
9715     * <em>relative</em> movement of the trackball since the last event
9716     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
9717     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
9718     * that a movement of 1 corresponds to the user pressing one DPAD key (so
9719     * they will often be fractional values, representing the more fine-grained
9720     * movement information available from a trackball).
9721     *
9722     * @param event The motion event.
9723     * @return True if the event was handled, false otherwise.
9724     */
9725    public boolean onTrackballEvent(MotionEvent event) {
9726        return false;
9727    }
9728
9729    /**
9730     * Implement this method to handle generic motion events.
9731     * <p>
9732     * Generic motion events describe joystick movements, mouse hovers, track pad
9733     * touches, scroll wheel movements and other input events.  The
9734     * {@link MotionEvent#getSource() source} of the motion event specifies
9735     * the class of input that was received.  Implementations of this method
9736     * must examine the bits in the source before processing the event.
9737     * The following code example shows how this is done.
9738     * </p><p>
9739     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
9740     * are delivered to the view under the pointer.  All other generic motion events are
9741     * delivered to the focused view.
9742     * </p>
9743     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
9744     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
9745     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
9746     *             // process the joystick movement...
9747     *             return true;
9748     *         }
9749     *     }
9750     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
9751     *         switch (event.getAction()) {
9752     *             case MotionEvent.ACTION_HOVER_MOVE:
9753     *                 // process the mouse hover movement...
9754     *                 return true;
9755     *             case MotionEvent.ACTION_SCROLL:
9756     *                 // process the scroll wheel movement...
9757     *                 return true;
9758     *         }
9759     *     }
9760     *     return super.onGenericMotionEvent(event);
9761     * }</pre>
9762     *
9763     * @param event The generic motion event being processed.
9764     * @return True if the event was handled, false otherwise.
9765     */
9766    public boolean onGenericMotionEvent(MotionEvent event) {
9767        return false;
9768    }
9769
9770    /**
9771     * Implement this method to handle hover events.
9772     * <p>
9773     * This method is called whenever a pointer is hovering into, over, or out of the
9774     * bounds of a view and the view is not currently being touched.
9775     * Hover events are represented as pointer events with action
9776     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
9777     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
9778     * </p>
9779     * <ul>
9780     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9781     * when the pointer enters the bounds of the view.</li>
9782     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9783     * when the pointer has already entered the bounds of the view and has moved.</li>
9784     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9785     * when the pointer has exited the bounds of the view or when the pointer is
9786     * about to go down due to a button click, tap, or similar user action that
9787     * causes the view to be touched.</li>
9788     * </ul>
9789     * <p>
9790     * The view should implement this method to return true to indicate that it is
9791     * handling the hover event, such as by changing its drawable state.
9792     * </p><p>
9793     * The default implementation calls {@link #setHovered} to update the hovered state
9794     * of the view when a hover enter or hover exit event is received, if the view
9795     * is enabled and is clickable.  The default implementation also sends hover
9796     * accessibility events.
9797     * </p>
9798     *
9799     * @param event The motion event that describes the hover.
9800     * @return True if the view handled the hover event.
9801     *
9802     * @see #isHovered
9803     * @see #setHovered
9804     * @see #onHoverChanged
9805     */
9806    public boolean onHoverEvent(MotionEvent event) {
9807        // The root view may receive hover (or touch) events that are outside the bounds of
9808        // the window.  This code ensures that we only send accessibility events for
9809        // hovers that are actually within the bounds of the root view.
9810        final int action = event.getActionMasked();
9811        if (!mSendingHoverAccessibilityEvents) {
9812            if ((action == MotionEvent.ACTION_HOVER_ENTER
9813                    || action == MotionEvent.ACTION_HOVER_MOVE)
9814                    && !hasHoveredChild()
9815                    && pointInView(event.getX(), event.getY())) {
9816                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9817                mSendingHoverAccessibilityEvents = true;
9818            }
9819        } else {
9820            if (action == MotionEvent.ACTION_HOVER_EXIT
9821                    || (action == MotionEvent.ACTION_MOVE
9822                            && !pointInView(event.getX(), event.getY()))) {
9823                mSendingHoverAccessibilityEvents = false;
9824                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9825            }
9826        }
9827
9828        if (isHoverable()) {
9829            switch (action) {
9830                case MotionEvent.ACTION_HOVER_ENTER:
9831                    setHovered(true);
9832                    break;
9833                case MotionEvent.ACTION_HOVER_EXIT:
9834                    setHovered(false);
9835                    break;
9836            }
9837
9838            // Dispatch the event to onGenericMotionEvent before returning true.
9839            // This is to provide compatibility with existing applications that
9840            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9841            // break because of the new default handling for hoverable views
9842            // in onHoverEvent.
9843            // Note that onGenericMotionEvent will be called by default when
9844            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9845            dispatchGenericMotionEventInternal(event);
9846            // The event was already handled by calling setHovered(), so always
9847            // return true.
9848            return true;
9849        }
9850
9851        return false;
9852    }
9853
9854    /**
9855     * Returns true if the view should handle {@link #onHoverEvent}
9856     * by calling {@link #setHovered} to change its hovered state.
9857     *
9858     * @return True if the view is hoverable.
9859     */
9860    private boolean isHoverable() {
9861        final int viewFlags = mViewFlags;
9862        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9863            return false;
9864        }
9865
9866        return (viewFlags & CLICKABLE) == CLICKABLE
9867                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
9868                || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE;
9869    }
9870
9871    /**
9872     * Returns true if the view is currently hovered.
9873     *
9874     * @return True if the view is currently hovered.
9875     *
9876     * @see #setHovered
9877     * @see #onHoverChanged
9878     */
9879    @ViewDebug.ExportedProperty
9880    public boolean isHovered() {
9881        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9882    }
9883
9884    /**
9885     * Sets whether the view is currently hovered.
9886     * <p>
9887     * Calling this method also changes the drawable state of the view.  This
9888     * enables the view to react to hover by using different drawable resources
9889     * to change its appearance.
9890     * </p><p>
9891     * The {@link #onHoverChanged} method is called when the hovered state changes.
9892     * </p>
9893     *
9894     * @param hovered True if the view is hovered.
9895     *
9896     * @see #isHovered
9897     * @see #onHoverChanged
9898     */
9899    public void setHovered(boolean hovered) {
9900        if (hovered) {
9901            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9902                mPrivateFlags |= PFLAG_HOVERED;
9903                refreshDrawableState();
9904                onHoverChanged(true);
9905            }
9906        } else {
9907            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9908                mPrivateFlags &= ~PFLAG_HOVERED;
9909                refreshDrawableState();
9910                onHoverChanged(false);
9911            }
9912        }
9913    }
9914
9915    /**
9916     * Implement this method to handle hover state changes.
9917     * <p>
9918     * This method is called whenever the hover state changes as a result of a
9919     * call to {@link #setHovered}.
9920     * </p>
9921     *
9922     * @param hovered The current hover state, as returned by {@link #isHovered}.
9923     *
9924     * @see #isHovered
9925     * @see #setHovered
9926     */
9927    public void onHoverChanged(boolean hovered) {
9928    }
9929
9930    /**
9931     * Implement this method to handle touch screen motion events.
9932     * <p>
9933     * If this method is used to detect click actions, it is recommended that
9934     * the actions be performed by implementing and calling
9935     * {@link #performClick()}. This will ensure consistent system behavior,
9936     * including:
9937     * <ul>
9938     * <li>obeying click sound preferences
9939     * <li>dispatching OnClickListener calls
9940     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9941     * accessibility features are enabled
9942     * </ul>
9943     *
9944     * @param event The motion event.
9945     * @return True if the event was handled, false otherwise.
9946     */
9947    public boolean onTouchEvent(MotionEvent event) {
9948        final float x = event.getX();
9949        final float y = event.getY();
9950        final int viewFlags = mViewFlags;
9951        final int action = event.getAction();
9952
9953        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9954            if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9955                setPressed(false);
9956            }
9957            // A disabled view that is clickable still consumes the touch
9958            // events, it just doesn't respond to them.
9959            return (((viewFlags & CLICKABLE) == CLICKABLE
9960                    || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
9961                    || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE);
9962        }
9963
9964        if (mTouchDelegate != null) {
9965            if (mTouchDelegate.onTouchEvent(event)) {
9966                return true;
9967            }
9968        }
9969
9970        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9971                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
9972                (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE) {
9973            switch (action) {
9974                case MotionEvent.ACTION_UP:
9975                    if (mInStylusButtonPress) {
9976                        mInStylusButtonPress = false;
9977                        mHasPerformedLongPress = false;
9978                    }
9979                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9980                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9981                        // take focus if we don't have it already and we should in
9982                        // touch mode.
9983                        boolean focusTaken = false;
9984                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9985                            focusTaken = requestFocus();
9986                        }
9987
9988                        if (prepressed) {
9989                            // The button is being released before we actually
9990                            // showed it as pressed.  Make it show the pressed
9991                            // state now (before scheduling the click) to ensure
9992                            // the user sees it.
9993                            setPressed(true, x, y);
9994                       }
9995
9996                        if (!mHasPerformedLongPress) {
9997                            // This is a tap, so remove the longpress check
9998                            removeLongPressCallback();
9999
10000                            // Only perform take click actions if we were in the pressed state
10001                            if (!focusTaken) {
10002                                // Use a Runnable and post this rather than calling
10003                                // performClick directly. This lets other visual state
10004                                // of the view update before click actions start.
10005                                if (mPerformClick == null) {
10006                                    mPerformClick = new PerformClick();
10007                                }
10008                                if (!post(mPerformClick)) {
10009                                    performClick();
10010                                }
10011                            }
10012                        }
10013
10014                        if (mUnsetPressedState == null) {
10015                            mUnsetPressedState = new UnsetPressedState();
10016                        }
10017
10018                        if (prepressed) {
10019                            postDelayed(mUnsetPressedState,
10020                                    ViewConfiguration.getPressedStateDuration());
10021                        } else if (!post(mUnsetPressedState)) {
10022                            // If the post failed, unpress right now
10023                            mUnsetPressedState.run();
10024                        }
10025
10026                        removeTapCallback();
10027                    }
10028                    break;
10029
10030                case MotionEvent.ACTION_DOWN:
10031                    mHasPerformedLongPress = false;
10032                    mInStylusButtonPress = false;
10033
10034                    if (performStylusActionOnButtonPress(event)) {
10035                        break;
10036                    }
10037
10038                    if (performButtonActionOnTouchDown(event)) {
10039                        break;
10040                    }
10041
10042                    // Walk up the hierarchy to determine if we're inside a scrolling container.
10043                    boolean isInScrollingContainer = isInScrollingContainer();
10044
10045                    // For views inside a scrolling container, delay the pressed feedback for
10046                    // a short period in case this is a scroll.
10047                    if (isInScrollingContainer) {
10048                        mPrivateFlags |= PFLAG_PREPRESSED;
10049                        if (mPendingCheckForTap == null) {
10050                            mPendingCheckForTap = new CheckForTap();
10051                        }
10052                        mPendingCheckForTap.x = event.getX();
10053                        mPendingCheckForTap.y = event.getY();
10054                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
10055                    } else {
10056                        // Not inside a scrolling container, so show the feedback right away
10057                        setPressed(true, x, y);
10058                        checkForLongClick(0);
10059                    }
10060                    break;
10061
10062                case MotionEvent.ACTION_CANCEL:
10063                    setPressed(false);
10064                    removeTapCallback();
10065                    removeLongPressCallback();
10066                    if (mInStylusButtonPress) {
10067                        mInStylusButtonPress = false;
10068                        mHasPerformedLongPress = false;
10069                    }
10070                    break;
10071
10072                case MotionEvent.ACTION_MOVE:
10073                    drawableHotspotChanged(x, y);
10074
10075                    // Be lenient about moving outside of buttons
10076                    if (!pointInView(x, y, mTouchSlop)) {
10077                        // Outside button
10078                        removeTapCallback();
10079                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
10080                            // Remove any future long press/tap checks
10081                            removeLongPressCallback();
10082
10083                            setPressed(false);
10084                        }
10085                    } else if (performStylusActionOnButtonPress(event)) {
10086                        // Check for stylus button press if we're within the view.
10087                        break;
10088                    }
10089                    break;
10090            }
10091
10092            return true;
10093        }
10094
10095        return false;
10096    }
10097
10098    /**
10099     * @hide
10100     */
10101    public boolean isInScrollingContainer() {
10102        ViewParent p = getParent();
10103        while (p != null && p instanceof ViewGroup) {
10104            if (((ViewGroup) p).shouldDelayChildPressedState()) {
10105                return true;
10106            }
10107            p = p.getParent();
10108        }
10109        return false;
10110    }
10111
10112    /**
10113     * Remove the longpress detection timer.
10114     */
10115    private void removeLongPressCallback() {
10116        if (mPendingCheckForLongPress != null) {
10117          removeCallbacks(mPendingCheckForLongPress);
10118        }
10119    }
10120
10121    /**
10122     * Remove the pending click action
10123     */
10124    private void removePerformClickCallback() {
10125        if (mPerformClick != null) {
10126            removeCallbacks(mPerformClick);
10127        }
10128    }
10129
10130    /**
10131     * Remove the prepress detection timer.
10132     */
10133    private void removeUnsetPressCallback() {
10134        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
10135            setPressed(false);
10136            removeCallbacks(mUnsetPressedState);
10137        }
10138    }
10139
10140    /**
10141     * Remove the tap detection timer.
10142     */
10143    private void removeTapCallback() {
10144        if (mPendingCheckForTap != null) {
10145            mPrivateFlags &= ~PFLAG_PREPRESSED;
10146            removeCallbacks(mPendingCheckForTap);
10147        }
10148    }
10149
10150    /**
10151     * Cancels a pending long press.  Your subclass can use this if you
10152     * want the context menu to come up if the user presses and holds
10153     * at the same place, but you don't want it to come up if they press
10154     * and then move around enough to cause scrolling.
10155     */
10156    public void cancelLongPress() {
10157        removeLongPressCallback();
10158
10159        /*
10160         * The prepressed state handled by the tap callback is a display
10161         * construct, but the tap callback will post a long press callback
10162         * less its own timeout. Remove it here.
10163         */
10164        removeTapCallback();
10165    }
10166
10167    /**
10168     * Remove the pending callback for sending a
10169     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
10170     */
10171    private void removeSendViewScrolledAccessibilityEventCallback() {
10172        if (mSendViewScrolledAccessibilityEvent != null) {
10173            removeCallbacks(mSendViewScrolledAccessibilityEvent);
10174            mSendViewScrolledAccessibilityEvent.mIsPending = false;
10175        }
10176    }
10177
10178    /**
10179     * Sets the TouchDelegate for this View.
10180     */
10181    public void setTouchDelegate(TouchDelegate delegate) {
10182        mTouchDelegate = delegate;
10183    }
10184
10185    /**
10186     * Gets the TouchDelegate for this View.
10187     */
10188    public TouchDelegate getTouchDelegate() {
10189        return mTouchDelegate;
10190    }
10191
10192    /**
10193     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
10194     *
10195     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
10196     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
10197     * available. This method should only be called for touch events.
10198     *
10199     * <p class="note">This api is not intended for most applications. Buffered dispatch
10200     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
10201     * streams will not improve your input latency. Side effects include: increased latency,
10202     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
10203     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
10204     * you.</p>
10205     */
10206    public final void requestUnbufferedDispatch(MotionEvent event) {
10207        final int action = event.getAction();
10208        if (mAttachInfo == null
10209                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
10210                || !event.isTouchEvent()) {
10211            return;
10212        }
10213        mAttachInfo.mUnbufferedDispatchRequested = true;
10214    }
10215
10216    /**
10217     * Set flags controlling behavior of this view.
10218     *
10219     * @param flags Constant indicating the value which should be set
10220     * @param mask Constant indicating the bit range that should be changed
10221     */
10222    void setFlags(int flags, int mask) {
10223        final boolean accessibilityEnabled =
10224                AccessibilityManager.getInstance(mContext).isEnabled();
10225        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
10226
10227        int old = mViewFlags;
10228        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
10229
10230        int changed = mViewFlags ^ old;
10231        if (changed == 0) {
10232            return;
10233        }
10234        int privateFlags = mPrivateFlags;
10235
10236        /* Check if the FOCUSABLE bit has changed */
10237        if (((changed & FOCUSABLE_MASK) != 0) &&
10238                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
10239            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
10240                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
10241                /* Give up focus if we are no longer focusable */
10242                clearFocus();
10243            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
10244                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
10245                /*
10246                 * Tell the view system that we are now available to take focus
10247                 * if no one else already has it.
10248                 */
10249                if (mParent != null) mParent.focusableViewAvailable(this);
10250            }
10251        }
10252
10253        final int newVisibility = flags & VISIBILITY_MASK;
10254        if (newVisibility == VISIBLE) {
10255            if ((changed & VISIBILITY_MASK) != 0) {
10256                /*
10257                 * If this view is becoming visible, invalidate it in case it changed while
10258                 * it was not visible. Marking it drawn ensures that the invalidation will
10259                 * go through.
10260                 */
10261                mPrivateFlags |= PFLAG_DRAWN;
10262                invalidate(true);
10263
10264                needGlobalAttributesUpdate(true);
10265
10266                // a view becoming visible is worth notifying the parent
10267                // about in case nothing has focus.  even if this specific view
10268                // isn't focusable, it may contain something that is, so let
10269                // the root view try to give this focus if nothing else does.
10270                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
10271                    mParent.focusableViewAvailable(this);
10272                }
10273            }
10274        }
10275
10276        /* Check if the GONE bit has changed */
10277        if ((changed & GONE) != 0) {
10278            needGlobalAttributesUpdate(false);
10279            requestLayout();
10280
10281            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
10282                if (hasFocus()) clearFocus();
10283                clearAccessibilityFocus();
10284                destroyDrawingCache();
10285                if (mParent instanceof View) {
10286                    // GONE views noop invalidation, so invalidate the parent
10287                    ((View) mParent).invalidate(true);
10288                }
10289                // Mark the view drawn to ensure that it gets invalidated properly the next
10290                // time it is visible and gets invalidated
10291                mPrivateFlags |= PFLAG_DRAWN;
10292            }
10293            if (mAttachInfo != null) {
10294                mAttachInfo.mViewVisibilityChanged = true;
10295            }
10296        }
10297
10298        /* Check if the VISIBLE bit has changed */
10299        if ((changed & INVISIBLE) != 0) {
10300            needGlobalAttributesUpdate(false);
10301            /*
10302             * If this view is becoming invisible, set the DRAWN flag so that
10303             * the next invalidate() will not be skipped.
10304             */
10305            mPrivateFlags |= PFLAG_DRAWN;
10306
10307            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
10308                // root view becoming invisible shouldn't clear focus and accessibility focus
10309                if (getRootView() != this) {
10310                    if (hasFocus()) clearFocus();
10311                    clearAccessibilityFocus();
10312                }
10313            }
10314            if (mAttachInfo != null) {
10315                mAttachInfo.mViewVisibilityChanged = true;
10316            }
10317        }
10318
10319        if ((changed & VISIBILITY_MASK) != 0) {
10320            // If the view is invisible, cleanup its display list to free up resources
10321            if (newVisibility != VISIBLE && mAttachInfo != null) {
10322                cleanupDraw();
10323            }
10324
10325            if (mParent instanceof ViewGroup) {
10326                ((ViewGroup) mParent).onChildVisibilityChanged(this,
10327                        (changed & VISIBILITY_MASK), newVisibility);
10328                ((View) mParent).invalidate(true);
10329            } else if (mParent != null) {
10330                mParent.invalidateChild(this, null);
10331            }
10332            dispatchVisibilityChanged(this, newVisibility);
10333
10334            notifySubtreeAccessibilityStateChangedIfNeeded();
10335        }
10336
10337        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
10338            destroyDrawingCache();
10339        }
10340
10341        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
10342            destroyDrawingCache();
10343            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10344            invalidateParentCaches();
10345        }
10346
10347        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
10348            destroyDrawingCache();
10349            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10350        }
10351
10352        if ((changed & DRAW_MASK) != 0) {
10353            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
10354                if (mBackground != null) {
10355                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10356                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
10357                } else {
10358                    mPrivateFlags |= PFLAG_SKIP_DRAW;
10359                }
10360            } else {
10361                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
10362            }
10363            requestLayout();
10364            invalidate(true);
10365        }
10366
10367        if ((changed & KEEP_SCREEN_ON) != 0) {
10368            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10369                mParent.recomputeViewAttributes(this);
10370            }
10371        }
10372
10373        if (accessibilityEnabled) {
10374            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
10375                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
10376                    || (changed & STYLUS_BUTTON_PRESSABLE) != 0) {
10377                if (oldIncludeForAccessibility != includeForAccessibility()) {
10378                    notifySubtreeAccessibilityStateChangedIfNeeded();
10379                } else {
10380                    notifyViewAccessibilityStateChangedIfNeeded(
10381                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10382                }
10383            } else if ((changed & ENABLED_MASK) != 0) {
10384                notifyViewAccessibilityStateChangedIfNeeded(
10385                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10386            }
10387        }
10388    }
10389
10390    /**
10391     * Change the view's z order in the tree, so it's on top of other sibling
10392     * views. This ordering change may affect layout, if the parent container
10393     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
10394     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
10395     * method should be followed by calls to {@link #requestLayout()} and
10396     * {@link View#invalidate()} on the view's parent to force the parent to redraw
10397     * with the new child ordering.
10398     *
10399     * @see ViewGroup#bringChildToFront(View)
10400     */
10401    public void bringToFront() {
10402        if (mParent != null) {
10403            mParent.bringChildToFront(this);
10404        }
10405    }
10406
10407    /**
10408     * This is called in response to an internal scroll in this view (i.e., the
10409     * view scrolled its own contents). This is typically as a result of
10410     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
10411     * called.
10412     *
10413     * @param l Current horizontal scroll origin.
10414     * @param t Current vertical scroll origin.
10415     * @param oldl Previous horizontal scroll origin.
10416     * @param oldt Previous vertical scroll origin.
10417     */
10418    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
10419        notifySubtreeAccessibilityStateChangedIfNeeded();
10420
10421        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10422            postSendViewScrolledAccessibilityEventCallback();
10423        }
10424
10425        mBackgroundSizeChanged = true;
10426        if (mForegroundInfo != null) {
10427            mForegroundInfo.mBoundsChanged = true;
10428        }
10429
10430        final AttachInfo ai = mAttachInfo;
10431        if (ai != null) {
10432            ai.mViewScrollChanged = true;
10433        }
10434
10435        if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) {
10436            mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
10437        }
10438    }
10439
10440    /**
10441     * Interface definition for a callback to be invoked when the scroll
10442     * X or Y positions of a view change.
10443     * <p>
10444     * <b>Note:</b> Some views handle scrolling independently from View and may
10445     * have their own separate listeners for scroll-type events. For example,
10446     * {@link android.widget.ListView ListView} allows clients to register an
10447     * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener}
10448     * to listen for changes in list scroll position.
10449     *
10450     * @see #setOnScrollChangeListener(View.OnScrollChangeListener)
10451     */
10452    public interface OnScrollChangeListener {
10453        /**
10454         * Called when the scroll position of a view changes.
10455         *
10456         * @param v The view whose scroll position has changed.
10457         * @param scrollX Current horizontal scroll origin.
10458         * @param scrollY Current vertical scroll origin.
10459         * @param oldScrollX Previous horizontal scroll origin.
10460         * @param oldScrollY Previous vertical scroll origin.
10461         */
10462        void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
10463    }
10464
10465    /**
10466     * Interface definition for a callback to be invoked when the layout bounds of a view
10467     * changes due to layout processing.
10468     */
10469    public interface OnLayoutChangeListener {
10470        /**
10471         * Called when the layout bounds of a view changes due to layout processing.
10472         *
10473         * @param v The view whose bounds have changed.
10474         * @param left The new value of the view's left property.
10475         * @param top The new value of the view's top property.
10476         * @param right The new value of the view's right property.
10477         * @param bottom The new value of the view's bottom property.
10478         * @param oldLeft The previous value of the view's left property.
10479         * @param oldTop The previous value of the view's top property.
10480         * @param oldRight The previous value of the view's right property.
10481         * @param oldBottom The previous value of the view's bottom property.
10482         */
10483        void onLayoutChange(View v, int left, int top, int right, int bottom,
10484            int oldLeft, int oldTop, int oldRight, int oldBottom);
10485    }
10486
10487    /**
10488     * This is called during layout when the size of this view has changed. If
10489     * you were just added to the view hierarchy, you're called with the old
10490     * values of 0.
10491     *
10492     * @param w Current width of this view.
10493     * @param h Current height of this view.
10494     * @param oldw Old width of this view.
10495     * @param oldh Old height of this view.
10496     */
10497    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
10498    }
10499
10500    /**
10501     * Called by draw to draw the child views. This may be overridden
10502     * by derived classes to gain control just before its children are drawn
10503     * (but after its own view has been drawn).
10504     * @param canvas the canvas on which to draw the view
10505     */
10506    protected void dispatchDraw(Canvas canvas) {
10507
10508    }
10509
10510    /**
10511     * Gets the parent of this view. Note that the parent is a
10512     * ViewParent and not necessarily a View.
10513     *
10514     * @return Parent of this view.
10515     */
10516    public final ViewParent getParent() {
10517        return mParent;
10518    }
10519
10520    /**
10521     * Set the horizontal scrolled position of your view. This will cause a call to
10522     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10523     * invalidated.
10524     * @param value the x position to scroll to
10525     */
10526    public void setScrollX(int value) {
10527        scrollTo(value, mScrollY);
10528    }
10529
10530    /**
10531     * Set the vertical scrolled position of your view. This will cause a call to
10532     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10533     * invalidated.
10534     * @param value the y position to scroll to
10535     */
10536    public void setScrollY(int value) {
10537        scrollTo(mScrollX, value);
10538    }
10539
10540    /**
10541     * Return the scrolled left position of this view. This is the left edge of
10542     * the displayed part of your view. You do not need to draw any pixels
10543     * farther left, since those are outside of the frame of your view on
10544     * screen.
10545     *
10546     * @return The left edge of the displayed part of your view, in pixels.
10547     */
10548    public final int getScrollX() {
10549        return mScrollX;
10550    }
10551
10552    /**
10553     * Return the scrolled top position of this view. This is the top edge of
10554     * the displayed part of your view. You do not need to draw any pixels above
10555     * it, since those are outside of the frame of your view on screen.
10556     *
10557     * @return The top edge of the displayed part of your view, in pixels.
10558     */
10559    public final int getScrollY() {
10560        return mScrollY;
10561    }
10562
10563    /**
10564     * Return the width of the your view.
10565     *
10566     * @return The width of your view, in pixels.
10567     */
10568    @ViewDebug.ExportedProperty(category = "layout")
10569    public final int getWidth() {
10570        return mRight - mLeft;
10571    }
10572
10573    /**
10574     * Return the height of your view.
10575     *
10576     * @return The height of your view, in pixels.
10577     */
10578    @ViewDebug.ExportedProperty(category = "layout")
10579    public final int getHeight() {
10580        return mBottom - mTop;
10581    }
10582
10583    /**
10584     * Return the visible drawing bounds of your view. Fills in the output
10585     * rectangle with the values from getScrollX(), getScrollY(),
10586     * getWidth(), and getHeight(). These bounds do not account for any
10587     * transformation properties currently set on the view, such as
10588     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
10589     *
10590     * @param outRect The (scrolled) drawing bounds of the view.
10591     */
10592    public void getDrawingRect(Rect outRect) {
10593        outRect.left = mScrollX;
10594        outRect.top = mScrollY;
10595        outRect.right = mScrollX + (mRight - mLeft);
10596        outRect.bottom = mScrollY + (mBottom - mTop);
10597    }
10598
10599    /**
10600     * Like {@link #getMeasuredWidthAndState()}, but only returns the
10601     * raw width component (that is the result is masked by
10602     * {@link #MEASURED_SIZE_MASK}).
10603     *
10604     * @return The raw measured width of this view.
10605     */
10606    public final int getMeasuredWidth() {
10607        return mMeasuredWidth & MEASURED_SIZE_MASK;
10608    }
10609
10610    /**
10611     * Return the full width measurement information for this view as computed
10612     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10613     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10614     * This should be used during measurement and layout calculations only. Use
10615     * {@link #getWidth()} to see how wide a view is after layout.
10616     *
10617     * @return The measured width of this view as a bit mask.
10618     */
10619    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10620            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10621                    name = "MEASURED_STATE_TOO_SMALL"),
10622    })
10623    public final int getMeasuredWidthAndState() {
10624        return mMeasuredWidth;
10625    }
10626
10627    /**
10628     * Like {@link #getMeasuredHeightAndState()}, but only returns the
10629     * raw width component (that is the result is masked by
10630     * {@link #MEASURED_SIZE_MASK}).
10631     *
10632     * @return The raw measured height of this view.
10633     */
10634    public final int getMeasuredHeight() {
10635        return mMeasuredHeight & MEASURED_SIZE_MASK;
10636    }
10637
10638    /**
10639     * Return the full height measurement information for this view as computed
10640     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
10641     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10642     * This should be used during measurement and layout calculations only. Use
10643     * {@link #getHeight()} to see how wide a view is after layout.
10644     *
10645     * @return The measured width of this view as a bit mask.
10646     */
10647    @ViewDebug.ExportedProperty(category = "measurement", flagMapping = {
10648            @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL,
10649                    name = "MEASURED_STATE_TOO_SMALL"),
10650    })
10651    public final int getMeasuredHeightAndState() {
10652        return mMeasuredHeight;
10653    }
10654
10655    /**
10656     * Return only the state bits of {@link #getMeasuredWidthAndState()}
10657     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
10658     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
10659     * and the height component is at the shifted bits
10660     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
10661     */
10662    public final int getMeasuredState() {
10663        return (mMeasuredWidth&MEASURED_STATE_MASK)
10664                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
10665                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
10666    }
10667
10668    /**
10669     * The transform matrix of this view, which is calculated based on the current
10670     * rotation, scale, and pivot properties.
10671     *
10672     * @see #getRotation()
10673     * @see #getScaleX()
10674     * @see #getScaleY()
10675     * @see #getPivotX()
10676     * @see #getPivotY()
10677     * @return The current transform matrix for the view
10678     */
10679    public Matrix getMatrix() {
10680        ensureTransformationInfo();
10681        final Matrix matrix = mTransformationInfo.mMatrix;
10682        mRenderNode.getMatrix(matrix);
10683        return matrix;
10684    }
10685
10686    /**
10687     * Returns true if the transform matrix is the identity matrix.
10688     * Recomputes the matrix if necessary.
10689     *
10690     * @return True if the transform matrix is the identity matrix, false otherwise.
10691     */
10692    final boolean hasIdentityMatrix() {
10693        return mRenderNode.hasIdentityMatrix();
10694    }
10695
10696    void ensureTransformationInfo() {
10697        if (mTransformationInfo == null) {
10698            mTransformationInfo = new TransformationInfo();
10699        }
10700    }
10701
10702   /**
10703     * Utility method to retrieve the inverse of the current mMatrix property.
10704     * We cache the matrix to avoid recalculating it when transform properties
10705     * have not changed.
10706     *
10707     * @return The inverse of the current matrix of this view.
10708     * @hide
10709     */
10710    public final Matrix getInverseMatrix() {
10711        ensureTransformationInfo();
10712        if (mTransformationInfo.mInverseMatrix == null) {
10713            mTransformationInfo.mInverseMatrix = new Matrix();
10714        }
10715        final Matrix matrix = mTransformationInfo.mInverseMatrix;
10716        mRenderNode.getInverseMatrix(matrix);
10717        return matrix;
10718    }
10719
10720    /**
10721     * Gets the distance along the Z axis from the camera to this view.
10722     *
10723     * @see #setCameraDistance(float)
10724     *
10725     * @return The distance along the Z axis.
10726     */
10727    public float getCameraDistance() {
10728        final float dpi = mResources.getDisplayMetrics().densityDpi;
10729        return -(mRenderNode.getCameraDistance() * dpi);
10730    }
10731
10732    /**
10733     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
10734     * views are drawn) from the camera to this view. The camera's distance
10735     * affects 3D transformations, for instance rotations around the X and Y
10736     * axis. If the rotationX or rotationY properties are changed and this view is
10737     * large (more than half the size of the screen), it is recommended to always
10738     * use a camera distance that's greater than the height (X axis rotation) or
10739     * the width (Y axis rotation) of this view.</p>
10740     *
10741     * <p>The distance of the camera from the view plane can have an affect on the
10742     * perspective distortion of the view when it is rotated around the x or y axis.
10743     * For example, a large distance will result in a large viewing angle, and there
10744     * will not be much perspective distortion of the view as it rotates. A short
10745     * distance may cause much more perspective distortion upon rotation, and can
10746     * also result in some drawing artifacts if the rotated view ends up partially
10747     * behind the camera (which is why the recommendation is to use a distance at
10748     * least as far as the size of the view, if the view is to be rotated.)</p>
10749     *
10750     * <p>The distance is expressed in "depth pixels." The default distance depends
10751     * on the screen density. For instance, on a medium density display, the
10752     * default distance is 1280. On a high density display, the default distance
10753     * is 1920.</p>
10754     *
10755     * <p>If you want to specify a distance that leads to visually consistent
10756     * results across various densities, use the following formula:</p>
10757     * <pre>
10758     * float scale = context.getResources().getDisplayMetrics().density;
10759     * view.setCameraDistance(distance * scale);
10760     * </pre>
10761     *
10762     * <p>The density scale factor of a high density display is 1.5,
10763     * and 1920 = 1280 * 1.5.</p>
10764     *
10765     * @param distance The distance in "depth pixels", if negative the opposite
10766     *        value is used
10767     *
10768     * @see #setRotationX(float)
10769     * @see #setRotationY(float)
10770     */
10771    public void setCameraDistance(float distance) {
10772        final float dpi = mResources.getDisplayMetrics().densityDpi;
10773
10774        invalidateViewProperty(true, false);
10775        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
10776        invalidateViewProperty(false, false);
10777
10778        invalidateParentIfNeededAndWasQuickRejected();
10779    }
10780
10781    /**
10782     * The degrees that the view is rotated around the pivot point.
10783     *
10784     * @see #setRotation(float)
10785     * @see #getPivotX()
10786     * @see #getPivotY()
10787     *
10788     * @return The degrees of rotation.
10789     */
10790    @ViewDebug.ExportedProperty(category = "drawing")
10791    public float getRotation() {
10792        return mRenderNode.getRotation();
10793    }
10794
10795    /**
10796     * Sets the degrees that the view is rotated around the pivot point. Increasing values
10797     * result in clockwise rotation.
10798     *
10799     * @param rotation The degrees of rotation.
10800     *
10801     * @see #getRotation()
10802     * @see #getPivotX()
10803     * @see #getPivotY()
10804     * @see #setRotationX(float)
10805     * @see #setRotationY(float)
10806     *
10807     * @attr ref android.R.styleable#View_rotation
10808     */
10809    public void setRotation(float rotation) {
10810        if (rotation != getRotation()) {
10811            // Double-invalidation is necessary to capture view's old and new areas
10812            invalidateViewProperty(true, false);
10813            mRenderNode.setRotation(rotation);
10814            invalidateViewProperty(false, true);
10815
10816            invalidateParentIfNeededAndWasQuickRejected();
10817            notifySubtreeAccessibilityStateChangedIfNeeded();
10818        }
10819    }
10820
10821    /**
10822     * The degrees that the view is rotated around the vertical axis through the pivot point.
10823     *
10824     * @see #getPivotX()
10825     * @see #getPivotY()
10826     * @see #setRotationY(float)
10827     *
10828     * @return The degrees of Y rotation.
10829     */
10830    @ViewDebug.ExportedProperty(category = "drawing")
10831    public float getRotationY() {
10832        return mRenderNode.getRotationY();
10833    }
10834
10835    /**
10836     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
10837     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
10838     * down the y axis.
10839     *
10840     * When rotating large views, it is recommended to adjust the camera distance
10841     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10842     *
10843     * @param rotationY The degrees of Y rotation.
10844     *
10845     * @see #getRotationY()
10846     * @see #getPivotX()
10847     * @see #getPivotY()
10848     * @see #setRotation(float)
10849     * @see #setRotationX(float)
10850     * @see #setCameraDistance(float)
10851     *
10852     * @attr ref android.R.styleable#View_rotationY
10853     */
10854    public void setRotationY(float rotationY) {
10855        if (rotationY != getRotationY()) {
10856            invalidateViewProperty(true, false);
10857            mRenderNode.setRotationY(rotationY);
10858            invalidateViewProperty(false, true);
10859
10860            invalidateParentIfNeededAndWasQuickRejected();
10861            notifySubtreeAccessibilityStateChangedIfNeeded();
10862        }
10863    }
10864
10865    /**
10866     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10867     *
10868     * @see #getPivotX()
10869     * @see #getPivotY()
10870     * @see #setRotationX(float)
10871     *
10872     * @return The degrees of X rotation.
10873     */
10874    @ViewDebug.ExportedProperty(category = "drawing")
10875    public float getRotationX() {
10876        return mRenderNode.getRotationX();
10877    }
10878
10879    /**
10880     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10881     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10882     * x axis.
10883     *
10884     * When rotating large views, it is recommended to adjust the camera distance
10885     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10886     *
10887     * @param rotationX The degrees of X rotation.
10888     *
10889     * @see #getRotationX()
10890     * @see #getPivotX()
10891     * @see #getPivotY()
10892     * @see #setRotation(float)
10893     * @see #setRotationY(float)
10894     * @see #setCameraDistance(float)
10895     *
10896     * @attr ref android.R.styleable#View_rotationX
10897     */
10898    public void setRotationX(float rotationX) {
10899        if (rotationX != getRotationX()) {
10900            invalidateViewProperty(true, false);
10901            mRenderNode.setRotationX(rotationX);
10902            invalidateViewProperty(false, true);
10903
10904            invalidateParentIfNeededAndWasQuickRejected();
10905            notifySubtreeAccessibilityStateChangedIfNeeded();
10906        }
10907    }
10908
10909    /**
10910     * The amount that the view is scaled in x around the pivot point, as a proportion of
10911     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10912     *
10913     * <p>By default, this is 1.0f.
10914     *
10915     * @see #getPivotX()
10916     * @see #getPivotY()
10917     * @return The scaling factor.
10918     */
10919    @ViewDebug.ExportedProperty(category = "drawing")
10920    public float getScaleX() {
10921        return mRenderNode.getScaleX();
10922    }
10923
10924    /**
10925     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10926     * the view's unscaled width. A value of 1 means that no scaling is applied.
10927     *
10928     * @param scaleX The scaling factor.
10929     * @see #getPivotX()
10930     * @see #getPivotY()
10931     *
10932     * @attr ref android.R.styleable#View_scaleX
10933     */
10934    public void setScaleX(float scaleX) {
10935        if (scaleX != getScaleX()) {
10936            invalidateViewProperty(true, false);
10937            mRenderNode.setScaleX(scaleX);
10938            invalidateViewProperty(false, true);
10939
10940            invalidateParentIfNeededAndWasQuickRejected();
10941            notifySubtreeAccessibilityStateChangedIfNeeded();
10942        }
10943    }
10944
10945    /**
10946     * The amount that the view is scaled in y around the pivot point, as a proportion of
10947     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10948     *
10949     * <p>By default, this is 1.0f.
10950     *
10951     * @see #getPivotX()
10952     * @see #getPivotY()
10953     * @return The scaling factor.
10954     */
10955    @ViewDebug.ExportedProperty(category = "drawing")
10956    public float getScaleY() {
10957        return mRenderNode.getScaleY();
10958    }
10959
10960    /**
10961     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10962     * the view's unscaled width. A value of 1 means that no scaling is applied.
10963     *
10964     * @param scaleY The scaling factor.
10965     * @see #getPivotX()
10966     * @see #getPivotY()
10967     *
10968     * @attr ref android.R.styleable#View_scaleY
10969     */
10970    public void setScaleY(float scaleY) {
10971        if (scaleY != getScaleY()) {
10972            invalidateViewProperty(true, false);
10973            mRenderNode.setScaleY(scaleY);
10974            invalidateViewProperty(false, true);
10975
10976            invalidateParentIfNeededAndWasQuickRejected();
10977            notifySubtreeAccessibilityStateChangedIfNeeded();
10978        }
10979    }
10980
10981    /**
10982     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10983     * and {@link #setScaleX(float) scaled}.
10984     *
10985     * @see #getRotation()
10986     * @see #getScaleX()
10987     * @see #getScaleY()
10988     * @see #getPivotY()
10989     * @return The x location of the pivot point.
10990     *
10991     * @attr ref android.R.styleable#View_transformPivotX
10992     */
10993    @ViewDebug.ExportedProperty(category = "drawing")
10994    public float getPivotX() {
10995        return mRenderNode.getPivotX();
10996    }
10997
10998    /**
10999     * Sets the x location of the point around which the view is
11000     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
11001     * By default, the pivot point is centered on the object.
11002     * Setting this property disables this behavior and causes the view to use only the
11003     * explicitly set pivotX and pivotY values.
11004     *
11005     * @param pivotX The x location of the pivot point.
11006     * @see #getRotation()
11007     * @see #getScaleX()
11008     * @see #getScaleY()
11009     * @see #getPivotY()
11010     *
11011     * @attr ref android.R.styleable#View_transformPivotX
11012     */
11013    public void setPivotX(float pivotX) {
11014        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
11015            invalidateViewProperty(true, false);
11016            mRenderNode.setPivotX(pivotX);
11017            invalidateViewProperty(false, true);
11018
11019            invalidateParentIfNeededAndWasQuickRejected();
11020        }
11021    }
11022
11023    /**
11024     * The y location of the point around which the view is {@link #setRotation(float) rotated}
11025     * and {@link #setScaleY(float) scaled}.
11026     *
11027     * @see #getRotation()
11028     * @see #getScaleX()
11029     * @see #getScaleY()
11030     * @see #getPivotY()
11031     * @return The y location of the pivot point.
11032     *
11033     * @attr ref android.R.styleable#View_transformPivotY
11034     */
11035    @ViewDebug.ExportedProperty(category = "drawing")
11036    public float getPivotY() {
11037        return mRenderNode.getPivotY();
11038    }
11039
11040    /**
11041     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
11042     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
11043     * Setting this property disables this behavior and causes the view to use only the
11044     * explicitly set pivotX and pivotY values.
11045     *
11046     * @param pivotY The y location of the pivot point.
11047     * @see #getRotation()
11048     * @see #getScaleX()
11049     * @see #getScaleY()
11050     * @see #getPivotY()
11051     *
11052     * @attr ref android.R.styleable#View_transformPivotY
11053     */
11054    public void setPivotY(float pivotY) {
11055        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
11056            invalidateViewProperty(true, false);
11057            mRenderNode.setPivotY(pivotY);
11058            invalidateViewProperty(false, true);
11059
11060            invalidateParentIfNeededAndWasQuickRejected();
11061        }
11062    }
11063
11064    /**
11065     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
11066     * completely transparent and 1 means the view is completely opaque.
11067     *
11068     * <p>By default this is 1.0f.
11069     * @return The opacity of the view.
11070     */
11071    @ViewDebug.ExportedProperty(category = "drawing")
11072    public float getAlpha() {
11073        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
11074    }
11075
11076    /**
11077     * Returns whether this View has content which overlaps.
11078     *
11079     * <p>This function, intended to be overridden by specific View types, is an optimization when
11080     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
11081     * an offscreen buffer and then composited into place, which can be expensive. If the view has
11082     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
11083     * directly. An example of overlapping rendering is a TextView with a background image, such as
11084     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
11085     * ImageView with only the foreground image. The default implementation returns true; subclasses
11086     * should override if they have cases which can be optimized.</p>
11087     *
11088     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
11089     * necessitates that a View return true if it uses the methods internally without passing the
11090     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
11091     *
11092     * @return true if the content in this view might overlap, false otherwise.
11093     */
11094    @ViewDebug.ExportedProperty(category = "drawing")
11095    public boolean hasOverlappingRendering() {
11096        return true;
11097    }
11098
11099    /**
11100     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
11101     * completely transparent and 1 means the view is completely opaque.</p>
11102     *
11103     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
11104     * performance implications, especially for large views. It is best to use the alpha property
11105     * sparingly and transiently, as in the case of fading animations.</p>
11106     *
11107     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
11108     * strongly recommended for performance reasons to either override
11109     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
11110     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
11111     *
11112     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
11113     * responsible for applying the opacity itself.</p>
11114     *
11115     * <p>Note that if the view is backed by a
11116     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
11117     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
11118     * 1.0 will supersede the alpha of the layer paint.</p>
11119     *
11120     * @param alpha The opacity of the view.
11121     *
11122     * @see #hasOverlappingRendering()
11123     * @see #setLayerType(int, android.graphics.Paint)
11124     *
11125     * @attr ref android.R.styleable#View_alpha
11126     */
11127    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
11128        ensureTransformationInfo();
11129        if (mTransformationInfo.mAlpha != alpha) {
11130            mTransformationInfo.mAlpha = alpha;
11131            if (onSetAlpha((int) (alpha * 255))) {
11132                mPrivateFlags |= PFLAG_ALPHA_SET;
11133                // subclass is handling alpha - don't optimize rendering cache invalidation
11134                invalidateParentCaches();
11135                invalidate(true);
11136            } else {
11137                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11138                invalidateViewProperty(true, false);
11139                mRenderNode.setAlpha(getFinalAlpha());
11140                notifyViewAccessibilityStateChangedIfNeeded(
11141                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11142            }
11143        }
11144    }
11145
11146    /**
11147     * Faster version of setAlpha() which performs the same steps except there are
11148     * no calls to invalidate(). The caller of this function should perform proper invalidation
11149     * on the parent and this object. The return value indicates whether the subclass handles
11150     * alpha (the return value for onSetAlpha()).
11151     *
11152     * @param alpha The new value for the alpha property
11153     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
11154     *         the new value for the alpha property is different from the old value
11155     */
11156    boolean setAlphaNoInvalidation(float alpha) {
11157        ensureTransformationInfo();
11158        if (mTransformationInfo.mAlpha != alpha) {
11159            mTransformationInfo.mAlpha = alpha;
11160            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
11161            if (subclassHandlesAlpha) {
11162                mPrivateFlags |= PFLAG_ALPHA_SET;
11163                return true;
11164            } else {
11165                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11166                mRenderNode.setAlpha(getFinalAlpha());
11167            }
11168        }
11169        return false;
11170    }
11171
11172    /**
11173     * This property is hidden and intended only for use by the Fade transition, which
11174     * animates it to produce a visual translucency that does not side-effect (or get
11175     * affected by) the real alpha property. This value is composited with the other
11176     * alpha value (and the AlphaAnimation value, when that is present) to produce
11177     * a final visual translucency result, which is what is passed into the DisplayList.
11178     *
11179     * @hide
11180     */
11181    public void setTransitionAlpha(float alpha) {
11182        ensureTransformationInfo();
11183        if (mTransformationInfo.mTransitionAlpha != alpha) {
11184            mTransformationInfo.mTransitionAlpha = alpha;
11185            mPrivateFlags &= ~PFLAG_ALPHA_SET;
11186            invalidateViewProperty(true, false);
11187            mRenderNode.setAlpha(getFinalAlpha());
11188        }
11189    }
11190
11191    /**
11192     * Calculates the visual alpha of this view, which is a combination of the actual
11193     * alpha value and the transitionAlpha value (if set).
11194     */
11195    private float getFinalAlpha() {
11196        if (mTransformationInfo != null) {
11197            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
11198        }
11199        return 1;
11200    }
11201
11202    /**
11203     * This property is hidden and intended only for use by the Fade transition, which
11204     * animates it to produce a visual translucency that does not side-effect (or get
11205     * affected by) the real alpha property. This value is composited with the other
11206     * alpha value (and the AlphaAnimation value, when that is present) to produce
11207     * a final visual translucency result, which is what is passed into the DisplayList.
11208     *
11209     * @hide
11210     */
11211    @ViewDebug.ExportedProperty(category = "drawing")
11212    public float getTransitionAlpha() {
11213        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
11214    }
11215
11216    /**
11217     * Top position of this view relative to its parent.
11218     *
11219     * @return The top of this view, in pixels.
11220     */
11221    @ViewDebug.CapturedViewProperty
11222    public final int getTop() {
11223        return mTop;
11224    }
11225
11226    /**
11227     * Sets the top position of this view relative to its parent. This method is meant to be called
11228     * by the layout system and should not generally be called otherwise, because the property
11229     * may be changed at any time by the layout.
11230     *
11231     * @param top The top of this view, in pixels.
11232     */
11233    public final void setTop(int top) {
11234        if (top != mTop) {
11235            final boolean matrixIsIdentity = hasIdentityMatrix();
11236            if (matrixIsIdentity) {
11237                if (mAttachInfo != null) {
11238                    int minTop;
11239                    int yLoc;
11240                    if (top < mTop) {
11241                        minTop = top;
11242                        yLoc = top - mTop;
11243                    } else {
11244                        minTop = mTop;
11245                        yLoc = 0;
11246                    }
11247                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11248                }
11249            } else {
11250                // Double-invalidation is necessary to capture view's old and new areas
11251                invalidate(true);
11252            }
11253
11254            int width = mRight - mLeft;
11255            int oldHeight = mBottom - mTop;
11256
11257            mTop = top;
11258            mRenderNode.setTop(mTop);
11259
11260            sizeChange(width, mBottom - mTop, width, oldHeight);
11261
11262            if (!matrixIsIdentity) {
11263                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11264                invalidate(true);
11265            }
11266            mBackgroundSizeChanged = true;
11267            if (mForegroundInfo != null) {
11268                mForegroundInfo.mBoundsChanged = true;
11269            }
11270            invalidateParentIfNeeded();
11271            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11272                // View was rejected last time it was drawn by its parent; this may have changed
11273                invalidateParentIfNeeded();
11274            }
11275        }
11276    }
11277
11278    /**
11279     * Bottom position of this view relative to its parent.
11280     *
11281     * @return The bottom of this view, in pixels.
11282     */
11283    @ViewDebug.CapturedViewProperty
11284    public final int getBottom() {
11285        return mBottom;
11286    }
11287
11288    /**
11289     * True if this view has changed since the last time being drawn.
11290     *
11291     * @return The dirty state of this view.
11292     */
11293    public boolean isDirty() {
11294        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11295    }
11296
11297    /**
11298     * Sets the bottom position of this view relative to its parent. This method is meant to be
11299     * called by the layout system and should not generally be called otherwise, because the
11300     * property may be changed at any time by the layout.
11301     *
11302     * @param bottom The bottom of this view, in pixels.
11303     */
11304    public final void setBottom(int bottom) {
11305        if (bottom != mBottom) {
11306            final boolean matrixIsIdentity = hasIdentityMatrix();
11307            if (matrixIsIdentity) {
11308                if (mAttachInfo != null) {
11309                    int maxBottom;
11310                    if (bottom < mBottom) {
11311                        maxBottom = mBottom;
11312                    } else {
11313                        maxBottom = bottom;
11314                    }
11315                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11316                }
11317            } else {
11318                // Double-invalidation is necessary to capture view's old and new areas
11319                invalidate(true);
11320            }
11321
11322            int width = mRight - mLeft;
11323            int oldHeight = mBottom - mTop;
11324
11325            mBottom = bottom;
11326            mRenderNode.setBottom(mBottom);
11327
11328            sizeChange(width, mBottom - mTop, width, oldHeight);
11329
11330            if (!matrixIsIdentity) {
11331                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11332                invalidate(true);
11333            }
11334            mBackgroundSizeChanged = true;
11335            if (mForegroundInfo != null) {
11336                mForegroundInfo.mBoundsChanged = true;
11337            }
11338            invalidateParentIfNeeded();
11339            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11340                // View was rejected last time it was drawn by its parent; this may have changed
11341                invalidateParentIfNeeded();
11342            }
11343        }
11344    }
11345
11346    /**
11347     * Left position of this view relative to its parent.
11348     *
11349     * @return The left edge of this view, in pixels.
11350     */
11351    @ViewDebug.CapturedViewProperty
11352    public final int getLeft() {
11353        return mLeft;
11354    }
11355
11356    /**
11357     * Sets the left position of this view relative to its parent. This method is meant to be called
11358     * by the layout system and should not generally be called otherwise, because the property
11359     * may be changed at any time by the layout.
11360     *
11361     * @param left The left of this view, in pixels.
11362     */
11363    public final void setLeft(int left) {
11364        if (left != mLeft) {
11365            final boolean matrixIsIdentity = hasIdentityMatrix();
11366            if (matrixIsIdentity) {
11367                if (mAttachInfo != null) {
11368                    int minLeft;
11369                    int xLoc;
11370                    if (left < mLeft) {
11371                        minLeft = left;
11372                        xLoc = left - mLeft;
11373                    } else {
11374                        minLeft = mLeft;
11375                        xLoc = 0;
11376                    }
11377                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11378                }
11379            } else {
11380                // Double-invalidation is necessary to capture view's old and new areas
11381                invalidate(true);
11382            }
11383
11384            int oldWidth = mRight - mLeft;
11385            int height = mBottom - mTop;
11386
11387            mLeft = left;
11388            mRenderNode.setLeft(left);
11389
11390            sizeChange(mRight - mLeft, height, oldWidth, height);
11391
11392            if (!matrixIsIdentity) {
11393                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11394                invalidate(true);
11395            }
11396            mBackgroundSizeChanged = true;
11397            if (mForegroundInfo != null) {
11398                mForegroundInfo.mBoundsChanged = true;
11399            }
11400            invalidateParentIfNeeded();
11401            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11402                // View was rejected last time it was drawn by its parent; this may have changed
11403                invalidateParentIfNeeded();
11404            }
11405        }
11406    }
11407
11408    /**
11409     * Right position of this view relative to its parent.
11410     *
11411     * @return The right edge of this view, in pixels.
11412     */
11413    @ViewDebug.CapturedViewProperty
11414    public final int getRight() {
11415        return mRight;
11416    }
11417
11418    /**
11419     * Sets the right position of this view relative to its parent. This method is meant to be called
11420     * by the layout system and should not generally be called otherwise, because the property
11421     * may be changed at any time by the layout.
11422     *
11423     * @param right The right of this view, in pixels.
11424     */
11425    public final void setRight(int right) {
11426        if (right != mRight) {
11427            final boolean matrixIsIdentity = hasIdentityMatrix();
11428            if (matrixIsIdentity) {
11429                if (mAttachInfo != null) {
11430                    int maxRight;
11431                    if (right < mRight) {
11432                        maxRight = mRight;
11433                    } else {
11434                        maxRight = right;
11435                    }
11436                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11437                }
11438            } else {
11439                // Double-invalidation is necessary to capture view's old and new areas
11440                invalidate(true);
11441            }
11442
11443            int oldWidth = mRight - mLeft;
11444            int height = mBottom - mTop;
11445
11446            mRight = right;
11447            mRenderNode.setRight(mRight);
11448
11449            sizeChange(mRight - mLeft, height, oldWidth, height);
11450
11451            if (!matrixIsIdentity) {
11452                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11453                invalidate(true);
11454            }
11455            mBackgroundSizeChanged = true;
11456            if (mForegroundInfo != null) {
11457                mForegroundInfo.mBoundsChanged = true;
11458            }
11459            invalidateParentIfNeeded();
11460            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11461                // View was rejected last time it was drawn by its parent; this may have changed
11462                invalidateParentIfNeeded();
11463            }
11464        }
11465    }
11466
11467    /**
11468     * The visual x position of this view, in pixels. This is equivalent to the
11469     * {@link #setTranslationX(float) translationX} property plus the current
11470     * {@link #getLeft() left} property.
11471     *
11472     * @return The visual x position of this view, in pixels.
11473     */
11474    @ViewDebug.ExportedProperty(category = "drawing")
11475    public float getX() {
11476        return mLeft + getTranslationX();
11477    }
11478
11479    /**
11480     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11481     * {@link #setTranslationX(float) translationX} property to be the difference between
11482     * the x value passed in and the current {@link #getLeft() left} property.
11483     *
11484     * @param x The visual x position of this view, in pixels.
11485     */
11486    public void setX(float x) {
11487        setTranslationX(x - mLeft);
11488    }
11489
11490    /**
11491     * The visual y position of this view, in pixels. This is equivalent to the
11492     * {@link #setTranslationY(float) translationY} property plus the current
11493     * {@link #getTop() top} property.
11494     *
11495     * @return The visual y position of this view, in pixels.
11496     */
11497    @ViewDebug.ExportedProperty(category = "drawing")
11498    public float getY() {
11499        return mTop + getTranslationY();
11500    }
11501
11502    /**
11503     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11504     * {@link #setTranslationY(float) translationY} property to be the difference between
11505     * the y value passed in and the current {@link #getTop() top} property.
11506     *
11507     * @param y The visual y position of this view, in pixels.
11508     */
11509    public void setY(float y) {
11510        setTranslationY(y - mTop);
11511    }
11512
11513    /**
11514     * The visual z position of this view, in pixels. This is equivalent to the
11515     * {@link #setTranslationZ(float) translationZ} property plus the current
11516     * {@link #getElevation() elevation} property.
11517     *
11518     * @return The visual z position of this view, in pixels.
11519     */
11520    @ViewDebug.ExportedProperty(category = "drawing")
11521    public float getZ() {
11522        return getElevation() + getTranslationZ();
11523    }
11524
11525    /**
11526     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11527     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11528     * the x value passed in and the current {@link #getElevation() elevation} property.
11529     *
11530     * @param z The visual z position of this view, in pixels.
11531     */
11532    public void setZ(float z) {
11533        setTranslationZ(z - getElevation());
11534    }
11535
11536    /**
11537     * The base elevation of this view relative to its parent, in pixels.
11538     *
11539     * @return The base depth position of the view, in pixels.
11540     */
11541    @ViewDebug.ExportedProperty(category = "drawing")
11542    public float getElevation() {
11543        return mRenderNode.getElevation();
11544    }
11545
11546    /**
11547     * Sets the base elevation of this view, in pixels.
11548     *
11549     * @attr ref android.R.styleable#View_elevation
11550     */
11551    public void setElevation(float elevation) {
11552        if (elevation != getElevation()) {
11553            invalidateViewProperty(true, false);
11554            mRenderNode.setElevation(elevation);
11555            invalidateViewProperty(false, true);
11556
11557            invalidateParentIfNeededAndWasQuickRejected();
11558        }
11559    }
11560
11561    /**
11562     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11563     * This position is post-layout, in addition to wherever the object's
11564     * layout placed it.
11565     *
11566     * @return The horizontal position of this view relative to its left position, in pixels.
11567     */
11568    @ViewDebug.ExportedProperty(category = "drawing")
11569    public float getTranslationX() {
11570        return mRenderNode.getTranslationX();
11571    }
11572
11573    /**
11574     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11575     * This effectively positions the object post-layout, in addition to wherever the object's
11576     * layout placed it.
11577     *
11578     * @param translationX The horizontal position of this view relative to its left position,
11579     * in pixels.
11580     *
11581     * @attr ref android.R.styleable#View_translationX
11582     */
11583    public void setTranslationX(float translationX) {
11584        if (translationX != getTranslationX()) {
11585            invalidateViewProperty(true, false);
11586            mRenderNode.setTranslationX(translationX);
11587            invalidateViewProperty(false, true);
11588
11589            invalidateParentIfNeededAndWasQuickRejected();
11590            notifySubtreeAccessibilityStateChangedIfNeeded();
11591        }
11592    }
11593
11594    /**
11595     * The vertical location of this view relative to its {@link #getTop() top} position.
11596     * This position is post-layout, in addition to wherever the object's
11597     * layout placed it.
11598     *
11599     * @return The vertical position of this view relative to its top position,
11600     * in pixels.
11601     */
11602    @ViewDebug.ExportedProperty(category = "drawing")
11603    public float getTranslationY() {
11604        return mRenderNode.getTranslationY();
11605    }
11606
11607    /**
11608     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11609     * This effectively positions the object post-layout, in addition to wherever the object's
11610     * layout placed it.
11611     *
11612     * @param translationY The vertical position of this view relative to its top position,
11613     * in pixels.
11614     *
11615     * @attr ref android.R.styleable#View_translationY
11616     */
11617    public void setTranslationY(float translationY) {
11618        if (translationY != getTranslationY()) {
11619            invalidateViewProperty(true, false);
11620            mRenderNode.setTranslationY(translationY);
11621            invalidateViewProperty(false, true);
11622
11623            invalidateParentIfNeededAndWasQuickRejected();
11624            notifySubtreeAccessibilityStateChangedIfNeeded();
11625        }
11626    }
11627
11628    /**
11629     * The depth location of this view relative to its {@link #getElevation() elevation}.
11630     *
11631     * @return The depth of this view relative to its elevation.
11632     */
11633    @ViewDebug.ExportedProperty(category = "drawing")
11634    public float getTranslationZ() {
11635        return mRenderNode.getTranslationZ();
11636    }
11637
11638    /**
11639     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11640     *
11641     * @attr ref android.R.styleable#View_translationZ
11642     */
11643    public void setTranslationZ(float translationZ) {
11644        if (translationZ != getTranslationZ()) {
11645            invalidateViewProperty(true, false);
11646            mRenderNode.setTranslationZ(translationZ);
11647            invalidateViewProperty(false, true);
11648
11649            invalidateParentIfNeededAndWasQuickRejected();
11650        }
11651    }
11652
11653    /** @hide */
11654    public void setAnimationMatrix(Matrix matrix) {
11655        invalidateViewProperty(true, false);
11656        mRenderNode.setAnimationMatrix(matrix);
11657        invalidateViewProperty(false, true);
11658
11659        invalidateParentIfNeededAndWasQuickRejected();
11660    }
11661
11662    /**
11663     * Returns the current StateListAnimator if exists.
11664     *
11665     * @return StateListAnimator or null if it does not exists
11666     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11667     */
11668    public StateListAnimator getStateListAnimator() {
11669        return mStateListAnimator;
11670    }
11671
11672    /**
11673     * Attaches the provided StateListAnimator to this View.
11674     * <p>
11675     * Any previously attached StateListAnimator will be detached.
11676     *
11677     * @param stateListAnimator The StateListAnimator to update the view
11678     * @see {@link android.animation.StateListAnimator}
11679     */
11680    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11681        if (mStateListAnimator == stateListAnimator) {
11682            return;
11683        }
11684        if (mStateListAnimator != null) {
11685            mStateListAnimator.setTarget(null);
11686        }
11687        mStateListAnimator = stateListAnimator;
11688        if (stateListAnimator != null) {
11689            stateListAnimator.setTarget(this);
11690            if (isAttachedToWindow()) {
11691                stateListAnimator.setState(getDrawableState());
11692            }
11693        }
11694    }
11695
11696    /**
11697     * Returns whether the Outline should be used to clip the contents of the View.
11698     * <p>
11699     * Note that this flag will only be respected if the View's Outline returns true from
11700     * {@link Outline#canClip()}.
11701     *
11702     * @see #setOutlineProvider(ViewOutlineProvider)
11703     * @see #setClipToOutline(boolean)
11704     */
11705    public final boolean getClipToOutline() {
11706        return mRenderNode.getClipToOutline();
11707    }
11708
11709    /**
11710     * Sets whether the View's Outline should be used to clip the contents of the View.
11711     * <p>
11712     * Only a single non-rectangular clip can be applied on a View at any time.
11713     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11714     * circular reveal} animation take priority over Outline clipping, and
11715     * child Outline clipping takes priority over Outline clipping done by a
11716     * parent.
11717     * <p>
11718     * Note that this flag will only be respected if the View's Outline returns true from
11719     * {@link Outline#canClip()}.
11720     *
11721     * @see #setOutlineProvider(ViewOutlineProvider)
11722     * @see #getClipToOutline()
11723     */
11724    public void setClipToOutline(boolean clipToOutline) {
11725        damageInParent();
11726        if (getClipToOutline() != clipToOutline) {
11727            mRenderNode.setClipToOutline(clipToOutline);
11728        }
11729    }
11730
11731    // correspond to the enum values of View_outlineProvider
11732    private static final int PROVIDER_BACKGROUND = 0;
11733    private static final int PROVIDER_NONE = 1;
11734    private static final int PROVIDER_BOUNDS = 2;
11735    private static final int PROVIDER_PADDED_BOUNDS = 3;
11736    private void setOutlineProviderFromAttribute(int providerInt) {
11737        switch (providerInt) {
11738            case PROVIDER_BACKGROUND:
11739                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11740                break;
11741            case PROVIDER_NONE:
11742                setOutlineProvider(null);
11743                break;
11744            case PROVIDER_BOUNDS:
11745                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11746                break;
11747            case PROVIDER_PADDED_BOUNDS:
11748                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11749                break;
11750        }
11751    }
11752
11753    /**
11754     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11755     * the shape of the shadow it casts, and enables outline clipping.
11756     * <p>
11757     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11758     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11759     * outline provider with this method allows this behavior to be overridden.
11760     * <p>
11761     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11762     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11763     * <p>
11764     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11765     *
11766     * @see #setClipToOutline(boolean)
11767     * @see #getClipToOutline()
11768     * @see #getOutlineProvider()
11769     */
11770    public void setOutlineProvider(ViewOutlineProvider provider) {
11771        mOutlineProvider = provider;
11772        invalidateOutline();
11773    }
11774
11775    /**
11776     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11777     * that defines the shape of the shadow it casts, and enables outline clipping.
11778     *
11779     * @see #setOutlineProvider(ViewOutlineProvider)
11780     */
11781    public ViewOutlineProvider getOutlineProvider() {
11782        return mOutlineProvider;
11783    }
11784
11785    /**
11786     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11787     *
11788     * @see #setOutlineProvider(ViewOutlineProvider)
11789     */
11790    public void invalidateOutline() {
11791        rebuildOutline();
11792
11793        notifySubtreeAccessibilityStateChangedIfNeeded();
11794        invalidateViewProperty(false, false);
11795    }
11796
11797    /**
11798     * Internal version of {@link #invalidateOutline()} which invalidates the
11799     * outline without invalidating the view itself. This is intended to be called from
11800     * within methods in the View class itself which are the result of the view being
11801     * invalidated already. For example, when we are drawing the background of a View,
11802     * we invalidate the outline in case it changed in the meantime, but we do not
11803     * need to invalidate the view because we're already drawing the background as part
11804     * of drawing the view in response to an earlier invalidation of the view.
11805     */
11806    private void rebuildOutline() {
11807        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11808        if (mAttachInfo == null) return;
11809
11810        if (mOutlineProvider == null) {
11811            // no provider, remove outline
11812            mRenderNode.setOutline(null);
11813        } else {
11814            final Outline outline = mAttachInfo.mTmpOutline;
11815            outline.setEmpty();
11816            outline.setAlpha(1.0f);
11817
11818            mOutlineProvider.getOutline(this, outline);
11819            mRenderNode.setOutline(outline);
11820        }
11821    }
11822
11823    /**
11824     * HierarchyViewer only
11825     *
11826     * @hide
11827     */
11828    @ViewDebug.ExportedProperty(category = "drawing")
11829    public boolean hasShadow() {
11830        return mRenderNode.hasShadow();
11831    }
11832
11833
11834    /** @hide */
11835    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11836        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11837        invalidateViewProperty(false, false);
11838    }
11839
11840    /**
11841     * Hit rectangle in parent's coordinates
11842     *
11843     * @param outRect The hit rectangle of the view.
11844     */
11845    public void getHitRect(Rect outRect) {
11846        if (hasIdentityMatrix() || mAttachInfo == null) {
11847            outRect.set(mLeft, mTop, mRight, mBottom);
11848        } else {
11849            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11850            tmpRect.set(0, 0, getWidth(), getHeight());
11851            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11852            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11853                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11854        }
11855    }
11856
11857    /**
11858     * Determines whether the given point, in local coordinates is inside the view.
11859     */
11860    /*package*/ final boolean pointInView(float localX, float localY) {
11861        return localX >= 0 && localX < (mRight - mLeft)
11862                && localY >= 0 && localY < (mBottom - mTop);
11863    }
11864
11865    /**
11866     * Utility method to determine whether the given point, in local coordinates,
11867     * is inside the view, where the area of the view is expanded by the slop factor.
11868     * This method is called while processing touch-move events to determine if the event
11869     * is still within the view.
11870     *
11871     * @hide
11872     */
11873    public boolean pointInView(float localX, float localY, float slop) {
11874        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11875                localY < ((mBottom - mTop) + slop);
11876    }
11877
11878    /**
11879     * When a view has focus and the user navigates away from it, the next view is searched for
11880     * starting from the rectangle filled in by this method.
11881     *
11882     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11883     * of the view.  However, if your view maintains some idea of internal selection,
11884     * such as a cursor, or a selected row or column, you should override this method and
11885     * fill in a more specific rectangle.
11886     *
11887     * @param r The rectangle to fill in, in this view's coordinates.
11888     */
11889    public void getFocusedRect(Rect r) {
11890        getDrawingRect(r);
11891    }
11892
11893    /**
11894     * If some part of this view is not clipped by any of its parents, then
11895     * return that area in r in global (root) coordinates. To convert r to local
11896     * coordinates (without taking possible View rotations into account), offset
11897     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11898     * If the view is completely clipped or translated out, return false.
11899     *
11900     * @param r If true is returned, r holds the global coordinates of the
11901     *        visible portion of this view.
11902     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11903     *        between this view and its root. globalOffet may be null.
11904     * @return true if r is non-empty (i.e. part of the view is visible at the
11905     *         root level.
11906     */
11907    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11908        int width = mRight - mLeft;
11909        int height = mBottom - mTop;
11910        if (width > 0 && height > 0) {
11911            r.set(0, 0, width, height);
11912            if (globalOffset != null) {
11913                globalOffset.set(-mScrollX, -mScrollY);
11914            }
11915            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11916        }
11917        return false;
11918    }
11919
11920    public final boolean getGlobalVisibleRect(Rect r) {
11921        return getGlobalVisibleRect(r, null);
11922    }
11923
11924    public final boolean getLocalVisibleRect(Rect r) {
11925        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11926        if (getGlobalVisibleRect(r, offset)) {
11927            r.offset(-offset.x, -offset.y); // make r local
11928            return true;
11929        }
11930        return false;
11931    }
11932
11933    /**
11934     * Offset this view's vertical location by the specified number of pixels.
11935     *
11936     * @param offset the number of pixels to offset the view by
11937     */
11938    public void offsetTopAndBottom(int offset) {
11939        if (offset != 0) {
11940            final boolean matrixIsIdentity = hasIdentityMatrix();
11941            if (matrixIsIdentity) {
11942                if (isHardwareAccelerated()) {
11943                    invalidateViewProperty(false, false);
11944                } else {
11945                    final ViewParent p = mParent;
11946                    if (p != null && mAttachInfo != null) {
11947                        final Rect r = mAttachInfo.mTmpInvalRect;
11948                        int minTop;
11949                        int maxBottom;
11950                        int yLoc;
11951                        if (offset < 0) {
11952                            minTop = mTop + offset;
11953                            maxBottom = mBottom;
11954                            yLoc = offset;
11955                        } else {
11956                            minTop = mTop;
11957                            maxBottom = mBottom + offset;
11958                            yLoc = 0;
11959                        }
11960                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11961                        p.invalidateChild(this, r);
11962                    }
11963                }
11964            } else {
11965                invalidateViewProperty(false, false);
11966            }
11967
11968            mTop += offset;
11969            mBottom += offset;
11970            mRenderNode.offsetTopAndBottom(offset);
11971            if (isHardwareAccelerated()) {
11972                invalidateViewProperty(false, false);
11973            } else {
11974                if (!matrixIsIdentity) {
11975                    invalidateViewProperty(false, true);
11976                }
11977                invalidateParentIfNeeded();
11978            }
11979            notifySubtreeAccessibilityStateChangedIfNeeded();
11980        }
11981    }
11982
11983    /**
11984     * Offset this view's horizontal location by the specified amount of pixels.
11985     *
11986     * @param offset the number of pixels to offset the view by
11987     */
11988    public void offsetLeftAndRight(int offset) {
11989        if (offset != 0) {
11990            final boolean matrixIsIdentity = hasIdentityMatrix();
11991            if (matrixIsIdentity) {
11992                if (isHardwareAccelerated()) {
11993                    invalidateViewProperty(false, false);
11994                } else {
11995                    final ViewParent p = mParent;
11996                    if (p != null && mAttachInfo != null) {
11997                        final Rect r = mAttachInfo.mTmpInvalRect;
11998                        int minLeft;
11999                        int maxRight;
12000                        if (offset < 0) {
12001                            minLeft = mLeft + offset;
12002                            maxRight = mRight;
12003                        } else {
12004                            minLeft = mLeft;
12005                            maxRight = mRight + offset;
12006                        }
12007                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
12008                        p.invalidateChild(this, r);
12009                    }
12010                }
12011            } else {
12012                invalidateViewProperty(false, false);
12013            }
12014
12015            mLeft += offset;
12016            mRight += offset;
12017            mRenderNode.offsetLeftAndRight(offset);
12018            if (isHardwareAccelerated()) {
12019                invalidateViewProperty(false, false);
12020            } else {
12021                if (!matrixIsIdentity) {
12022                    invalidateViewProperty(false, true);
12023                }
12024                invalidateParentIfNeeded();
12025            }
12026            notifySubtreeAccessibilityStateChangedIfNeeded();
12027        }
12028    }
12029
12030    /**
12031     * Get the LayoutParams associated with this view. All views should have
12032     * layout parameters. These supply parameters to the <i>parent</i> of this
12033     * view specifying how it should be arranged. There are many subclasses of
12034     * ViewGroup.LayoutParams, and these correspond to the different subclasses
12035     * of ViewGroup that are responsible for arranging their children.
12036     *
12037     * This method may return null if this View is not attached to a parent
12038     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
12039     * was not invoked successfully. When a View is attached to a parent
12040     * ViewGroup, this method must not return null.
12041     *
12042     * @return The LayoutParams associated with this view, or null if no
12043     *         parameters have been set yet
12044     */
12045    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
12046    public ViewGroup.LayoutParams getLayoutParams() {
12047        return mLayoutParams;
12048    }
12049
12050    /**
12051     * Set the layout parameters associated with this view. These supply
12052     * parameters to the <i>parent</i> of this view specifying how it should be
12053     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
12054     * correspond to the different subclasses of ViewGroup that are responsible
12055     * for arranging their children.
12056     *
12057     * @param params The layout parameters for this view, cannot be null
12058     */
12059    public void setLayoutParams(ViewGroup.LayoutParams params) {
12060        if (params == null) {
12061            throw new NullPointerException("Layout parameters cannot be null");
12062        }
12063        mLayoutParams = params;
12064        resolveLayoutParams();
12065        if (mParent instanceof ViewGroup) {
12066            ((ViewGroup) mParent).onSetLayoutParams(this, params);
12067        }
12068        requestLayout();
12069    }
12070
12071    /**
12072     * Resolve the layout parameters depending on the resolved layout direction
12073     *
12074     * @hide
12075     */
12076    public void resolveLayoutParams() {
12077        if (mLayoutParams != null) {
12078            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
12079        }
12080    }
12081
12082    /**
12083     * Set the scrolled position of your view. This will cause a call to
12084     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12085     * invalidated.
12086     * @param x the x position to scroll to
12087     * @param y the y position to scroll to
12088     */
12089    public void scrollTo(int x, int y) {
12090        if (mScrollX != x || mScrollY != y) {
12091            int oldX = mScrollX;
12092            int oldY = mScrollY;
12093            mScrollX = x;
12094            mScrollY = y;
12095            invalidateParentCaches();
12096            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
12097            if (!awakenScrollBars()) {
12098                postInvalidateOnAnimation();
12099            }
12100        }
12101    }
12102
12103    /**
12104     * Move the scrolled position of your view. This will cause a call to
12105     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12106     * invalidated.
12107     * @param x the amount of pixels to scroll by horizontally
12108     * @param y the amount of pixels to scroll by vertically
12109     */
12110    public void scrollBy(int x, int y) {
12111        scrollTo(mScrollX + x, mScrollY + y);
12112    }
12113
12114    /**
12115     * <p>Trigger the scrollbars to draw. When invoked this method starts an
12116     * animation to fade the scrollbars out after a default delay. If a subclass
12117     * provides animated scrolling, the start delay should equal the duration
12118     * of the scrolling animation.</p>
12119     *
12120     * <p>The animation starts only if at least one of the scrollbars is
12121     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
12122     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12123     * this method returns true, and false otherwise. If the animation is
12124     * started, this method calls {@link #invalidate()}; in that case the
12125     * caller should not call {@link #invalidate()}.</p>
12126     *
12127     * <p>This method should be invoked every time a subclass directly updates
12128     * the scroll parameters.</p>
12129     *
12130     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
12131     * and {@link #scrollTo(int, int)}.</p>
12132     *
12133     * @return true if the animation is played, false otherwise
12134     *
12135     * @see #awakenScrollBars(int)
12136     * @see #scrollBy(int, int)
12137     * @see #scrollTo(int, int)
12138     * @see #isHorizontalScrollBarEnabled()
12139     * @see #isVerticalScrollBarEnabled()
12140     * @see #setHorizontalScrollBarEnabled(boolean)
12141     * @see #setVerticalScrollBarEnabled(boolean)
12142     */
12143    protected boolean awakenScrollBars() {
12144        return mScrollCache != null &&
12145                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
12146    }
12147
12148    /**
12149     * Trigger the scrollbars to draw.
12150     * This method differs from awakenScrollBars() only in its default duration.
12151     * initialAwakenScrollBars() will show the scroll bars for longer than
12152     * usual to give the user more of a chance to notice them.
12153     *
12154     * @return true if the animation is played, false otherwise.
12155     */
12156    private boolean initialAwakenScrollBars() {
12157        return mScrollCache != null &&
12158                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
12159    }
12160
12161    /**
12162     * <p>
12163     * Trigger the scrollbars to draw. When invoked this method starts an
12164     * animation to fade the scrollbars out after a fixed delay. If a subclass
12165     * provides animated scrolling, the start delay should equal the duration of
12166     * the scrolling animation.
12167     * </p>
12168     *
12169     * <p>
12170     * The animation starts only if at least one of the scrollbars is enabled,
12171     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12172     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12173     * this method returns true, and false otherwise. If the animation is
12174     * started, this method calls {@link #invalidate()}; in that case the caller
12175     * should not call {@link #invalidate()}.
12176     * </p>
12177     *
12178     * <p>
12179     * This method should be invoked every time a subclass directly updates the
12180     * scroll parameters.
12181     * </p>
12182     *
12183     * @param startDelay the delay, in milliseconds, after which the animation
12184     *        should start; when the delay is 0, the animation starts
12185     *        immediately
12186     * @return true if the animation is played, false otherwise
12187     *
12188     * @see #scrollBy(int, int)
12189     * @see #scrollTo(int, int)
12190     * @see #isHorizontalScrollBarEnabled()
12191     * @see #isVerticalScrollBarEnabled()
12192     * @see #setHorizontalScrollBarEnabled(boolean)
12193     * @see #setVerticalScrollBarEnabled(boolean)
12194     */
12195    protected boolean awakenScrollBars(int startDelay) {
12196        return awakenScrollBars(startDelay, true);
12197    }
12198
12199    /**
12200     * <p>
12201     * Trigger the scrollbars to draw. When invoked this method starts an
12202     * animation to fade the scrollbars out after a fixed delay. If a subclass
12203     * provides animated scrolling, the start delay should equal the duration of
12204     * the scrolling animation.
12205     * </p>
12206     *
12207     * <p>
12208     * The animation starts only if at least one of the scrollbars is enabled,
12209     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12210     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12211     * this method returns true, and false otherwise. If the animation is
12212     * started, this method calls {@link #invalidate()} if the invalidate parameter
12213     * is set to true; in that case the caller
12214     * should not call {@link #invalidate()}.
12215     * </p>
12216     *
12217     * <p>
12218     * This method should be invoked every time a subclass directly updates the
12219     * scroll parameters.
12220     * </p>
12221     *
12222     * @param startDelay the delay, in milliseconds, after which the animation
12223     *        should start; when the delay is 0, the animation starts
12224     *        immediately
12225     *
12226     * @param invalidate Whether this method should call invalidate
12227     *
12228     * @return true if the animation is played, false otherwise
12229     *
12230     * @see #scrollBy(int, int)
12231     * @see #scrollTo(int, int)
12232     * @see #isHorizontalScrollBarEnabled()
12233     * @see #isVerticalScrollBarEnabled()
12234     * @see #setHorizontalScrollBarEnabled(boolean)
12235     * @see #setVerticalScrollBarEnabled(boolean)
12236     */
12237    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
12238        final ScrollabilityCache scrollCache = mScrollCache;
12239
12240        if (scrollCache == null || !scrollCache.fadeScrollBars) {
12241            return false;
12242        }
12243
12244        if (scrollCache.scrollBar == null) {
12245            scrollCache.scrollBar = new ScrollBarDrawable();
12246            scrollCache.scrollBar.setCallback(this);
12247            scrollCache.scrollBar.setState(getDrawableState());
12248        }
12249
12250        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
12251
12252            if (invalidate) {
12253                // Invalidate to show the scrollbars
12254                postInvalidateOnAnimation();
12255            }
12256
12257            if (scrollCache.state == ScrollabilityCache.OFF) {
12258                // FIXME: this is copied from WindowManagerService.
12259                // We should get this value from the system when it
12260                // is possible to do so.
12261                final int KEY_REPEAT_FIRST_DELAY = 750;
12262                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
12263            }
12264
12265            // Tell mScrollCache when we should start fading. This may
12266            // extend the fade start time if one was already scheduled
12267            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
12268            scrollCache.fadeStartTime = fadeStartTime;
12269            scrollCache.state = ScrollabilityCache.ON;
12270
12271            // Schedule our fader to run, unscheduling any old ones first
12272            if (mAttachInfo != null) {
12273                mAttachInfo.mHandler.removeCallbacks(scrollCache);
12274                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
12275            }
12276
12277            return true;
12278        }
12279
12280        return false;
12281    }
12282
12283    /**
12284     * Do not invalidate views which are not visible and which are not running an animation. They
12285     * will not get drawn and they should not set dirty flags as if they will be drawn
12286     */
12287    private boolean skipInvalidate() {
12288        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
12289                (!(mParent instanceof ViewGroup) ||
12290                        !((ViewGroup) mParent).isViewTransitioning(this));
12291    }
12292
12293    /**
12294     * Mark the area defined by dirty as needing to be drawn. If the view is
12295     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12296     * point in the future.
12297     * <p>
12298     * This must be called from a UI thread. To call from a non-UI thread, call
12299     * {@link #postInvalidate()}.
12300     * <p>
12301     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
12302     * {@code dirty}.
12303     *
12304     * @param dirty the rectangle representing the bounds of the dirty region
12305     */
12306    public void invalidate(Rect dirty) {
12307        final int scrollX = mScrollX;
12308        final int scrollY = mScrollY;
12309        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
12310                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
12311    }
12312
12313    /**
12314     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
12315     * coordinates of the dirty rect are relative to the view. If the view is
12316     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12317     * point in the future.
12318     * <p>
12319     * This must be called from a UI thread. To call from a non-UI thread, call
12320     * {@link #postInvalidate()}.
12321     *
12322     * @param l the left position of the dirty region
12323     * @param t the top position of the dirty region
12324     * @param r the right position of the dirty region
12325     * @param b the bottom position of the dirty region
12326     */
12327    public void invalidate(int l, int t, int r, int b) {
12328        final int scrollX = mScrollX;
12329        final int scrollY = mScrollY;
12330        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
12331    }
12332
12333    /**
12334     * Invalidate the whole view. If the view is visible,
12335     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
12336     * the future.
12337     * <p>
12338     * This must be called from a UI thread. To call from a non-UI thread, call
12339     * {@link #postInvalidate()}.
12340     */
12341    public void invalidate() {
12342        invalidate(true);
12343    }
12344
12345    /**
12346     * This is where the invalidate() work actually happens. A full invalidate()
12347     * causes the drawing cache to be invalidated, but this function can be
12348     * called with invalidateCache set to false to skip that invalidation step
12349     * for cases that do not need it (for example, a component that remains at
12350     * the same dimensions with the same content).
12351     *
12352     * @param invalidateCache Whether the drawing cache for this view should be
12353     *            invalidated as well. This is usually true for a full
12354     *            invalidate, but may be set to false if the View's contents or
12355     *            dimensions have not changed.
12356     */
12357    void invalidate(boolean invalidateCache) {
12358        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
12359    }
12360
12361    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
12362            boolean fullInvalidate) {
12363        if (mGhostView != null) {
12364            mGhostView.invalidate(true);
12365            return;
12366        }
12367
12368        if (skipInvalidate()) {
12369            return;
12370        }
12371
12372        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
12373                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
12374                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
12375                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
12376            if (fullInvalidate) {
12377                mLastIsOpaque = isOpaque();
12378                mPrivateFlags &= ~PFLAG_DRAWN;
12379            }
12380
12381            mPrivateFlags |= PFLAG_DIRTY;
12382
12383            if (invalidateCache) {
12384                mPrivateFlags |= PFLAG_INVALIDATED;
12385                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12386            }
12387
12388            // Propagate the damage rectangle to the parent view.
12389            final AttachInfo ai = mAttachInfo;
12390            final ViewParent p = mParent;
12391            if (p != null && ai != null && l < r && t < b) {
12392                final Rect damage = ai.mTmpInvalRect;
12393                damage.set(l, t, r, b);
12394                p.invalidateChild(this, damage);
12395            }
12396
12397            // Damage the entire projection receiver, if necessary.
12398            if (mBackground != null && mBackground.isProjected()) {
12399                final View receiver = getProjectionReceiver();
12400                if (receiver != null) {
12401                    receiver.damageInParent();
12402                }
12403            }
12404
12405            // Damage the entire IsolatedZVolume receiving this view's shadow.
12406            if (isHardwareAccelerated() && getZ() != 0) {
12407                damageShadowReceiver();
12408            }
12409        }
12410    }
12411
12412    /**
12413     * @return this view's projection receiver, or {@code null} if none exists
12414     */
12415    private View getProjectionReceiver() {
12416        ViewParent p = getParent();
12417        while (p != null && p instanceof View) {
12418            final View v = (View) p;
12419            if (v.isProjectionReceiver()) {
12420                return v;
12421            }
12422            p = p.getParent();
12423        }
12424
12425        return null;
12426    }
12427
12428    /**
12429     * @return whether the view is a projection receiver
12430     */
12431    private boolean isProjectionReceiver() {
12432        return mBackground != null;
12433    }
12434
12435    /**
12436     * Damage area of the screen that can be covered by this View's shadow.
12437     *
12438     * This method will guarantee that any changes to shadows cast by a View
12439     * are damaged on the screen for future redraw.
12440     */
12441    private void damageShadowReceiver() {
12442        final AttachInfo ai = mAttachInfo;
12443        if (ai != null) {
12444            ViewParent p = getParent();
12445            if (p != null && p instanceof ViewGroup) {
12446                final ViewGroup vg = (ViewGroup) p;
12447                vg.damageInParent();
12448            }
12449        }
12450    }
12451
12452    /**
12453     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
12454     * set any flags or handle all of the cases handled by the default invalidation methods.
12455     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
12456     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
12457     * walk up the hierarchy, transforming the dirty rect as necessary.
12458     *
12459     * The method also handles normal invalidation logic if display list properties are not
12460     * being used in this view. The invalidateParent and forceRedraw flags are used by that
12461     * backup approach, to handle these cases used in the various property-setting methods.
12462     *
12463     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
12464     * are not being used in this view
12465     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
12466     * list properties are not being used in this view
12467     */
12468    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
12469        if (!isHardwareAccelerated()
12470                || !mRenderNode.isValid()
12471                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
12472            if (invalidateParent) {
12473                invalidateParentCaches();
12474            }
12475            if (forceRedraw) {
12476                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12477            }
12478            invalidate(false);
12479        } else {
12480            damageInParent();
12481        }
12482        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
12483            damageShadowReceiver();
12484        }
12485    }
12486
12487    /**
12488     * Tells the parent view to damage this view's bounds.
12489     *
12490     * @hide
12491     */
12492    protected void damageInParent() {
12493        final AttachInfo ai = mAttachInfo;
12494        final ViewParent p = mParent;
12495        if (p != null && ai != null) {
12496            final Rect r = ai.mTmpInvalRect;
12497            r.set(0, 0, mRight - mLeft, mBottom - mTop);
12498            if (mParent instanceof ViewGroup) {
12499                ((ViewGroup) mParent).damageChild(this, r);
12500            } else {
12501                mParent.invalidateChild(this, r);
12502            }
12503        }
12504    }
12505
12506    /**
12507     * Utility method to transform a given Rect by the current matrix of this view.
12508     */
12509    void transformRect(final Rect rect) {
12510        if (!getMatrix().isIdentity()) {
12511            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12512            boundingRect.set(rect);
12513            getMatrix().mapRect(boundingRect);
12514            rect.set((int) Math.floor(boundingRect.left),
12515                    (int) Math.floor(boundingRect.top),
12516                    (int) Math.ceil(boundingRect.right),
12517                    (int) Math.ceil(boundingRect.bottom));
12518        }
12519    }
12520
12521    /**
12522     * Used to indicate that the parent of this view should clear its caches. This functionality
12523     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12524     * which is necessary when various parent-managed properties of the view change, such as
12525     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12526     * clears the parent caches and does not causes an invalidate event.
12527     *
12528     * @hide
12529     */
12530    protected void invalidateParentCaches() {
12531        if (mParent instanceof View) {
12532            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12533        }
12534    }
12535
12536    /**
12537     * Used to indicate that the parent of this view should be invalidated. This functionality
12538     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12539     * which is necessary when various parent-managed properties of the view change, such as
12540     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12541     * an invalidation event to the parent.
12542     *
12543     * @hide
12544     */
12545    protected void invalidateParentIfNeeded() {
12546        if (isHardwareAccelerated() && mParent instanceof View) {
12547            ((View) mParent).invalidate(true);
12548        }
12549    }
12550
12551    /**
12552     * @hide
12553     */
12554    protected void invalidateParentIfNeededAndWasQuickRejected() {
12555        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12556            // View was rejected last time it was drawn by its parent; this may have changed
12557            invalidateParentIfNeeded();
12558        }
12559    }
12560
12561    /**
12562     * Indicates whether this View is opaque. An opaque View guarantees that it will
12563     * draw all the pixels overlapping its bounds using a fully opaque color.
12564     *
12565     * Subclasses of View should override this method whenever possible to indicate
12566     * whether an instance is opaque. Opaque Views are treated in a special way by
12567     * the View hierarchy, possibly allowing it to perform optimizations during
12568     * invalidate/draw passes.
12569     *
12570     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12571     */
12572    @ViewDebug.ExportedProperty(category = "drawing")
12573    public boolean isOpaque() {
12574        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12575                getFinalAlpha() >= 1.0f;
12576    }
12577
12578    /**
12579     * @hide
12580     */
12581    protected void computeOpaqueFlags() {
12582        // Opaque if:
12583        //   - Has a background
12584        //   - Background is opaque
12585        //   - Doesn't have scrollbars or scrollbars overlay
12586
12587        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12588            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12589        } else {
12590            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12591        }
12592
12593        final int flags = mViewFlags;
12594        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12595                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12596                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12597            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12598        } else {
12599            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12600        }
12601    }
12602
12603    /**
12604     * @hide
12605     */
12606    protected boolean hasOpaqueScrollbars() {
12607        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12608    }
12609
12610    /**
12611     * @return A handler associated with the thread running the View. This
12612     * handler can be used to pump events in the UI events queue.
12613     */
12614    public Handler getHandler() {
12615        final AttachInfo attachInfo = mAttachInfo;
12616        if (attachInfo != null) {
12617            return attachInfo.mHandler;
12618        }
12619        return null;
12620    }
12621
12622    /**
12623     * Gets the view root associated with the View.
12624     * @return The view root, or null if none.
12625     * @hide
12626     */
12627    public ViewRootImpl getViewRootImpl() {
12628        if (mAttachInfo != null) {
12629            return mAttachInfo.mViewRootImpl;
12630        }
12631        return null;
12632    }
12633
12634    /**
12635     * @hide
12636     */
12637    public HardwareRenderer getHardwareRenderer() {
12638        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12639    }
12640
12641    /**
12642     * <p>Causes the Runnable to be added to the message queue.
12643     * The runnable will be run on the user interface thread.</p>
12644     *
12645     * @param action The Runnable that will be executed.
12646     *
12647     * @return Returns true if the Runnable was successfully placed in to the
12648     *         message queue.  Returns false on failure, usually because the
12649     *         looper processing the message queue is exiting.
12650     *
12651     * @see #postDelayed
12652     * @see #removeCallbacks
12653     */
12654    public boolean post(Runnable action) {
12655        final AttachInfo attachInfo = mAttachInfo;
12656        if (attachInfo != null) {
12657            return attachInfo.mHandler.post(action);
12658        }
12659        // Assume that post will succeed later
12660        ViewRootImpl.getRunQueue().post(action);
12661        return true;
12662    }
12663
12664    /**
12665     * <p>Causes the Runnable to be added to the message queue, to be run
12666     * after the specified amount of time elapses.
12667     * The runnable will be run on the user interface thread.</p>
12668     *
12669     * @param action The Runnable that will be executed.
12670     * @param delayMillis The delay (in milliseconds) until the Runnable
12671     *        will be executed.
12672     *
12673     * @return true if the Runnable was successfully placed in to the
12674     *         message queue.  Returns false on failure, usually because the
12675     *         looper processing the message queue is exiting.  Note that a
12676     *         result of true does not mean the Runnable will be processed --
12677     *         if the looper is quit before the delivery time of the message
12678     *         occurs then the message will be dropped.
12679     *
12680     * @see #post
12681     * @see #removeCallbacks
12682     */
12683    public boolean postDelayed(Runnable action, long delayMillis) {
12684        final AttachInfo attachInfo = mAttachInfo;
12685        if (attachInfo != null) {
12686            return attachInfo.mHandler.postDelayed(action, delayMillis);
12687        }
12688        // Assume that post will succeed later
12689        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12690        return true;
12691    }
12692
12693    /**
12694     * <p>Causes the Runnable to execute on the next animation time step.
12695     * The runnable will be run on the user interface thread.</p>
12696     *
12697     * @param action The Runnable that will be executed.
12698     *
12699     * @see #postOnAnimationDelayed
12700     * @see #removeCallbacks
12701     */
12702    public void postOnAnimation(Runnable action) {
12703        final AttachInfo attachInfo = mAttachInfo;
12704        if (attachInfo != null) {
12705            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12706                    Choreographer.CALLBACK_ANIMATION, action, null);
12707        } else {
12708            // Assume that post will succeed later
12709            ViewRootImpl.getRunQueue().post(action);
12710        }
12711    }
12712
12713    /**
12714     * <p>Causes the Runnable to execute on the next animation time step,
12715     * after the specified amount of time elapses.
12716     * The runnable will be run on the user interface thread.</p>
12717     *
12718     * @param action The Runnable that will be executed.
12719     * @param delayMillis The delay (in milliseconds) until the Runnable
12720     *        will be executed.
12721     *
12722     * @see #postOnAnimation
12723     * @see #removeCallbacks
12724     */
12725    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12726        final AttachInfo attachInfo = mAttachInfo;
12727        if (attachInfo != null) {
12728            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12729                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12730        } else {
12731            // Assume that post will succeed later
12732            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12733        }
12734    }
12735
12736    /**
12737     * <p>Removes the specified Runnable from the message queue.</p>
12738     *
12739     * @param action The Runnable to remove from the message handling queue
12740     *
12741     * @return true if this view could ask the Handler to remove the Runnable,
12742     *         false otherwise. When the returned value is true, the Runnable
12743     *         may or may not have been actually removed from the message queue
12744     *         (for instance, if the Runnable was not in the queue already.)
12745     *
12746     * @see #post
12747     * @see #postDelayed
12748     * @see #postOnAnimation
12749     * @see #postOnAnimationDelayed
12750     */
12751    public boolean removeCallbacks(Runnable action) {
12752        if (action != null) {
12753            final AttachInfo attachInfo = mAttachInfo;
12754            if (attachInfo != null) {
12755                attachInfo.mHandler.removeCallbacks(action);
12756                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12757                        Choreographer.CALLBACK_ANIMATION, action, null);
12758            }
12759            // Assume that post will succeed later
12760            ViewRootImpl.getRunQueue().removeCallbacks(action);
12761        }
12762        return true;
12763    }
12764
12765    /**
12766     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12767     * Use this to invalidate the View from a non-UI thread.</p>
12768     *
12769     * <p>This method can be invoked from outside of the UI thread
12770     * only when this View is attached to a window.</p>
12771     *
12772     * @see #invalidate()
12773     * @see #postInvalidateDelayed(long)
12774     */
12775    public void postInvalidate() {
12776        postInvalidateDelayed(0);
12777    }
12778
12779    /**
12780     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12781     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12782     *
12783     * <p>This method can be invoked from outside of the UI thread
12784     * only when this View is attached to a window.</p>
12785     *
12786     * @param left The left coordinate of the rectangle to invalidate.
12787     * @param top The top coordinate of the rectangle to invalidate.
12788     * @param right The right coordinate of the rectangle to invalidate.
12789     * @param bottom The bottom coordinate of the rectangle to invalidate.
12790     *
12791     * @see #invalidate(int, int, int, int)
12792     * @see #invalidate(Rect)
12793     * @see #postInvalidateDelayed(long, int, int, int, int)
12794     */
12795    public void postInvalidate(int left, int top, int right, int bottom) {
12796        postInvalidateDelayed(0, left, top, right, bottom);
12797    }
12798
12799    /**
12800     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12801     * loop. Waits for the specified amount of time.</p>
12802     *
12803     * <p>This method can be invoked from outside of the UI thread
12804     * only when this View is attached to a window.</p>
12805     *
12806     * @param delayMilliseconds the duration in milliseconds to delay the
12807     *         invalidation by
12808     *
12809     * @see #invalidate()
12810     * @see #postInvalidate()
12811     */
12812    public void postInvalidateDelayed(long delayMilliseconds) {
12813        // We try only with the AttachInfo because there's no point in invalidating
12814        // if we are not attached to our window
12815        final AttachInfo attachInfo = mAttachInfo;
12816        if (attachInfo != null) {
12817            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12818        }
12819    }
12820
12821    /**
12822     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12823     * through the event loop. Waits for the specified amount of time.</p>
12824     *
12825     * <p>This method can be invoked from outside of the UI thread
12826     * only when this View is attached to a window.</p>
12827     *
12828     * @param delayMilliseconds the duration in milliseconds to delay the
12829     *         invalidation by
12830     * @param left The left coordinate of the rectangle to invalidate.
12831     * @param top The top coordinate of the rectangle to invalidate.
12832     * @param right The right coordinate of the rectangle to invalidate.
12833     * @param bottom The bottom coordinate of the rectangle to invalidate.
12834     *
12835     * @see #invalidate(int, int, int, int)
12836     * @see #invalidate(Rect)
12837     * @see #postInvalidate(int, int, int, int)
12838     */
12839    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12840            int right, int bottom) {
12841
12842        // We try only with the AttachInfo because there's no point in invalidating
12843        // if we are not attached to our window
12844        final AttachInfo attachInfo = mAttachInfo;
12845        if (attachInfo != null) {
12846            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12847            info.target = this;
12848            info.left = left;
12849            info.top = top;
12850            info.right = right;
12851            info.bottom = bottom;
12852
12853            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12854        }
12855    }
12856
12857    /**
12858     * <p>Cause an invalidate to happen on the next animation time step, typically the
12859     * next display frame.</p>
12860     *
12861     * <p>This method can be invoked from outside of the UI thread
12862     * only when this View is attached to a window.</p>
12863     *
12864     * @see #invalidate()
12865     */
12866    public void postInvalidateOnAnimation() {
12867        // We try only with the AttachInfo because there's no point in invalidating
12868        // if we are not attached to our window
12869        final AttachInfo attachInfo = mAttachInfo;
12870        if (attachInfo != null) {
12871            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12872        }
12873    }
12874
12875    /**
12876     * <p>Cause an invalidate of the specified area to happen on the next animation
12877     * time step, typically the next display frame.</p>
12878     *
12879     * <p>This method can be invoked from outside of the UI thread
12880     * only when this View is attached to a window.</p>
12881     *
12882     * @param left The left coordinate of the rectangle to invalidate.
12883     * @param top The top coordinate of the rectangle to invalidate.
12884     * @param right The right coordinate of the rectangle to invalidate.
12885     * @param bottom The bottom coordinate of the rectangle to invalidate.
12886     *
12887     * @see #invalidate(int, int, int, int)
12888     * @see #invalidate(Rect)
12889     */
12890    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12891        // We try only with the AttachInfo because there's no point in invalidating
12892        // if we are not attached to our window
12893        final AttachInfo attachInfo = mAttachInfo;
12894        if (attachInfo != null) {
12895            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12896            info.target = this;
12897            info.left = left;
12898            info.top = top;
12899            info.right = right;
12900            info.bottom = bottom;
12901
12902            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12903        }
12904    }
12905
12906    /**
12907     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12908     * This event is sent at most once every
12909     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12910     */
12911    private void postSendViewScrolledAccessibilityEventCallback() {
12912        if (mSendViewScrolledAccessibilityEvent == null) {
12913            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12914        }
12915        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12916            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12917            postDelayed(mSendViewScrolledAccessibilityEvent,
12918                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12919        }
12920    }
12921
12922    /**
12923     * Called by a parent to request that a child update its values for mScrollX
12924     * and mScrollY if necessary. This will typically be done if the child is
12925     * animating a scroll using a {@link android.widget.Scroller Scroller}
12926     * object.
12927     */
12928    public void computeScroll() {
12929    }
12930
12931    /**
12932     * <p>Indicate whether the horizontal edges are faded when the view is
12933     * scrolled horizontally.</p>
12934     *
12935     * @return true if the horizontal edges should are faded on scroll, false
12936     *         otherwise
12937     *
12938     * @see #setHorizontalFadingEdgeEnabled(boolean)
12939     *
12940     * @attr ref android.R.styleable#View_requiresFadingEdge
12941     */
12942    public boolean isHorizontalFadingEdgeEnabled() {
12943        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12944    }
12945
12946    /**
12947     * <p>Define whether the horizontal edges should be faded when this view
12948     * is scrolled horizontally.</p>
12949     *
12950     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12951     *                                    be faded when the view is scrolled
12952     *                                    horizontally
12953     *
12954     * @see #isHorizontalFadingEdgeEnabled()
12955     *
12956     * @attr ref android.R.styleable#View_requiresFadingEdge
12957     */
12958    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12959        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12960            if (horizontalFadingEdgeEnabled) {
12961                initScrollCache();
12962            }
12963
12964            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12965        }
12966    }
12967
12968    /**
12969     * <p>Indicate whether the vertical edges are faded when the view is
12970     * scrolled horizontally.</p>
12971     *
12972     * @return true if the vertical edges should are faded on scroll, false
12973     *         otherwise
12974     *
12975     * @see #setVerticalFadingEdgeEnabled(boolean)
12976     *
12977     * @attr ref android.R.styleable#View_requiresFadingEdge
12978     */
12979    public boolean isVerticalFadingEdgeEnabled() {
12980        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12981    }
12982
12983    /**
12984     * <p>Define whether the vertical edges should be faded when this view
12985     * is scrolled vertically.</p>
12986     *
12987     * @param verticalFadingEdgeEnabled true if the vertical edges should
12988     *                                  be faded when the view is scrolled
12989     *                                  vertically
12990     *
12991     * @see #isVerticalFadingEdgeEnabled()
12992     *
12993     * @attr ref android.R.styleable#View_requiresFadingEdge
12994     */
12995    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12996        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12997            if (verticalFadingEdgeEnabled) {
12998                initScrollCache();
12999            }
13000
13001            mViewFlags ^= FADING_EDGE_VERTICAL;
13002        }
13003    }
13004
13005    /**
13006     * Returns the strength, or intensity, of the top faded edge. The strength is
13007     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13008     * returns 0.0 or 1.0 but no value in between.
13009     *
13010     * Subclasses should override this method to provide a smoother fade transition
13011     * when scrolling occurs.
13012     *
13013     * @return the intensity of the top fade as a float between 0.0f and 1.0f
13014     */
13015    protected float getTopFadingEdgeStrength() {
13016        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
13017    }
13018
13019    /**
13020     * Returns the strength, or intensity, of the bottom faded edge. The strength is
13021     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13022     * returns 0.0 or 1.0 but no value in between.
13023     *
13024     * Subclasses should override this method to provide a smoother fade transition
13025     * when scrolling occurs.
13026     *
13027     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
13028     */
13029    protected float getBottomFadingEdgeStrength() {
13030        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
13031                computeVerticalScrollRange() ? 1.0f : 0.0f;
13032    }
13033
13034    /**
13035     * Returns the strength, or intensity, of the left faded edge. The strength is
13036     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13037     * returns 0.0 or 1.0 but no value in between.
13038     *
13039     * Subclasses should override this method to provide a smoother fade transition
13040     * when scrolling occurs.
13041     *
13042     * @return the intensity of the left fade as a float between 0.0f and 1.0f
13043     */
13044    protected float getLeftFadingEdgeStrength() {
13045        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
13046    }
13047
13048    /**
13049     * Returns the strength, or intensity, of the right faded edge. The strength is
13050     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13051     * returns 0.0 or 1.0 but no value in between.
13052     *
13053     * Subclasses should override this method to provide a smoother fade transition
13054     * when scrolling occurs.
13055     *
13056     * @return the intensity of the right fade as a float between 0.0f and 1.0f
13057     */
13058    protected float getRightFadingEdgeStrength() {
13059        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
13060                computeHorizontalScrollRange() ? 1.0f : 0.0f;
13061    }
13062
13063    /**
13064     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
13065     * scrollbar is not drawn by default.</p>
13066     *
13067     * @return true if the horizontal scrollbar should be painted, false
13068     *         otherwise
13069     *
13070     * @see #setHorizontalScrollBarEnabled(boolean)
13071     */
13072    public boolean isHorizontalScrollBarEnabled() {
13073        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13074    }
13075
13076    /**
13077     * <p>Define whether the horizontal scrollbar should be drawn or not. The
13078     * scrollbar is not drawn by default.</p>
13079     *
13080     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
13081     *                                   be painted
13082     *
13083     * @see #isHorizontalScrollBarEnabled()
13084     */
13085    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
13086        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
13087            mViewFlags ^= SCROLLBARS_HORIZONTAL;
13088            computeOpaqueFlags();
13089            resolvePadding();
13090        }
13091    }
13092
13093    /**
13094     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
13095     * scrollbar is not drawn by default.</p>
13096     *
13097     * @return true if the vertical scrollbar should be painted, false
13098     *         otherwise
13099     *
13100     * @see #setVerticalScrollBarEnabled(boolean)
13101     */
13102    public boolean isVerticalScrollBarEnabled() {
13103        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
13104    }
13105
13106    /**
13107     * <p>Define whether the vertical scrollbar should be drawn or not. The
13108     * scrollbar is not drawn by default.</p>
13109     *
13110     * @param verticalScrollBarEnabled true if the vertical scrollbar should
13111     *                                 be painted
13112     *
13113     * @see #isVerticalScrollBarEnabled()
13114     */
13115    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
13116        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
13117            mViewFlags ^= SCROLLBARS_VERTICAL;
13118            computeOpaqueFlags();
13119            resolvePadding();
13120        }
13121    }
13122
13123    /**
13124     * @hide
13125     */
13126    protected void recomputePadding() {
13127        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13128    }
13129
13130    /**
13131     * Define whether scrollbars will fade when the view is not scrolling.
13132     *
13133     * @param fadeScrollbars whether to enable fading
13134     *
13135     * @attr ref android.R.styleable#View_fadeScrollbars
13136     */
13137    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
13138        initScrollCache();
13139        final ScrollabilityCache scrollabilityCache = mScrollCache;
13140        scrollabilityCache.fadeScrollBars = fadeScrollbars;
13141        if (fadeScrollbars) {
13142            scrollabilityCache.state = ScrollabilityCache.OFF;
13143        } else {
13144            scrollabilityCache.state = ScrollabilityCache.ON;
13145        }
13146    }
13147
13148    /**
13149     *
13150     * Returns true if scrollbars will fade when this view is not scrolling
13151     *
13152     * @return true if scrollbar fading is enabled
13153     *
13154     * @attr ref android.R.styleable#View_fadeScrollbars
13155     */
13156    public boolean isScrollbarFadingEnabled() {
13157        return mScrollCache != null && mScrollCache.fadeScrollBars;
13158    }
13159
13160    /**
13161     *
13162     * Returns the delay before scrollbars fade.
13163     *
13164     * @return the delay before scrollbars fade
13165     *
13166     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13167     */
13168    public int getScrollBarDefaultDelayBeforeFade() {
13169        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
13170                mScrollCache.scrollBarDefaultDelayBeforeFade;
13171    }
13172
13173    /**
13174     * Define the delay before scrollbars fade.
13175     *
13176     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
13177     *
13178     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13179     */
13180    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
13181        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
13182    }
13183
13184    /**
13185     *
13186     * Returns the scrollbar fade duration.
13187     *
13188     * @return the scrollbar fade duration
13189     *
13190     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13191     */
13192    public int getScrollBarFadeDuration() {
13193        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
13194                mScrollCache.scrollBarFadeDuration;
13195    }
13196
13197    /**
13198     * Define the scrollbar fade duration.
13199     *
13200     * @param scrollBarFadeDuration - the scrollbar fade duration
13201     *
13202     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13203     */
13204    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
13205        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
13206    }
13207
13208    /**
13209     *
13210     * Returns the scrollbar size.
13211     *
13212     * @return the scrollbar size
13213     *
13214     * @attr ref android.R.styleable#View_scrollbarSize
13215     */
13216    public int getScrollBarSize() {
13217        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
13218                mScrollCache.scrollBarSize;
13219    }
13220
13221    /**
13222     * Define the scrollbar size.
13223     *
13224     * @param scrollBarSize - the scrollbar size
13225     *
13226     * @attr ref android.R.styleable#View_scrollbarSize
13227     */
13228    public void setScrollBarSize(int scrollBarSize) {
13229        getScrollCache().scrollBarSize = scrollBarSize;
13230    }
13231
13232    /**
13233     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
13234     * inset. When inset, they add to the padding of the view. And the scrollbars
13235     * can be drawn inside the padding area or on the edge of the view. For example,
13236     * if a view has a background drawable and you want to draw the scrollbars
13237     * inside the padding specified by the drawable, you can use
13238     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
13239     * appear at the edge of the view, ignoring the padding, then you can use
13240     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
13241     * @param style the style of the scrollbars. Should be one of
13242     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
13243     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
13244     * @see #SCROLLBARS_INSIDE_OVERLAY
13245     * @see #SCROLLBARS_INSIDE_INSET
13246     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13247     * @see #SCROLLBARS_OUTSIDE_INSET
13248     *
13249     * @attr ref android.R.styleable#View_scrollbarStyle
13250     */
13251    public void setScrollBarStyle(@ScrollBarStyle int style) {
13252        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
13253            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
13254            computeOpaqueFlags();
13255            resolvePadding();
13256        }
13257    }
13258
13259    /**
13260     * <p>Returns the current scrollbar style.</p>
13261     * @return the current scrollbar style
13262     * @see #SCROLLBARS_INSIDE_OVERLAY
13263     * @see #SCROLLBARS_INSIDE_INSET
13264     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13265     * @see #SCROLLBARS_OUTSIDE_INSET
13266     *
13267     * @attr ref android.R.styleable#View_scrollbarStyle
13268     */
13269    @ViewDebug.ExportedProperty(mapping = {
13270            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
13271            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
13272            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
13273            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
13274    })
13275    @ScrollBarStyle
13276    public int getScrollBarStyle() {
13277        return mViewFlags & SCROLLBARS_STYLE_MASK;
13278    }
13279
13280    /**
13281     * <p>Compute the horizontal range that the horizontal scrollbar
13282     * represents.</p>
13283     *
13284     * <p>The range is expressed in arbitrary units that must be the same as the
13285     * units used by {@link #computeHorizontalScrollExtent()} and
13286     * {@link #computeHorizontalScrollOffset()}.</p>
13287     *
13288     * <p>The default range is the drawing width of this view.</p>
13289     *
13290     * @return the total horizontal range represented by the horizontal
13291     *         scrollbar
13292     *
13293     * @see #computeHorizontalScrollExtent()
13294     * @see #computeHorizontalScrollOffset()
13295     * @see android.widget.ScrollBarDrawable
13296     */
13297    protected int computeHorizontalScrollRange() {
13298        return getWidth();
13299    }
13300
13301    /**
13302     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
13303     * within the horizontal range. This value is used to compute the position
13304     * of the thumb within the scrollbar's track.</p>
13305     *
13306     * <p>The range is expressed in arbitrary units that must be the same as the
13307     * units used by {@link #computeHorizontalScrollRange()} and
13308     * {@link #computeHorizontalScrollExtent()}.</p>
13309     *
13310     * <p>The default offset is the scroll offset of this view.</p>
13311     *
13312     * @return the horizontal offset of the scrollbar's thumb
13313     *
13314     * @see #computeHorizontalScrollRange()
13315     * @see #computeHorizontalScrollExtent()
13316     * @see android.widget.ScrollBarDrawable
13317     */
13318    protected int computeHorizontalScrollOffset() {
13319        return mScrollX;
13320    }
13321
13322    /**
13323     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
13324     * within the horizontal range. This value is used to compute the length
13325     * of the thumb within the scrollbar's track.</p>
13326     *
13327     * <p>The range is expressed in arbitrary units that must be the same as the
13328     * units used by {@link #computeHorizontalScrollRange()} and
13329     * {@link #computeHorizontalScrollOffset()}.</p>
13330     *
13331     * <p>The default extent is the drawing width of this view.</p>
13332     *
13333     * @return the horizontal extent of the scrollbar's thumb
13334     *
13335     * @see #computeHorizontalScrollRange()
13336     * @see #computeHorizontalScrollOffset()
13337     * @see android.widget.ScrollBarDrawable
13338     */
13339    protected int computeHorizontalScrollExtent() {
13340        return getWidth();
13341    }
13342
13343    /**
13344     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
13345     *
13346     * <p>The range is expressed in arbitrary units that must be the same as the
13347     * units used by {@link #computeVerticalScrollExtent()} and
13348     * {@link #computeVerticalScrollOffset()}.</p>
13349     *
13350     * @return the total vertical range represented by the vertical scrollbar
13351     *
13352     * <p>The default range is the drawing height of this view.</p>
13353     *
13354     * @see #computeVerticalScrollExtent()
13355     * @see #computeVerticalScrollOffset()
13356     * @see android.widget.ScrollBarDrawable
13357     */
13358    protected int computeVerticalScrollRange() {
13359        return getHeight();
13360    }
13361
13362    /**
13363     * <p>Compute the vertical offset of the vertical scrollbar's thumb
13364     * within the horizontal range. This value is used to compute the position
13365     * of the thumb within the scrollbar's track.</p>
13366     *
13367     * <p>The range is expressed in arbitrary units that must be the same as the
13368     * units used by {@link #computeVerticalScrollRange()} and
13369     * {@link #computeVerticalScrollExtent()}.</p>
13370     *
13371     * <p>The default offset is the scroll offset of this view.</p>
13372     *
13373     * @return the vertical offset of the scrollbar's thumb
13374     *
13375     * @see #computeVerticalScrollRange()
13376     * @see #computeVerticalScrollExtent()
13377     * @see android.widget.ScrollBarDrawable
13378     */
13379    protected int computeVerticalScrollOffset() {
13380        return mScrollY;
13381    }
13382
13383    /**
13384     * <p>Compute the vertical extent of the vertical scrollbar's thumb
13385     * within the vertical range. This value is used to compute the length
13386     * of the thumb within the scrollbar's track.</p>
13387     *
13388     * <p>The range is expressed in arbitrary units that must be the same as the
13389     * units used by {@link #computeVerticalScrollRange()} and
13390     * {@link #computeVerticalScrollOffset()}.</p>
13391     *
13392     * <p>The default extent is the drawing height of this view.</p>
13393     *
13394     * @return the vertical extent of the scrollbar's thumb
13395     *
13396     * @see #computeVerticalScrollRange()
13397     * @see #computeVerticalScrollOffset()
13398     * @see android.widget.ScrollBarDrawable
13399     */
13400    protected int computeVerticalScrollExtent() {
13401        return getHeight();
13402    }
13403
13404    /**
13405     * Check if this view can be scrolled horizontally in a certain direction.
13406     *
13407     * @param direction Negative to check scrolling left, positive to check scrolling right.
13408     * @return true if this view can be scrolled in the specified direction, false otherwise.
13409     */
13410    public boolean canScrollHorizontally(int direction) {
13411        final int offset = computeHorizontalScrollOffset();
13412        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
13413        if (range == 0) return false;
13414        if (direction < 0) {
13415            return offset > 0;
13416        } else {
13417            return offset < range - 1;
13418        }
13419    }
13420
13421    /**
13422     * Check if this view can be scrolled vertically in a certain direction.
13423     *
13424     * @param direction Negative to check scrolling up, positive to check scrolling down.
13425     * @return true if this view can be scrolled in the specified direction, false otherwise.
13426     */
13427    public boolean canScrollVertically(int direction) {
13428        final int offset = computeVerticalScrollOffset();
13429        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
13430        if (range == 0) return false;
13431        if (direction < 0) {
13432            return offset > 0;
13433        } else {
13434            return offset < range - 1;
13435        }
13436    }
13437
13438    /**
13439     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
13440     * scrollbars are painted only if they have been awakened first.</p>
13441     *
13442     * @param canvas the canvas on which to draw the scrollbars
13443     *
13444     * @see #awakenScrollBars(int)
13445     */
13446    protected final void onDrawScrollBars(Canvas canvas) {
13447        // scrollbars are drawn only when the animation is running
13448        final ScrollabilityCache cache = mScrollCache;
13449        if (cache != null) {
13450
13451            int state = cache.state;
13452
13453            if (state == ScrollabilityCache.OFF) {
13454                return;
13455            }
13456
13457            boolean invalidate = false;
13458
13459            if (state == ScrollabilityCache.FADING) {
13460                // We're fading -- get our fade interpolation
13461                if (cache.interpolatorValues == null) {
13462                    cache.interpolatorValues = new float[1];
13463                }
13464
13465                float[] values = cache.interpolatorValues;
13466
13467                // Stops the animation if we're done
13468                if (cache.scrollBarInterpolator.timeToValues(values) ==
13469                        Interpolator.Result.FREEZE_END) {
13470                    cache.state = ScrollabilityCache.OFF;
13471                } else {
13472                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
13473                }
13474
13475                // This will make the scroll bars inval themselves after
13476                // drawing. We only want this when we're fading so that
13477                // we prevent excessive redraws
13478                invalidate = true;
13479            } else {
13480                // We're just on -- but we may have been fading before so
13481                // reset alpha
13482                cache.scrollBar.mutate().setAlpha(255);
13483            }
13484
13485
13486            final int viewFlags = mViewFlags;
13487
13488            final boolean drawHorizontalScrollBar =
13489                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13490            final boolean drawVerticalScrollBar =
13491                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
13492                && !isVerticalScrollBarHidden();
13493
13494            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
13495                final int width = mRight - mLeft;
13496                final int height = mBottom - mTop;
13497
13498                final ScrollBarDrawable scrollBar = cache.scrollBar;
13499
13500                final int scrollX = mScrollX;
13501                final int scrollY = mScrollY;
13502                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
13503
13504                int left;
13505                int top;
13506                int right;
13507                int bottom;
13508
13509                if (drawHorizontalScrollBar) {
13510                    int size = scrollBar.getSize(false);
13511                    if (size <= 0) {
13512                        size = cache.scrollBarSize;
13513                    }
13514
13515                    scrollBar.setParameters(computeHorizontalScrollRange(),
13516                                            computeHorizontalScrollOffset(),
13517                                            computeHorizontalScrollExtent(), false);
13518                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13519                            getVerticalScrollbarWidth() : 0;
13520                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13521                    left = scrollX + (mPaddingLeft & inside);
13522                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13523                    bottom = top + size;
13524                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13525                    if (invalidate) {
13526                        invalidate(left, top, right, bottom);
13527                    }
13528                }
13529
13530                if (drawVerticalScrollBar) {
13531                    int size = scrollBar.getSize(true);
13532                    if (size <= 0) {
13533                        size = cache.scrollBarSize;
13534                    }
13535
13536                    scrollBar.setParameters(computeVerticalScrollRange(),
13537                                            computeVerticalScrollOffset(),
13538                                            computeVerticalScrollExtent(), true);
13539                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13540                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13541                        verticalScrollbarPosition = isLayoutRtl() ?
13542                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13543                    }
13544                    switch (verticalScrollbarPosition) {
13545                        default:
13546                        case SCROLLBAR_POSITION_RIGHT:
13547                            left = scrollX + width - size - (mUserPaddingRight & inside);
13548                            break;
13549                        case SCROLLBAR_POSITION_LEFT:
13550                            left = scrollX + (mUserPaddingLeft & inside);
13551                            break;
13552                    }
13553                    top = scrollY + (mPaddingTop & inside);
13554                    right = left + size;
13555                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13556                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13557                    if (invalidate) {
13558                        invalidate(left, top, right, bottom);
13559                    }
13560                }
13561            }
13562        }
13563    }
13564
13565    /**
13566     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13567     * FastScroller is visible.
13568     * @return whether to temporarily hide the vertical scrollbar
13569     * @hide
13570     */
13571    protected boolean isVerticalScrollBarHidden() {
13572        return false;
13573    }
13574
13575    /**
13576     * <p>Draw the horizontal scrollbar if
13577     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13578     *
13579     * @param canvas the canvas on which to draw the scrollbar
13580     * @param scrollBar the scrollbar's drawable
13581     *
13582     * @see #isHorizontalScrollBarEnabled()
13583     * @see #computeHorizontalScrollRange()
13584     * @see #computeHorizontalScrollExtent()
13585     * @see #computeHorizontalScrollOffset()
13586     * @see android.widget.ScrollBarDrawable
13587     * @hide
13588     */
13589    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13590            int l, int t, int r, int b) {
13591        scrollBar.setBounds(l, t, r, b);
13592        scrollBar.draw(canvas);
13593    }
13594
13595    /**
13596     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13597     * returns true.</p>
13598     *
13599     * @param canvas the canvas on which to draw the scrollbar
13600     * @param scrollBar the scrollbar's drawable
13601     *
13602     * @see #isVerticalScrollBarEnabled()
13603     * @see #computeVerticalScrollRange()
13604     * @see #computeVerticalScrollExtent()
13605     * @see #computeVerticalScrollOffset()
13606     * @see android.widget.ScrollBarDrawable
13607     * @hide
13608     */
13609    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13610            int l, int t, int r, int b) {
13611        scrollBar.setBounds(l, t, r, b);
13612        scrollBar.draw(canvas);
13613    }
13614
13615    /**
13616     * Implement this to do your drawing.
13617     *
13618     * @param canvas the canvas on which the background will be drawn
13619     */
13620    protected void onDraw(Canvas canvas) {
13621    }
13622
13623    /*
13624     * Caller is responsible for calling requestLayout if necessary.
13625     * (This allows addViewInLayout to not request a new layout.)
13626     */
13627    void assignParent(ViewParent parent) {
13628        if (mParent == null) {
13629            mParent = parent;
13630        } else if (parent == null) {
13631            mParent = null;
13632        } else {
13633            throw new RuntimeException("view " + this + " being added, but"
13634                    + " it already has a parent");
13635        }
13636    }
13637
13638    /**
13639     * This is called when the view is attached to a window.  At this point it
13640     * has a Surface and will start drawing.  Note that this function is
13641     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13642     * however it may be called any time before the first onDraw -- including
13643     * before or after {@link #onMeasure(int, int)}.
13644     *
13645     * @see #onDetachedFromWindow()
13646     */
13647    @CallSuper
13648    protected void onAttachedToWindow() {
13649        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13650            mParent.requestTransparentRegion(this);
13651        }
13652
13653        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13654            initialAwakenScrollBars();
13655            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13656        }
13657
13658        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13659
13660        jumpDrawablesToCurrentState();
13661
13662        resetSubtreeAccessibilityStateChanged();
13663
13664        // rebuild, since Outline not maintained while View is detached
13665        rebuildOutline();
13666
13667        if (isFocused()) {
13668            InputMethodManager imm = InputMethodManager.peekInstance();
13669            if (imm != null) {
13670                imm.focusIn(this);
13671            }
13672        }
13673    }
13674
13675    /**
13676     * Resolve all RTL related properties.
13677     *
13678     * @return true if resolution of RTL properties has been done
13679     *
13680     * @hide
13681     */
13682    public boolean resolveRtlPropertiesIfNeeded() {
13683        if (!needRtlPropertiesResolution()) return false;
13684
13685        // Order is important here: LayoutDirection MUST be resolved first
13686        if (!isLayoutDirectionResolved()) {
13687            resolveLayoutDirection();
13688            resolveLayoutParams();
13689        }
13690        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13691        if (!isTextDirectionResolved()) {
13692            resolveTextDirection();
13693        }
13694        if (!isTextAlignmentResolved()) {
13695            resolveTextAlignment();
13696        }
13697        // Should resolve Drawables before Padding because we need the layout direction of the
13698        // Drawable to correctly resolve Padding.
13699        if (!areDrawablesResolved()) {
13700            resolveDrawables();
13701        }
13702        if (!isPaddingResolved()) {
13703            resolvePadding();
13704        }
13705        onRtlPropertiesChanged(getLayoutDirection());
13706        return true;
13707    }
13708
13709    /**
13710     * Reset resolution of all RTL related properties.
13711     *
13712     * @hide
13713     */
13714    public void resetRtlProperties() {
13715        resetResolvedLayoutDirection();
13716        resetResolvedTextDirection();
13717        resetResolvedTextAlignment();
13718        resetResolvedPadding();
13719        resetResolvedDrawables();
13720    }
13721
13722    /**
13723     * @see #onScreenStateChanged(int)
13724     */
13725    void dispatchScreenStateChanged(int screenState) {
13726        onScreenStateChanged(screenState);
13727    }
13728
13729    /**
13730     * This method is called whenever the state of the screen this view is
13731     * attached to changes. A state change will usually occurs when the screen
13732     * turns on or off (whether it happens automatically or the user does it
13733     * manually.)
13734     *
13735     * @param screenState The new state of the screen. Can be either
13736     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13737     */
13738    public void onScreenStateChanged(int screenState) {
13739    }
13740
13741    /**
13742     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13743     */
13744    private boolean hasRtlSupport() {
13745        return mContext.getApplicationInfo().hasRtlSupport();
13746    }
13747
13748    /**
13749     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13750     * RTL not supported)
13751     */
13752    private boolean isRtlCompatibilityMode() {
13753        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13754        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13755    }
13756
13757    /**
13758     * @return true if RTL properties need resolution.
13759     *
13760     */
13761    private boolean needRtlPropertiesResolution() {
13762        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13763    }
13764
13765    /**
13766     * Called when any RTL property (layout direction or text direction or text alignment) has
13767     * been changed.
13768     *
13769     * Subclasses need to override this method to take care of cached information that depends on the
13770     * resolved layout direction, or to inform child views that inherit their layout direction.
13771     *
13772     * The default implementation does nothing.
13773     *
13774     * @param layoutDirection the direction of the layout
13775     *
13776     * @see #LAYOUT_DIRECTION_LTR
13777     * @see #LAYOUT_DIRECTION_RTL
13778     */
13779    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13780    }
13781
13782    /**
13783     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13784     * that the parent directionality can and will be resolved before its children.
13785     *
13786     * @return true if resolution has been done, false otherwise.
13787     *
13788     * @hide
13789     */
13790    public boolean resolveLayoutDirection() {
13791        // Clear any previous layout direction resolution
13792        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13793
13794        if (hasRtlSupport()) {
13795            // Set resolved depending on layout direction
13796            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13797                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13798                case LAYOUT_DIRECTION_INHERIT:
13799                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13800                    // later to get the correct resolved value
13801                    if (!canResolveLayoutDirection()) return false;
13802
13803                    // Parent has not yet resolved, LTR is still the default
13804                    try {
13805                        if (!mParent.isLayoutDirectionResolved()) return false;
13806
13807                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13808                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13809                        }
13810                    } catch (AbstractMethodError e) {
13811                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13812                                " does not fully implement ViewParent", e);
13813                    }
13814                    break;
13815                case LAYOUT_DIRECTION_RTL:
13816                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13817                    break;
13818                case LAYOUT_DIRECTION_LOCALE:
13819                    if((LAYOUT_DIRECTION_RTL ==
13820                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13821                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13822                    }
13823                    break;
13824                default:
13825                    // Nothing to do, LTR by default
13826            }
13827        }
13828
13829        // Set to resolved
13830        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13831        return true;
13832    }
13833
13834    /**
13835     * Check if layout direction resolution can be done.
13836     *
13837     * @return true if layout direction resolution can be done otherwise return false.
13838     */
13839    public boolean canResolveLayoutDirection() {
13840        switch (getRawLayoutDirection()) {
13841            case LAYOUT_DIRECTION_INHERIT:
13842                if (mParent != null) {
13843                    try {
13844                        return mParent.canResolveLayoutDirection();
13845                    } catch (AbstractMethodError e) {
13846                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13847                                " does not fully implement ViewParent", e);
13848                    }
13849                }
13850                return false;
13851
13852            default:
13853                return true;
13854        }
13855    }
13856
13857    /**
13858     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13859     * {@link #onMeasure(int, int)}.
13860     *
13861     * @hide
13862     */
13863    public void resetResolvedLayoutDirection() {
13864        // Reset the current resolved bits
13865        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13866    }
13867
13868    /**
13869     * @return true if the layout direction is inherited.
13870     *
13871     * @hide
13872     */
13873    public boolean isLayoutDirectionInherited() {
13874        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13875    }
13876
13877    /**
13878     * @return true if layout direction has been resolved.
13879     */
13880    public boolean isLayoutDirectionResolved() {
13881        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13882    }
13883
13884    /**
13885     * Return if padding has been resolved
13886     *
13887     * @hide
13888     */
13889    boolean isPaddingResolved() {
13890        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13891    }
13892
13893    /**
13894     * Resolves padding depending on layout direction, if applicable, and
13895     * recomputes internal padding values to adjust for scroll bars.
13896     *
13897     * @hide
13898     */
13899    public void resolvePadding() {
13900        final int resolvedLayoutDirection = getLayoutDirection();
13901
13902        if (!isRtlCompatibilityMode()) {
13903            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13904            // If start / end padding are defined, they will be resolved (hence overriding) to
13905            // left / right or right / left depending on the resolved layout direction.
13906            // If start / end padding are not defined, use the left / right ones.
13907            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13908                Rect padding = sThreadLocal.get();
13909                if (padding == null) {
13910                    padding = new Rect();
13911                    sThreadLocal.set(padding);
13912                }
13913                mBackground.getPadding(padding);
13914                if (!mLeftPaddingDefined) {
13915                    mUserPaddingLeftInitial = padding.left;
13916                }
13917                if (!mRightPaddingDefined) {
13918                    mUserPaddingRightInitial = padding.right;
13919                }
13920            }
13921            switch (resolvedLayoutDirection) {
13922                case LAYOUT_DIRECTION_RTL:
13923                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13924                        mUserPaddingRight = mUserPaddingStart;
13925                    } else {
13926                        mUserPaddingRight = mUserPaddingRightInitial;
13927                    }
13928                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13929                        mUserPaddingLeft = mUserPaddingEnd;
13930                    } else {
13931                        mUserPaddingLeft = mUserPaddingLeftInitial;
13932                    }
13933                    break;
13934                case LAYOUT_DIRECTION_LTR:
13935                default:
13936                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13937                        mUserPaddingLeft = mUserPaddingStart;
13938                    } else {
13939                        mUserPaddingLeft = mUserPaddingLeftInitial;
13940                    }
13941                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13942                        mUserPaddingRight = mUserPaddingEnd;
13943                    } else {
13944                        mUserPaddingRight = mUserPaddingRightInitial;
13945                    }
13946            }
13947
13948            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13949        }
13950
13951        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13952        onRtlPropertiesChanged(resolvedLayoutDirection);
13953
13954        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13955    }
13956
13957    /**
13958     * Reset the resolved layout direction.
13959     *
13960     * @hide
13961     */
13962    public void resetResolvedPadding() {
13963        resetResolvedPaddingInternal();
13964    }
13965
13966    /**
13967     * Used when we only want to reset *this* view's padding and not trigger overrides
13968     * in ViewGroup that reset children too.
13969     */
13970    void resetResolvedPaddingInternal() {
13971        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13972    }
13973
13974    /**
13975     * This is called when the view is detached from a window.  At this point it
13976     * no longer has a surface for drawing.
13977     *
13978     * @see #onAttachedToWindow()
13979     */
13980    @CallSuper
13981    protected void onDetachedFromWindow() {
13982    }
13983
13984    /**
13985     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13986     * after onDetachedFromWindow().
13987     *
13988     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13989     * The super method should be called at the end of the overridden method to ensure
13990     * subclasses are destroyed first
13991     *
13992     * @hide
13993     */
13994    @CallSuper
13995    protected void onDetachedFromWindowInternal() {
13996        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13997        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13998
13999        removeUnsetPressCallback();
14000        removeLongPressCallback();
14001        removePerformClickCallback();
14002        removeSendViewScrolledAccessibilityEventCallback();
14003        stopNestedScroll();
14004
14005        // Anything that started animating right before detach should already
14006        // be in its final state when re-attached.
14007        jumpDrawablesToCurrentState();
14008
14009        destroyDrawingCache();
14010
14011        cleanupDraw();
14012        mCurrentAnimation = null;
14013    }
14014
14015    private void cleanupDraw() {
14016        resetDisplayList();
14017        if (mAttachInfo != null) {
14018            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
14019        }
14020    }
14021
14022    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
14023    }
14024
14025    /**
14026     * @return The number of times this view has been attached to a window
14027     */
14028    protected int getWindowAttachCount() {
14029        return mWindowAttachCount;
14030    }
14031
14032    /**
14033     * Retrieve a unique token identifying the window this view is attached to.
14034     * @return Return the window's token for use in
14035     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
14036     */
14037    public IBinder getWindowToken() {
14038        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
14039    }
14040
14041    /**
14042     * Retrieve the {@link WindowId} for the window this view is
14043     * currently attached to.
14044     */
14045    public WindowId getWindowId() {
14046        if (mAttachInfo == null) {
14047            return null;
14048        }
14049        if (mAttachInfo.mWindowId == null) {
14050            try {
14051                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
14052                        mAttachInfo.mWindowToken);
14053                mAttachInfo.mWindowId = new WindowId(
14054                        mAttachInfo.mIWindowId);
14055            } catch (RemoteException e) {
14056            }
14057        }
14058        return mAttachInfo.mWindowId;
14059    }
14060
14061    /**
14062     * Retrieve a unique token identifying the top-level "real" window of
14063     * the window that this view is attached to.  That is, this is like
14064     * {@link #getWindowToken}, except if the window this view in is a panel
14065     * window (attached to another containing window), then the token of
14066     * the containing window is returned instead.
14067     *
14068     * @return Returns the associated window token, either
14069     * {@link #getWindowToken()} or the containing window's token.
14070     */
14071    public IBinder getApplicationWindowToken() {
14072        AttachInfo ai = mAttachInfo;
14073        if (ai != null) {
14074            IBinder appWindowToken = ai.mPanelParentWindowToken;
14075            if (appWindowToken == null) {
14076                appWindowToken = ai.mWindowToken;
14077            }
14078            return appWindowToken;
14079        }
14080        return null;
14081    }
14082
14083    /**
14084     * Gets the logical display to which the view's window has been attached.
14085     *
14086     * @return The logical display, or null if the view is not currently attached to a window.
14087     */
14088    public Display getDisplay() {
14089        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
14090    }
14091
14092    /**
14093     * Retrieve private session object this view hierarchy is using to
14094     * communicate with the window manager.
14095     * @return the session object to communicate with the window manager
14096     */
14097    /*package*/ IWindowSession getWindowSession() {
14098        return mAttachInfo != null ? mAttachInfo.mSession : null;
14099    }
14100
14101    /**
14102     * @param info the {@link android.view.View.AttachInfo} to associated with
14103     *        this view
14104     */
14105    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
14106        //System.out.println("Attached! " + this);
14107        mAttachInfo = info;
14108        if (mOverlay != null) {
14109            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
14110        }
14111        mWindowAttachCount++;
14112        // We will need to evaluate the drawable state at least once.
14113        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14114        if (mFloatingTreeObserver != null) {
14115            info.mTreeObserver.merge(mFloatingTreeObserver);
14116            mFloatingTreeObserver = null;
14117        }
14118        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
14119            mAttachInfo.mScrollContainers.add(this);
14120            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
14121        }
14122        performCollectViewAttributes(mAttachInfo, visibility);
14123        onAttachedToWindow();
14124
14125        ListenerInfo li = mListenerInfo;
14126        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14127                li != null ? li.mOnAttachStateChangeListeners : null;
14128        if (listeners != null && listeners.size() > 0) {
14129            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14130            // perform the dispatching. The iterator is a safe guard against listeners that
14131            // could mutate the list by calling the various add/remove methods. This prevents
14132            // the array from being modified while we iterate it.
14133            for (OnAttachStateChangeListener listener : listeners) {
14134                listener.onViewAttachedToWindow(this);
14135            }
14136        }
14137
14138        int vis = info.mWindowVisibility;
14139        if (vis != GONE) {
14140            onWindowVisibilityChanged(vis);
14141        }
14142        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
14143            // If nobody has evaluated the drawable state yet, then do it now.
14144            refreshDrawableState();
14145        }
14146        needGlobalAttributesUpdate(false);
14147    }
14148
14149    void dispatchDetachedFromWindow() {
14150        AttachInfo info = mAttachInfo;
14151        if (info != null) {
14152            int vis = info.mWindowVisibility;
14153            if (vis != GONE) {
14154                onWindowVisibilityChanged(GONE);
14155            }
14156        }
14157
14158        onDetachedFromWindow();
14159        onDetachedFromWindowInternal();
14160
14161        ListenerInfo li = mListenerInfo;
14162        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14163                li != null ? li.mOnAttachStateChangeListeners : null;
14164        if (listeners != null && listeners.size() > 0) {
14165            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14166            // perform the dispatching. The iterator is a safe guard against listeners that
14167            // could mutate the list by calling the various add/remove methods. This prevents
14168            // the array from being modified while we iterate it.
14169            for (OnAttachStateChangeListener listener : listeners) {
14170                listener.onViewDetachedFromWindow(this);
14171            }
14172        }
14173
14174        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
14175            mAttachInfo.mScrollContainers.remove(this);
14176            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
14177        }
14178
14179        mAttachInfo = null;
14180        if (mOverlay != null) {
14181            mOverlay.getOverlayView().dispatchDetachedFromWindow();
14182        }
14183    }
14184
14185    /**
14186     * Cancel any deferred high-level input events that were previously posted to the event queue.
14187     *
14188     * <p>Many views post high-level events such as click handlers to the event queue
14189     * to run deferred in order to preserve a desired user experience - clearing visible
14190     * pressed states before executing, etc. This method will abort any events of this nature
14191     * that are currently in flight.</p>
14192     *
14193     * <p>Custom views that generate their own high-level deferred input events should override
14194     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
14195     *
14196     * <p>This will also cancel pending input events for any child views.</p>
14197     *
14198     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
14199     * This will not impact newer events posted after this call that may occur as a result of
14200     * lower-level input events still waiting in the queue. If you are trying to prevent
14201     * double-submitted  events for the duration of some sort of asynchronous transaction
14202     * you should also take other steps to protect against unexpected double inputs e.g. calling
14203     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
14204     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
14205     */
14206    public final void cancelPendingInputEvents() {
14207        dispatchCancelPendingInputEvents();
14208    }
14209
14210    /**
14211     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
14212     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
14213     */
14214    void dispatchCancelPendingInputEvents() {
14215        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
14216        onCancelPendingInputEvents();
14217        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
14218            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
14219                    " did not call through to super.onCancelPendingInputEvents()");
14220        }
14221    }
14222
14223    /**
14224     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
14225     * a parent view.
14226     *
14227     * <p>This method is responsible for removing any pending high-level input events that were
14228     * posted to the event queue to run later. Custom view classes that post their own deferred
14229     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
14230     * {@link android.os.Handler} should override this method, call
14231     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
14232     * </p>
14233     */
14234    public void onCancelPendingInputEvents() {
14235        removePerformClickCallback();
14236        cancelLongPress();
14237        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
14238    }
14239
14240    /**
14241     * Store this view hierarchy's frozen state into the given container.
14242     *
14243     * @param container The SparseArray in which to save the view's state.
14244     *
14245     * @see #restoreHierarchyState(android.util.SparseArray)
14246     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14247     * @see #onSaveInstanceState()
14248     */
14249    public void saveHierarchyState(SparseArray<Parcelable> container) {
14250        dispatchSaveInstanceState(container);
14251    }
14252
14253    /**
14254     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
14255     * this view and its children. May be overridden to modify how freezing happens to a
14256     * view's children; for example, some views may want to not store state for their children.
14257     *
14258     * @param container The SparseArray in which to save the view's state.
14259     *
14260     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14261     * @see #saveHierarchyState(android.util.SparseArray)
14262     * @see #onSaveInstanceState()
14263     */
14264    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
14265        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
14266            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14267            Parcelable state = onSaveInstanceState();
14268            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14269                throw new IllegalStateException(
14270                        "Derived class did not call super.onSaveInstanceState()");
14271            }
14272            if (state != null) {
14273                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
14274                // + ": " + state);
14275                container.put(mID, state);
14276            }
14277        }
14278    }
14279
14280    /**
14281     * Hook allowing a view to generate a representation of its internal state
14282     * that can later be used to create a new instance with that same state.
14283     * This state should only contain information that is not persistent or can
14284     * not be reconstructed later. For example, you will never store your
14285     * current position on screen because that will be computed again when a
14286     * new instance of the view is placed in its view hierarchy.
14287     * <p>
14288     * Some examples of things you may store here: the current cursor position
14289     * in a text view (but usually not the text itself since that is stored in a
14290     * content provider or other persistent storage), the currently selected
14291     * item in a list view.
14292     *
14293     * @return Returns a Parcelable object containing the view's current dynamic
14294     *         state, or null if there is nothing interesting to save. The
14295     *         default implementation returns null.
14296     * @see #onRestoreInstanceState(android.os.Parcelable)
14297     * @see #saveHierarchyState(android.util.SparseArray)
14298     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14299     * @see #setSaveEnabled(boolean)
14300     */
14301    @CallSuper
14302    protected Parcelable onSaveInstanceState() {
14303        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14304        if (mStartActivityRequestWho != null) {
14305            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
14306            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
14307            return state;
14308        }
14309        return BaseSavedState.EMPTY_STATE;
14310    }
14311
14312    /**
14313     * Restore this view hierarchy's frozen state from the given container.
14314     *
14315     * @param container The SparseArray which holds previously frozen states.
14316     *
14317     * @see #saveHierarchyState(android.util.SparseArray)
14318     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14319     * @see #onRestoreInstanceState(android.os.Parcelable)
14320     */
14321    public void restoreHierarchyState(SparseArray<Parcelable> container) {
14322        dispatchRestoreInstanceState(container);
14323    }
14324
14325    /**
14326     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
14327     * state for this view and its children. May be overridden to modify how restoring
14328     * happens to a view's children; for example, some views may want to not store state
14329     * for their children.
14330     *
14331     * @param container The SparseArray which holds previously saved state.
14332     *
14333     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14334     * @see #restoreHierarchyState(android.util.SparseArray)
14335     * @see #onRestoreInstanceState(android.os.Parcelable)
14336     */
14337    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
14338        if (mID != NO_ID) {
14339            Parcelable state = container.get(mID);
14340            if (state != null) {
14341                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
14342                // + ": " + state);
14343                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14344                onRestoreInstanceState(state);
14345                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14346                    throw new IllegalStateException(
14347                            "Derived class did not call super.onRestoreInstanceState()");
14348                }
14349            }
14350        }
14351    }
14352
14353    /**
14354     * Hook allowing a view to re-apply a representation of its internal state that had previously
14355     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
14356     * null state.
14357     *
14358     * @param state The frozen state that had previously been returned by
14359     *        {@link #onSaveInstanceState}.
14360     *
14361     * @see #onSaveInstanceState()
14362     * @see #restoreHierarchyState(android.util.SparseArray)
14363     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14364     */
14365    @CallSuper
14366    protected void onRestoreInstanceState(Parcelable state) {
14367        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14368        if (state != null && !(state instanceof AbsSavedState)) {
14369            throw new IllegalArgumentException("Wrong state class, expecting View State but "
14370                    + "received " + state.getClass().toString() + " instead. This usually happens "
14371                    + "when two views of different type have the same id in the same hierarchy. "
14372                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
14373                    + "other views do not use the same id.");
14374        }
14375        if (state != null && state instanceof BaseSavedState) {
14376            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
14377        }
14378    }
14379
14380    /**
14381     * <p>Return the time at which the drawing of the view hierarchy started.</p>
14382     *
14383     * @return the drawing start time in milliseconds
14384     */
14385    public long getDrawingTime() {
14386        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
14387    }
14388
14389    /**
14390     * <p>Enables or disables the duplication of the parent's state into this view. When
14391     * duplication is enabled, this view gets its drawable state from its parent rather
14392     * than from its own internal properties.</p>
14393     *
14394     * <p>Note: in the current implementation, setting this property to true after the
14395     * view was added to a ViewGroup might have no effect at all. This property should
14396     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
14397     *
14398     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
14399     * property is enabled, an exception will be thrown.</p>
14400     *
14401     * <p>Note: if the child view uses and updates additional states which are unknown to the
14402     * parent, these states should not be affected by this method.</p>
14403     *
14404     * @param enabled True to enable duplication of the parent's drawable state, false
14405     *                to disable it.
14406     *
14407     * @see #getDrawableState()
14408     * @see #isDuplicateParentStateEnabled()
14409     */
14410    public void setDuplicateParentStateEnabled(boolean enabled) {
14411        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
14412    }
14413
14414    /**
14415     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
14416     *
14417     * @return True if this view's drawable state is duplicated from the parent,
14418     *         false otherwise
14419     *
14420     * @see #getDrawableState()
14421     * @see #setDuplicateParentStateEnabled(boolean)
14422     */
14423    public boolean isDuplicateParentStateEnabled() {
14424        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
14425    }
14426
14427    /**
14428     * <p>Specifies the type of layer backing this view. The layer can be
14429     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14430     * {@link #LAYER_TYPE_HARDWARE}.</p>
14431     *
14432     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14433     * instance that controls how the layer is composed on screen. The following
14434     * properties of the paint are taken into account when composing the layer:</p>
14435     * <ul>
14436     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14437     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14438     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14439     * </ul>
14440     *
14441     * <p>If this view has an alpha value set to < 1.0 by calling
14442     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
14443     * by this view's alpha value.</p>
14444     *
14445     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
14446     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
14447     * for more information on when and how to use layers.</p>
14448     *
14449     * @param layerType The type of layer to use with this view, must be one of
14450     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14451     *        {@link #LAYER_TYPE_HARDWARE}
14452     * @param paint The paint used to compose the layer. This argument is optional
14453     *        and can be null. It is ignored when the layer type is
14454     *        {@link #LAYER_TYPE_NONE}
14455     *
14456     * @see #getLayerType()
14457     * @see #LAYER_TYPE_NONE
14458     * @see #LAYER_TYPE_SOFTWARE
14459     * @see #LAYER_TYPE_HARDWARE
14460     * @see #setAlpha(float)
14461     *
14462     * @attr ref android.R.styleable#View_layerType
14463     */
14464    public void setLayerType(int layerType, Paint paint) {
14465        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
14466            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
14467                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
14468        }
14469
14470        boolean typeChanged = mRenderNode.setLayerType(layerType);
14471
14472        if (!typeChanged) {
14473            setLayerPaint(paint);
14474            return;
14475        }
14476
14477        // Destroy any previous software drawing cache if needed
14478        if (mLayerType == LAYER_TYPE_SOFTWARE) {
14479            destroyDrawingCache();
14480        }
14481
14482        mLayerType = layerType;
14483        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
14484        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
14485        mRenderNode.setLayerPaint(mLayerPaint);
14486
14487        // draw() behaves differently if we are on a layer, so we need to
14488        // invalidate() here
14489        invalidateParentCaches();
14490        invalidate(true);
14491    }
14492
14493    /**
14494     * Updates the {@link Paint} object used with the current layer (used only if the current
14495     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
14496     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
14497     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
14498     * ensure that the view gets redrawn immediately.
14499     *
14500     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14501     * instance that controls how the layer is composed on screen. The following
14502     * properties of the paint are taken into account when composing the layer:</p>
14503     * <ul>
14504     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14505     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14506     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14507     * </ul>
14508     *
14509     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
14510     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
14511     *
14512     * @param paint The paint used to compose the layer. This argument is optional
14513     *        and can be null. It is ignored when the layer type is
14514     *        {@link #LAYER_TYPE_NONE}
14515     *
14516     * @see #setLayerType(int, android.graphics.Paint)
14517     */
14518    public void setLayerPaint(Paint paint) {
14519        int layerType = getLayerType();
14520        if (layerType != LAYER_TYPE_NONE) {
14521            mLayerPaint = paint == null ? new Paint() : paint;
14522            if (layerType == LAYER_TYPE_HARDWARE) {
14523                if (mRenderNode.setLayerPaint(mLayerPaint)) {
14524                    invalidateViewProperty(false, false);
14525                }
14526            } else {
14527                invalidate();
14528            }
14529        }
14530    }
14531
14532    /**
14533     * Indicates what type of layer is currently associated with this view. By default
14534     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14535     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14536     * for more information on the different types of layers.
14537     *
14538     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14539     *         {@link #LAYER_TYPE_HARDWARE}
14540     *
14541     * @see #setLayerType(int, android.graphics.Paint)
14542     * @see #buildLayer()
14543     * @see #LAYER_TYPE_NONE
14544     * @see #LAYER_TYPE_SOFTWARE
14545     * @see #LAYER_TYPE_HARDWARE
14546     */
14547    public int getLayerType() {
14548        return mLayerType;
14549    }
14550
14551    /**
14552     * Forces this view's layer to be created and this view to be rendered
14553     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14554     * invoking this method will have no effect.
14555     *
14556     * This method can for instance be used to render a view into its layer before
14557     * starting an animation. If this view is complex, rendering into the layer
14558     * before starting the animation will avoid skipping frames.
14559     *
14560     * @throws IllegalStateException If this view is not attached to a window
14561     *
14562     * @see #setLayerType(int, android.graphics.Paint)
14563     */
14564    public void buildLayer() {
14565        if (mLayerType == LAYER_TYPE_NONE) return;
14566
14567        final AttachInfo attachInfo = mAttachInfo;
14568        if (attachInfo == null) {
14569            throw new IllegalStateException("This view must be attached to a window first");
14570        }
14571
14572        if (getWidth() == 0 || getHeight() == 0) {
14573            return;
14574        }
14575
14576        switch (mLayerType) {
14577            case LAYER_TYPE_HARDWARE:
14578                updateDisplayListIfDirty();
14579                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14580                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14581                }
14582                break;
14583            case LAYER_TYPE_SOFTWARE:
14584                buildDrawingCache(true);
14585                break;
14586        }
14587    }
14588
14589    /**
14590     * If this View draws with a HardwareLayer, returns it.
14591     * Otherwise returns null
14592     *
14593     * TODO: Only TextureView uses this, can we eliminate it?
14594     */
14595    HardwareLayer getHardwareLayer() {
14596        return null;
14597    }
14598
14599    /**
14600     * Destroys all hardware rendering resources. This method is invoked
14601     * when the system needs to reclaim resources. Upon execution of this
14602     * method, you should free any OpenGL resources created by the view.
14603     *
14604     * Note: you <strong>must</strong> call
14605     * <code>super.destroyHardwareResources()</code> when overriding
14606     * this method.
14607     *
14608     * @hide
14609     */
14610    @CallSuper
14611    protected void destroyHardwareResources() {
14612        // Although the Layer will be destroyed by RenderNode, we want to release
14613        // the staging display list, which is also a signal to RenderNode that it's
14614        // safe to free its copy of the display list as it knows that we will
14615        // push an updated DisplayList if we try to draw again
14616        resetDisplayList();
14617    }
14618
14619    /**
14620     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14621     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14622     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14623     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14624     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14625     * null.</p>
14626     *
14627     * <p>Enabling the drawing cache is similar to
14628     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14629     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14630     * drawing cache has no effect on rendering because the system uses a different mechanism
14631     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14632     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14633     * for information on how to enable software and hardware layers.</p>
14634     *
14635     * <p>This API can be used to manually generate
14636     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14637     * {@link #getDrawingCache()}.</p>
14638     *
14639     * @param enabled true to enable the drawing cache, false otherwise
14640     *
14641     * @see #isDrawingCacheEnabled()
14642     * @see #getDrawingCache()
14643     * @see #buildDrawingCache()
14644     * @see #setLayerType(int, android.graphics.Paint)
14645     */
14646    public void setDrawingCacheEnabled(boolean enabled) {
14647        mCachingFailed = false;
14648        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14649    }
14650
14651    /**
14652     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14653     *
14654     * @return true if the drawing cache is enabled
14655     *
14656     * @see #setDrawingCacheEnabled(boolean)
14657     * @see #getDrawingCache()
14658     */
14659    @ViewDebug.ExportedProperty(category = "drawing")
14660    public boolean isDrawingCacheEnabled() {
14661        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14662    }
14663
14664    /**
14665     * Debugging utility which recursively outputs the dirty state of a view and its
14666     * descendants.
14667     *
14668     * @hide
14669     */
14670    @SuppressWarnings({"UnusedDeclaration"})
14671    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14672        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14673                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14674                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14675                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14676        if (clear) {
14677            mPrivateFlags &= clearMask;
14678        }
14679        if (this instanceof ViewGroup) {
14680            ViewGroup parent = (ViewGroup) this;
14681            final int count = parent.getChildCount();
14682            for (int i = 0; i < count; i++) {
14683                final View child = parent.getChildAt(i);
14684                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14685            }
14686        }
14687    }
14688
14689    /**
14690     * This method is used by ViewGroup to cause its children to restore or recreate their
14691     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14692     * to recreate its own display list, which would happen if it went through the normal
14693     * draw/dispatchDraw mechanisms.
14694     *
14695     * @hide
14696     */
14697    protected void dispatchGetDisplayList() {}
14698
14699    /**
14700     * A view that is not attached or hardware accelerated cannot create a display list.
14701     * This method checks these conditions and returns the appropriate result.
14702     *
14703     * @return true if view has the ability to create a display list, false otherwise.
14704     *
14705     * @hide
14706     */
14707    public boolean canHaveDisplayList() {
14708        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14709    }
14710
14711    private void updateDisplayListIfDirty() {
14712        final RenderNode renderNode = mRenderNode;
14713        if (!canHaveDisplayList()) {
14714            // can't populate RenderNode, don't try
14715            return;
14716        }
14717
14718        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14719                || !renderNode.isValid()
14720                || (mRecreateDisplayList)) {
14721            // Don't need to recreate the display list, just need to tell our
14722            // children to restore/recreate theirs
14723            if (renderNode.isValid()
14724                    && !mRecreateDisplayList) {
14725                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14726                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14727                dispatchGetDisplayList();
14728
14729                return; // no work needed
14730            }
14731
14732            // If we got here, we're recreating it. Mark it as such to ensure that
14733            // we copy in child display lists into ours in drawChild()
14734            mRecreateDisplayList = true;
14735
14736            int width = mRight - mLeft;
14737            int height = mBottom - mTop;
14738            int layerType = getLayerType();
14739
14740            final DisplayListCanvas canvas = renderNode.start(width, height);
14741            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14742
14743            try {
14744                final HardwareLayer layer = getHardwareLayer();
14745                if (layer != null && layer.isValid()) {
14746                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14747                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14748                    buildDrawingCache(true);
14749                    Bitmap cache = getDrawingCache(true);
14750                    if (cache != null) {
14751                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14752                    }
14753                } else {
14754                    computeScroll();
14755
14756                    canvas.translate(-mScrollX, -mScrollY);
14757                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14758                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14759
14760                    // Fast path for layouts with no backgrounds
14761                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14762                        dispatchDraw(canvas);
14763                        if (mOverlay != null && !mOverlay.isEmpty()) {
14764                            mOverlay.getOverlayView().draw(canvas);
14765                        }
14766                    } else {
14767                        draw(canvas);
14768                    }
14769                }
14770            } finally {
14771                renderNode.end(canvas);
14772                setDisplayListProperties(renderNode);
14773            }
14774        } else {
14775            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14776            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14777        }
14778    }
14779
14780    /**
14781     * Returns a RenderNode with View draw content recorded, which can be
14782     * used to draw this view again without executing its draw method.
14783     *
14784     * @return A RenderNode ready to replay, or null if caching is not enabled.
14785     *
14786     * @hide
14787     */
14788    public RenderNode getDisplayList() {
14789        updateDisplayListIfDirty();
14790        return mRenderNode;
14791    }
14792
14793    private void resetDisplayList() {
14794        if (mRenderNode.isValid()) {
14795            mRenderNode.destroyDisplayListData();
14796        }
14797
14798        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14799            mBackgroundRenderNode.destroyDisplayListData();
14800        }
14801    }
14802
14803    /**
14804     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14805     *
14806     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14807     *
14808     * @see #getDrawingCache(boolean)
14809     */
14810    public Bitmap getDrawingCache() {
14811        return getDrawingCache(false);
14812    }
14813
14814    /**
14815     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14816     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14817     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14818     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14819     * request the drawing cache by calling this method and draw it on screen if the
14820     * returned bitmap is not null.</p>
14821     *
14822     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14823     * this method will create a bitmap of the same size as this view. Because this bitmap
14824     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14825     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14826     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14827     * size than the view. This implies that your application must be able to handle this
14828     * size.</p>
14829     *
14830     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14831     *        the current density of the screen when the application is in compatibility
14832     *        mode.
14833     *
14834     * @return A bitmap representing this view or null if cache is disabled.
14835     *
14836     * @see #setDrawingCacheEnabled(boolean)
14837     * @see #isDrawingCacheEnabled()
14838     * @see #buildDrawingCache(boolean)
14839     * @see #destroyDrawingCache()
14840     */
14841    public Bitmap getDrawingCache(boolean autoScale) {
14842        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14843            return null;
14844        }
14845        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14846            buildDrawingCache(autoScale);
14847        }
14848        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14849    }
14850
14851    /**
14852     * <p>Frees the resources used by the drawing cache. If you call
14853     * {@link #buildDrawingCache()} manually without calling
14854     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14855     * should cleanup the cache with this method afterwards.</p>
14856     *
14857     * @see #setDrawingCacheEnabled(boolean)
14858     * @see #buildDrawingCache()
14859     * @see #getDrawingCache()
14860     */
14861    public void destroyDrawingCache() {
14862        if (mDrawingCache != null) {
14863            mDrawingCache.recycle();
14864            mDrawingCache = null;
14865        }
14866        if (mUnscaledDrawingCache != null) {
14867            mUnscaledDrawingCache.recycle();
14868            mUnscaledDrawingCache = null;
14869        }
14870    }
14871
14872    /**
14873     * Setting a solid background color for the drawing cache's bitmaps will improve
14874     * performance and memory usage. Note, though that this should only be used if this
14875     * view will always be drawn on top of a solid color.
14876     *
14877     * @param color The background color to use for the drawing cache's bitmap
14878     *
14879     * @see #setDrawingCacheEnabled(boolean)
14880     * @see #buildDrawingCache()
14881     * @see #getDrawingCache()
14882     */
14883    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
14884        if (color != mDrawingCacheBackgroundColor) {
14885            mDrawingCacheBackgroundColor = color;
14886            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14887        }
14888    }
14889
14890    /**
14891     * @see #setDrawingCacheBackgroundColor(int)
14892     *
14893     * @return The background color to used for the drawing cache's bitmap
14894     */
14895    @ColorInt
14896    public int getDrawingCacheBackgroundColor() {
14897        return mDrawingCacheBackgroundColor;
14898    }
14899
14900    /**
14901     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14902     *
14903     * @see #buildDrawingCache(boolean)
14904     */
14905    public void buildDrawingCache() {
14906        buildDrawingCache(false);
14907    }
14908
14909    /**
14910     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14911     *
14912     * <p>If you call {@link #buildDrawingCache()} manually without calling
14913     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14914     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14915     *
14916     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14917     * this method will create a bitmap of the same size as this view. Because this bitmap
14918     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14919     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14920     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14921     * size than the view. This implies that your application must be able to handle this
14922     * size.</p>
14923     *
14924     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14925     * you do not need the drawing cache bitmap, calling this method will increase memory
14926     * usage and cause the view to be rendered in software once, thus negatively impacting
14927     * performance.</p>
14928     *
14929     * @see #getDrawingCache()
14930     * @see #destroyDrawingCache()
14931     */
14932    public void buildDrawingCache(boolean autoScale) {
14933        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14934                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14935            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14936                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14937                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14938            }
14939            try {
14940                buildDrawingCacheImpl(autoScale);
14941            } finally {
14942                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14943            }
14944        }
14945    }
14946
14947    /**
14948     * private, internal implementation of buildDrawingCache, used to enable tracing
14949     */
14950    private void buildDrawingCacheImpl(boolean autoScale) {
14951        mCachingFailed = false;
14952
14953        int width = mRight - mLeft;
14954        int height = mBottom - mTop;
14955
14956        final AttachInfo attachInfo = mAttachInfo;
14957        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14958
14959        if (autoScale && scalingRequired) {
14960            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14961            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14962        }
14963
14964        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14965        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14966        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14967
14968        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14969        final long drawingCacheSize =
14970                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14971        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14972            if (width > 0 && height > 0) {
14973                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14974                        + projectedBitmapSize + " bytes, only "
14975                        + drawingCacheSize + " available");
14976            }
14977            destroyDrawingCache();
14978            mCachingFailed = true;
14979            return;
14980        }
14981
14982        boolean clear = true;
14983        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14984
14985        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14986            Bitmap.Config quality;
14987            if (!opaque) {
14988                // Never pick ARGB_4444 because it looks awful
14989                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14990                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14991                    case DRAWING_CACHE_QUALITY_AUTO:
14992                    case DRAWING_CACHE_QUALITY_LOW:
14993                    case DRAWING_CACHE_QUALITY_HIGH:
14994                    default:
14995                        quality = Bitmap.Config.ARGB_8888;
14996                        break;
14997                }
14998            } else {
14999                // Optimization for translucent windows
15000                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
15001                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
15002            }
15003
15004            // Try to cleanup memory
15005            if (bitmap != null) bitmap.recycle();
15006
15007            try {
15008                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15009                        width, height, quality);
15010                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
15011                if (autoScale) {
15012                    mDrawingCache = bitmap;
15013                } else {
15014                    mUnscaledDrawingCache = bitmap;
15015                }
15016                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
15017            } catch (OutOfMemoryError e) {
15018                // If there is not enough memory to create the bitmap cache, just
15019                // ignore the issue as bitmap caches are not required to draw the
15020                // view hierarchy
15021                if (autoScale) {
15022                    mDrawingCache = null;
15023                } else {
15024                    mUnscaledDrawingCache = null;
15025                }
15026                mCachingFailed = true;
15027                return;
15028            }
15029
15030            clear = drawingCacheBackgroundColor != 0;
15031        }
15032
15033        Canvas canvas;
15034        if (attachInfo != null) {
15035            canvas = attachInfo.mCanvas;
15036            if (canvas == null) {
15037                canvas = new Canvas();
15038            }
15039            canvas.setBitmap(bitmap);
15040            // Temporarily clobber the cached Canvas in case one of our children
15041            // is also using a drawing cache. Without this, the children would
15042            // steal the canvas by attaching their own bitmap to it and bad, bad
15043            // thing would happen (invisible views, corrupted drawings, etc.)
15044            attachInfo.mCanvas = null;
15045        } else {
15046            // This case should hopefully never or seldom happen
15047            canvas = new Canvas(bitmap);
15048        }
15049
15050        if (clear) {
15051            bitmap.eraseColor(drawingCacheBackgroundColor);
15052        }
15053
15054        computeScroll();
15055        final int restoreCount = canvas.save();
15056
15057        if (autoScale && scalingRequired) {
15058            final float scale = attachInfo.mApplicationScale;
15059            canvas.scale(scale, scale);
15060        }
15061
15062        canvas.translate(-mScrollX, -mScrollY);
15063
15064        mPrivateFlags |= PFLAG_DRAWN;
15065        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
15066                mLayerType != LAYER_TYPE_NONE) {
15067            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
15068        }
15069
15070        // Fast path for layouts with no backgrounds
15071        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15072            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15073            dispatchDraw(canvas);
15074            if (mOverlay != null && !mOverlay.isEmpty()) {
15075                mOverlay.getOverlayView().draw(canvas);
15076            }
15077        } else {
15078            draw(canvas);
15079        }
15080
15081        canvas.restoreToCount(restoreCount);
15082        canvas.setBitmap(null);
15083
15084        if (attachInfo != null) {
15085            // Restore the cached Canvas for our siblings
15086            attachInfo.mCanvas = canvas;
15087        }
15088    }
15089
15090    /**
15091     * Create a snapshot of the view into a bitmap.  We should probably make
15092     * some form of this public, but should think about the API.
15093     */
15094    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
15095        int width = mRight - mLeft;
15096        int height = mBottom - mTop;
15097
15098        final AttachInfo attachInfo = mAttachInfo;
15099        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
15100        width = (int) ((width * scale) + 0.5f);
15101        height = (int) ((height * scale) + 0.5f);
15102
15103        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15104                width > 0 ? width : 1, height > 0 ? height : 1, quality);
15105        if (bitmap == null) {
15106            throw new OutOfMemoryError();
15107        }
15108
15109        Resources resources = getResources();
15110        if (resources != null) {
15111            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
15112        }
15113
15114        Canvas canvas;
15115        if (attachInfo != null) {
15116            canvas = attachInfo.mCanvas;
15117            if (canvas == null) {
15118                canvas = new Canvas();
15119            }
15120            canvas.setBitmap(bitmap);
15121            // Temporarily clobber the cached Canvas in case one of our children
15122            // is also using a drawing cache. Without this, the children would
15123            // steal the canvas by attaching their own bitmap to it and bad, bad
15124            // things would happen (invisible views, corrupted drawings, etc.)
15125            attachInfo.mCanvas = null;
15126        } else {
15127            // This case should hopefully never or seldom happen
15128            canvas = new Canvas(bitmap);
15129        }
15130
15131        if ((backgroundColor & 0xff000000) != 0) {
15132            bitmap.eraseColor(backgroundColor);
15133        }
15134
15135        computeScroll();
15136        final int restoreCount = canvas.save();
15137        canvas.scale(scale, scale);
15138        canvas.translate(-mScrollX, -mScrollY);
15139
15140        // Temporarily remove the dirty mask
15141        int flags = mPrivateFlags;
15142        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15143
15144        // Fast path for layouts with no backgrounds
15145        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15146            dispatchDraw(canvas);
15147            if (mOverlay != null && !mOverlay.isEmpty()) {
15148                mOverlay.getOverlayView().draw(canvas);
15149            }
15150        } else {
15151            draw(canvas);
15152        }
15153
15154        mPrivateFlags = flags;
15155
15156        canvas.restoreToCount(restoreCount);
15157        canvas.setBitmap(null);
15158
15159        if (attachInfo != null) {
15160            // Restore the cached Canvas for our siblings
15161            attachInfo.mCanvas = canvas;
15162        }
15163
15164        return bitmap;
15165    }
15166
15167    /**
15168     * Indicates whether this View is currently in edit mode. A View is usually
15169     * in edit mode when displayed within a developer tool. For instance, if
15170     * this View is being drawn by a visual user interface builder, this method
15171     * should return true.
15172     *
15173     * Subclasses should check the return value of this method to provide
15174     * different behaviors if their normal behavior might interfere with the
15175     * host environment. For instance: the class spawns a thread in its
15176     * constructor, the drawing code relies on device-specific features, etc.
15177     *
15178     * This method is usually checked in the drawing code of custom widgets.
15179     *
15180     * @return True if this View is in edit mode, false otherwise.
15181     */
15182    public boolean isInEditMode() {
15183        return false;
15184    }
15185
15186    /**
15187     * If the View draws content inside its padding and enables fading edges,
15188     * it needs to support padding offsets. Padding offsets are added to the
15189     * fading edges to extend the length of the fade so that it covers pixels
15190     * drawn inside the padding.
15191     *
15192     * Subclasses of this class should override this method if they need
15193     * to draw content inside the padding.
15194     *
15195     * @return True if padding offset must be applied, false otherwise.
15196     *
15197     * @see #getLeftPaddingOffset()
15198     * @see #getRightPaddingOffset()
15199     * @see #getTopPaddingOffset()
15200     * @see #getBottomPaddingOffset()
15201     *
15202     * @since CURRENT
15203     */
15204    protected boolean isPaddingOffsetRequired() {
15205        return false;
15206    }
15207
15208    /**
15209     * Amount by which to extend the left fading region. Called only when
15210     * {@link #isPaddingOffsetRequired()} returns true.
15211     *
15212     * @return The left padding offset in pixels.
15213     *
15214     * @see #isPaddingOffsetRequired()
15215     *
15216     * @since CURRENT
15217     */
15218    protected int getLeftPaddingOffset() {
15219        return 0;
15220    }
15221
15222    /**
15223     * Amount by which to extend the right fading region. Called only when
15224     * {@link #isPaddingOffsetRequired()} returns true.
15225     *
15226     * @return The right padding offset in pixels.
15227     *
15228     * @see #isPaddingOffsetRequired()
15229     *
15230     * @since CURRENT
15231     */
15232    protected int getRightPaddingOffset() {
15233        return 0;
15234    }
15235
15236    /**
15237     * Amount by which to extend the top fading region. Called only when
15238     * {@link #isPaddingOffsetRequired()} returns true.
15239     *
15240     * @return The top padding offset in pixels.
15241     *
15242     * @see #isPaddingOffsetRequired()
15243     *
15244     * @since CURRENT
15245     */
15246    protected int getTopPaddingOffset() {
15247        return 0;
15248    }
15249
15250    /**
15251     * Amount by which to extend the bottom fading region. Called only when
15252     * {@link #isPaddingOffsetRequired()} returns true.
15253     *
15254     * @return The bottom padding offset in pixels.
15255     *
15256     * @see #isPaddingOffsetRequired()
15257     *
15258     * @since CURRENT
15259     */
15260    protected int getBottomPaddingOffset() {
15261        return 0;
15262    }
15263
15264    /**
15265     * @hide
15266     * @param offsetRequired
15267     */
15268    protected int getFadeTop(boolean offsetRequired) {
15269        int top = mPaddingTop;
15270        if (offsetRequired) top += getTopPaddingOffset();
15271        return top;
15272    }
15273
15274    /**
15275     * @hide
15276     * @param offsetRequired
15277     */
15278    protected int getFadeHeight(boolean offsetRequired) {
15279        int padding = mPaddingTop;
15280        if (offsetRequired) padding += getTopPaddingOffset();
15281        return mBottom - mTop - mPaddingBottom - padding;
15282    }
15283
15284    /**
15285     * <p>Indicates whether this view is attached to a hardware accelerated
15286     * window or not.</p>
15287     *
15288     * <p>Even if this method returns true, it does not mean that every call
15289     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15290     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15291     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15292     * window is hardware accelerated,
15293     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15294     * return false, and this method will return true.</p>
15295     *
15296     * @return True if the view is attached to a window and the window is
15297     *         hardware accelerated; false in any other case.
15298     */
15299    @ViewDebug.ExportedProperty(category = "drawing")
15300    public boolean isHardwareAccelerated() {
15301        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15302    }
15303
15304    /**
15305     * Sets a rectangular area on this view to which the view will be clipped
15306     * when it is drawn. Setting the value to null will remove the clip bounds
15307     * and the view will draw normally, using its full bounds.
15308     *
15309     * @param clipBounds The rectangular area, in the local coordinates of
15310     * this view, to which future drawing operations will be clipped.
15311     */
15312    public void setClipBounds(Rect clipBounds) {
15313        if (clipBounds == mClipBounds
15314                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15315            return;
15316        }
15317        if (clipBounds != null) {
15318            if (mClipBounds == null) {
15319                mClipBounds = new Rect(clipBounds);
15320            } else {
15321                mClipBounds.set(clipBounds);
15322            }
15323        } else {
15324            mClipBounds = null;
15325        }
15326        mRenderNode.setClipBounds(mClipBounds);
15327        invalidateViewProperty(false, false);
15328    }
15329
15330    /**
15331     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15332     *
15333     * @return A copy of the current clip bounds if clip bounds are set,
15334     * otherwise null.
15335     */
15336    public Rect getClipBounds() {
15337        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15338    }
15339
15340
15341    /**
15342     * Populates an output rectangle with the clip bounds of the view,
15343     * returning {@code true} if successful or {@code false} if the view's
15344     * clip bounds are {@code null}.
15345     *
15346     * @param outRect rectangle in which to place the clip bounds of the view
15347     * @return {@code true} if successful or {@code false} if the view's
15348     *         clip bounds are {@code null}
15349     */
15350    public boolean getClipBounds(Rect outRect) {
15351        if (mClipBounds != null) {
15352            outRect.set(mClipBounds);
15353            return true;
15354        }
15355        return false;
15356    }
15357
15358    /**
15359     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15360     * case of an active Animation being run on the view.
15361     */
15362    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15363            Animation a, boolean scalingRequired) {
15364        Transformation invalidationTransform;
15365        final int flags = parent.mGroupFlags;
15366        final boolean initialized = a.isInitialized();
15367        if (!initialized) {
15368            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15369            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15370            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15371            onAnimationStart();
15372        }
15373
15374        final Transformation t = parent.getChildTransformation();
15375        boolean more = a.getTransformation(drawingTime, t, 1f);
15376        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15377            if (parent.mInvalidationTransformation == null) {
15378                parent.mInvalidationTransformation = new Transformation();
15379            }
15380            invalidationTransform = parent.mInvalidationTransformation;
15381            a.getTransformation(drawingTime, invalidationTransform, 1f);
15382        } else {
15383            invalidationTransform = t;
15384        }
15385
15386        if (more) {
15387            if (!a.willChangeBounds()) {
15388                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15389                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15390                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15391                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15392                    // The child need to draw an animation, potentially offscreen, so
15393                    // make sure we do not cancel invalidate requests
15394                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15395                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15396                }
15397            } else {
15398                if (parent.mInvalidateRegion == null) {
15399                    parent.mInvalidateRegion = new RectF();
15400                }
15401                final RectF region = parent.mInvalidateRegion;
15402                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15403                        invalidationTransform);
15404
15405                // The child need to draw an animation, potentially offscreen, so
15406                // make sure we do not cancel invalidate requests
15407                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15408
15409                final int left = mLeft + (int) region.left;
15410                final int top = mTop + (int) region.top;
15411                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15412                        top + (int) (region.height() + .5f));
15413            }
15414        }
15415        return more;
15416    }
15417
15418    /**
15419     * This method is called by getDisplayList() when a display list is recorded for a View.
15420     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15421     */
15422    void setDisplayListProperties(RenderNode renderNode) {
15423        if (renderNode != null) {
15424            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15425            renderNode.setClipToBounds(mParent instanceof ViewGroup
15426                    && ((ViewGroup) mParent).getClipChildren());
15427
15428            float alpha = 1;
15429            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15430                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15431                ViewGroup parentVG = (ViewGroup) mParent;
15432                final Transformation t = parentVG.getChildTransformation();
15433                if (parentVG.getChildStaticTransformation(this, t)) {
15434                    final int transformType = t.getTransformationType();
15435                    if (transformType != Transformation.TYPE_IDENTITY) {
15436                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15437                            alpha = t.getAlpha();
15438                        }
15439                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15440                            renderNode.setStaticMatrix(t.getMatrix());
15441                        }
15442                    }
15443                }
15444            }
15445            if (mTransformationInfo != null) {
15446                alpha *= getFinalAlpha();
15447                if (alpha < 1) {
15448                    final int multipliedAlpha = (int) (255 * alpha);
15449                    if (onSetAlpha(multipliedAlpha)) {
15450                        alpha = 1;
15451                    }
15452                }
15453                renderNode.setAlpha(alpha);
15454            } else if (alpha < 1) {
15455                renderNode.setAlpha(alpha);
15456            }
15457        }
15458    }
15459
15460    /**
15461     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15462     *
15463     * This is where the View specializes rendering behavior based on layer type,
15464     * and hardware acceleration.
15465     */
15466    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15467        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15468        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15469         *
15470         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15471         * HW accelerated, it can't handle drawing RenderNodes.
15472         */
15473        boolean drawingWithRenderNode = mAttachInfo != null
15474                && mAttachInfo.mHardwareAccelerated
15475                && hardwareAcceleratedCanvas;
15476
15477        boolean more = false;
15478        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15479        final int parentFlags = parent.mGroupFlags;
15480
15481        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15482            parent.getChildTransformation().clear();
15483            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15484        }
15485
15486        Transformation transformToApply = null;
15487        boolean concatMatrix = false;
15488        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15489        final Animation a = getAnimation();
15490        if (a != null) {
15491            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15492            concatMatrix = a.willChangeTransformationMatrix();
15493            if (concatMatrix) {
15494                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15495            }
15496            transformToApply = parent.getChildTransformation();
15497        } else {
15498            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15499                // No longer animating: clear out old animation matrix
15500                mRenderNode.setAnimationMatrix(null);
15501                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15502            }
15503            if (!drawingWithRenderNode
15504                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15505                final Transformation t = parent.getChildTransformation();
15506                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15507                if (hasTransform) {
15508                    final int transformType = t.getTransformationType();
15509                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15510                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15511                }
15512            }
15513        }
15514
15515        concatMatrix |= !childHasIdentityMatrix;
15516
15517        // Sets the flag as early as possible to allow draw() implementations
15518        // to call invalidate() successfully when doing animations
15519        mPrivateFlags |= PFLAG_DRAWN;
15520
15521        if (!concatMatrix &&
15522                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15523                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15524                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15525                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15526            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15527            return more;
15528        }
15529        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15530
15531        if (hardwareAcceleratedCanvas) {
15532            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15533            // retain the flag's value temporarily in the mRecreateDisplayList flag
15534            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15535            mPrivateFlags &= ~PFLAG_INVALIDATED;
15536        }
15537
15538        RenderNode renderNode = null;
15539        Bitmap cache = null;
15540        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
15541        if (layerType == LAYER_TYPE_SOFTWARE
15542                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15543            // If not drawing with RenderNode, treat HW layers as SW
15544            layerType = LAYER_TYPE_SOFTWARE;
15545            buildDrawingCache(true);
15546            cache = getDrawingCache(true);
15547        }
15548
15549        if (drawingWithRenderNode) {
15550            // Delay getting the display list until animation-driven alpha values are
15551            // set up and possibly passed on to the view
15552            renderNode = getDisplayList();
15553            if (!renderNode.isValid()) {
15554                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15555                // to getDisplayList(), the display list will be marked invalid and we should not
15556                // try to use it again.
15557                renderNode = null;
15558                drawingWithRenderNode = false;
15559            }
15560        }
15561
15562        int sx = 0;
15563        int sy = 0;
15564        if (!drawingWithRenderNode) {
15565            computeScroll();
15566            sx = mScrollX;
15567            sy = mScrollY;
15568        }
15569
15570        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
15571        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
15572
15573        int restoreTo = -1;
15574        if (!drawingWithRenderNode || transformToApply != null) {
15575            restoreTo = canvas.save();
15576        }
15577        if (offsetForScroll) {
15578            canvas.translate(mLeft - sx, mTop - sy);
15579        } else {
15580            if (!drawingWithRenderNode) {
15581                canvas.translate(mLeft, mTop);
15582            }
15583            if (scalingRequired) {
15584                if (drawingWithRenderNode) {
15585                    // TODO: Might not need this if we put everything inside the DL
15586                    restoreTo = canvas.save();
15587                }
15588                // mAttachInfo cannot be null, otherwise scalingRequired == false
15589                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15590                canvas.scale(scale, scale);
15591            }
15592        }
15593
15594        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15595        if (transformToApply != null
15596                || alpha < 1
15597                || !hasIdentityMatrix()
15598                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15599            if (transformToApply != null || !childHasIdentityMatrix) {
15600                int transX = 0;
15601                int transY = 0;
15602
15603                if (offsetForScroll) {
15604                    transX = -sx;
15605                    transY = -sy;
15606                }
15607
15608                if (transformToApply != null) {
15609                    if (concatMatrix) {
15610                        if (drawingWithRenderNode) {
15611                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15612                        } else {
15613                            // Undo the scroll translation, apply the transformation matrix,
15614                            // then redo the scroll translate to get the correct result.
15615                            canvas.translate(-transX, -transY);
15616                            canvas.concat(transformToApply.getMatrix());
15617                            canvas.translate(transX, transY);
15618                        }
15619                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15620                    }
15621
15622                    float transformAlpha = transformToApply.getAlpha();
15623                    if (transformAlpha < 1) {
15624                        alpha *= transformAlpha;
15625                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15626                    }
15627                }
15628
15629                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
15630                    canvas.translate(-transX, -transY);
15631                    canvas.concat(getMatrix());
15632                    canvas.translate(transX, transY);
15633                }
15634            }
15635
15636            // Deal with alpha if it is or used to be <1
15637            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15638                if (alpha < 1) {
15639                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15640                } else {
15641                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15642                }
15643                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15644                if (!drawingWithDrawingCache) {
15645                    final int multipliedAlpha = (int) (255 * alpha);
15646                    if (!onSetAlpha(multipliedAlpha)) {
15647                        if (drawingWithRenderNode) {
15648                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15649                        } else if (layerType == LAYER_TYPE_NONE) {
15650                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
15651                                    multipliedAlpha);
15652                        }
15653                    } else {
15654                        // Alpha is handled by the child directly, clobber the layer's alpha
15655                        mPrivateFlags |= PFLAG_ALPHA_SET;
15656                    }
15657                }
15658            }
15659        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15660            onSetAlpha(255);
15661            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15662        }
15663
15664        if (!drawingWithRenderNode) {
15665            // apply clips directly, since RenderNode won't do it for this draw
15666            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
15667                if (offsetForScroll) {
15668                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
15669                } else {
15670                    if (!scalingRequired || cache == null) {
15671                        canvas.clipRect(0, 0, getWidth(), getHeight());
15672                    } else {
15673                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15674                    }
15675                }
15676            }
15677
15678            if (mClipBounds != null) {
15679                // clip bounds ignore scroll
15680                canvas.clipRect(mClipBounds);
15681            }
15682        }
15683
15684        if (!drawingWithDrawingCache) {
15685            if (drawingWithRenderNode) {
15686                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15687                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15688            } else {
15689                // Fast path for layouts with no backgrounds
15690                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15691                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15692                    dispatchDraw(canvas);
15693                } else {
15694                    draw(canvas);
15695                }
15696            }
15697        } else if (cache != null) {
15698            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15699            Paint cachePaint;
15700            int restoreAlpha = 0;
15701
15702            if (layerType == LAYER_TYPE_NONE) {
15703                cachePaint = parent.mCachePaint;
15704                if (cachePaint == null) {
15705                    cachePaint = new Paint();
15706                    cachePaint.setDither(false);
15707                    parent.mCachePaint = cachePaint;
15708                }
15709            } else {
15710                cachePaint = mLayerPaint;
15711                restoreAlpha = mLayerPaint.getAlpha();
15712            }
15713            cachePaint.setAlpha((int) (alpha * 255));
15714            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15715            cachePaint.setAlpha(restoreAlpha);
15716        }
15717
15718        if (restoreTo >= 0) {
15719            canvas.restoreToCount(restoreTo);
15720        }
15721
15722        if (a != null && !more) {
15723            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
15724                onSetAlpha(255);
15725            }
15726            parent.finishAnimatingView(this, a);
15727        }
15728
15729        if (more && hardwareAcceleratedCanvas) {
15730            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15731                // alpha animations should cause the child to recreate its display list
15732                invalidate(true);
15733            }
15734        }
15735
15736        mRecreateDisplayList = false;
15737
15738        return more;
15739    }
15740
15741    /**
15742     * Manually render this view (and all of its children) to the given Canvas.
15743     * The view must have already done a full layout before this function is
15744     * called.  When implementing a view, implement
15745     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15746     * If you do need to override this method, call the superclass version.
15747     *
15748     * @param canvas The Canvas to which the View is rendered.
15749     */
15750    @CallSuper
15751    public void draw(Canvas canvas) {
15752        final int privateFlags = mPrivateFlags;
15753        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15754                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15755        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15756
15757        /*
15758         * Draw traversal performs several drawing steps which must be executed
15759         * in the appropriate order:
15760         *
15761         *      1. Draw the background
15762         *      2. If necessary, save the canvas' layers to prepare for fading
15763         *      3. Draw view's content
15764         *      4. Draw children
15765         *      5. If necessary, draw the fading edges and restore layers
15766         *      6. Draw decorations (scrollbars for instance)
15767         */
15768
15769        // Step 1, draw the background, if needed
15770        int saveCount;
15771
15772        if (!dirtyOpaque) {
15773            drawBackground(canvas);
15774        }
15775
15776        // skip step 2 & 5 if possible (common case)
15777        final int viewFlags = mViewFlags;
15778        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15779        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15780        if (!verticalEdges && !horizontalEdges) {
15781            // Step 3, draw the content
15782            if (!dirtyOpaque) onDraw(canvas);
15783
15784            // Step 4, draw the children
15785            dispatchDraw(canvas);
15786
15787            // Overlay is part of the content and draws beneath Foreground
15788            if (mOverlay != null && !mOverlay.isEmpty()) {
15789                mOverlay.getOverlayView().dispatchDraw(canvas);
15790            }
15791
15792            // Step 6, draw decorations (foreground, scrollbars)
15793            onDrawForeground(canvas);
15794
15795            // we're done...
15796            return;
15797        }
15798
15799        /*
15800         * Here we do the full fledged routine...
15801         * (this is an uncommon case where speed matters less,
15802         * this is why we repeat some of the tests that have been
15803         * done above)
15804         */
15805
15806        boolean drawTop = false;
15807        boolean drawBottom = false;
15808        boolean drawLeft = false;
15809        boolean drawRight = false;
15810
15811        float topFadeStrength = 0.0f;
15812        float bottomFadeStrength = 0.0f;
15813        float leftFadeStrength = 0.0f;
15814        float rightFadeStrength = 0.0f;
15815
15816        // Step 2, save the canvas' layers
15817        int paddingLeft = mPaddingLeft;
15818
15819        final boolean offsetRequired = isPaddingOffsetRequired();
15820        if (offsetRequired) {
15821            paddingLeft += getLeftPaddingOffset();
15822        }
15823
15824        int left = mScrollX + paddingLeft;
15825        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15826        int top = mScrollY + getFadeTop(offsetRequired);
15827        int bottom = top + getFadeHeight(offsetRequired);
15828
15829        if (offsetRequired) {
15830            right += getRightPaddingOffset();
15831            bottom += getBottomPaddingOffset();
15832        }
15833
15834        final ScrollabilityCache scrollabilityCache = mScrollCache;
15835        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15836        int length = (int) fadeHeight;
15837
15838        // clip the fade length if top and bottom fades overlap
15839        // overlapping fades produce odd-looking artifacts
15840        if (verticalEdges && (top + length > bottom - length)) {
15841            length = (bottom - top) / 2;
15842        }
15843
15844        // also clip horizontal fades if necessary
15845        if (horizontalEdges && (left + length > right - length)) {
15846            length = (right - left) / 2;
15847        }
15848
15849        if (verticalEdges) {
15850            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15851            drawTop = topFadeStrength * fadeHeight > 1.0f;
15852            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15853            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15854        }
15855
15856        if (horizontalEdges) {
15857            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15858            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15859            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15860            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15861        }
15862
15863        saveCount = canvas.getSaveCount();
15864
15865        int solidColor = getSolidColor();
15866        if (solidColor == 0) {
15867            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15868
15869            if (drawTop) {
15870                canvas.saveLayer(left, top, right, top + length, null, flags);
15871            }
15872
15873            if (drawBottom) {
15874                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15875            }
15876
15877            if (drawLeft) {
15878                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15879            }
15880
15881            if (drawRight) {
15882                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15883            }
15884        } else {
15885            scrollabilityCache.setFadeColor(solidColor);
15886        }
15887
15888        // Step 3, draw the content
15889        if (!dirtyOpaque) onDraw(canvas);
15890
15891        // Step 4, draw the children
15892        dispatchDraw(canvas);
15893
15894        // Step 5, draw the fade effect and restore layers
15895        final Paint p = scrollabilityCache.paint;
15896        final Matrix matrix = scrollabilityCache.matrix;
15897        final Shader fade = scrollabilityCache.shader;
15898
15899        if (drawTop) {
15900            matrix.setScale(1, fadeHeight * topFadeStrength);
15901            matrix.postTranslate(left, top);
15902            fade.setLocalMatrix(matrix);
15903            p.setShader(fade);
15904            canvas.drawRect(left, top, right, top + length, p);
15905        }
15906
15907        if (drawBottom) {
15908            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15909            matrix.postRotate(180);
15910            matrix.postTranslate(left, bottom);
15911            fade.setLocalMatrix(matrix);
15912            p.setShader(fade);
15913            canvas.drawRect(left, bottom - length, right, bottom, p);
15914        }
15915
15916        if (drawLeft) {
15917            matrix.setScale(1, fadeHeight * leftFadeStrength);
15918            matrix.postRotate(-90);
15919            matrix.postTranslate(left, top);
15920            fade.setLocalMatrix(matrix);
15921            p.setShader(fade);
15922            canvas.drawRect(left, top, left + length, bottom, p);
15923        }
15924
15925        if (drawRight) {
15926            matrix.setScale(1, fadeHeight * rightFadeStrength);
15927            matrix.postRotate(90);
15928            matrix.postTranslate(right, top);
15929            fade.setLocalMatrix(matrix);
15930            p.setShader(fade);
15931            canvas.drawRect(right - length, top, right, bottom, p);
15932        }
15933
15934        canvas.restoreToCount(saveCount);
15935
15936        // Overlay is part of the content and draws beneath Foreground
15937        if (mOverlay != null && !mOverlay.isEmpty()) {
15938            mOverlay.getOverlayView().dispatchDraw(canvas);
15939        }
15940
15941        // Step 6, draw decorations (foreground, scrollbars)
15942        onDrawForeground(canvas);
15943    }
15944
15945    /**
15946     * Draws the background onto the specified canvas.
15947     *
15948     * @param canvas Canvas on which to draw the background
15949     */
15950    private void drawBackground(Canvas canvas) {
15951        final Drawable background = mBackground;
15952        if (background == null) {
15953            return;
15954        }
15955
15956        setBackgroundBounds();
15957
15958        // Attempt to use a display list if requested.
15959        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15960                && mAttachInfo.mHardwareRenderer != null) {
15961            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15962
15963            final RenderNode renderNode = mBackgroundRenderNode;
15964            if (renderNode != null && renderNode.isValid()) {
15965                setBackgroundRenderNodeProperties(renderNode);
15966                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15967                return;
15968            }
15969        }
15970
15971        final int scrollX = mScrollX;
15972        final int scrollY = mScrollY;
15973        if ((scrollX | scrollY) == 0) {
15974            background.draw(canvas);
15975        } else {
15976            canvas.translate(scrollX, scrollY);
15977            background.draw(canvas);
15978            canvas.translate(-scrollX, -scrollY);
15979        }
15980    }
15981
15982    /**
15983     * Sets the correct background bounds and rebuilds the outline, if needed.
15984     * <p/>
15985     * This is called by LayoutLib.
15986     */
15987    void setBackgroundBounds() {
15988        if (mBackgroundSizeChanged && mBackground != null) {
15989            mBackground.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15990            mBackgroundSizeChanged = false;
15991            rebuildOutline();
15992        }
15993    }
15994
15995    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15996        renderNode.setTranslationX(mScrollX);
15997        renderNode.setTranslationY(mScrollY);
15998    }
15999
16000    /**
16001     * Creates a new display list or updates the existing display list for the
16002     * specified Drawable.
16003     *
16004     * @param drawable Drawable for which to create a display list
16005     * @param renderNode Existing RenderNode, or {@code null}
16006     * @return A valid display list for the specified drawable
16007     */
16008    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
16009        if (renderNode == null) {
16010            renderNode = RenderNode.create(drawable.getClass().getName(), this);
16011        }
16012
16013        final Rect bounds = drawable.getBounds();
16014        final int width = bounds.width();
16015        final int height = bounds.height();
16016        final DisplayListCanvas canvas = renderNode.start(width, height);
16017
16018        // Reverse left/top translation done by drawable canvas, which will
16019        // instead be applied by rendernode's LTRB bounds below. This way, the
16020        // drawable's bounds match with its rendernode bounds and its content
16021        // will lie within those bounds in the rendernode tree.
16022        canvas.translate(-bounds.left, -bounds.top);
16023
16024        try {
16025            drawable.draw(canvas);
16026        } finally {
16027            renderNode.end(canvas);
16028        }
16029
16030        // Set up drawable properties that are view-independent.
16031        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
16032        renderNode.setProjectBackwards(drawable.isProjected());
16033        renderNode.setProjectionReceiver(true);
16034        renderNode.setClipToBounds(false);
16035        return renderNode;
16036    }
16037
16038    /**
16039     * Returns the overlay for this view, creating it if it does not yet exist.
16040     * Adding drawables to the overlay will cause them to be displayed whenever
16041     * the view itself is redrawn. Objects in the overlay should be actively
16042     * managed: remove them when they should not be displayed anymore. The
16043     * overlay will always have the same size as its host view.
16044     *
16045     * <p>Note: Overlays do not currently work correctly with {@link
16046     * SurfaceView} or {@link TextureView}; contents in overlays for these
16047     * types of views may not display correctly.</p>
16048     *
16049     * @return The ViewOverlay object for this view.
16050     * @see ViewOverlay
16051     */
16052    public ViewOverlay getOverlay() {
16053        if (mOverlay == null) {
16054            mOverlay = new ViewOverlay(mContext, this);
16055        }
16056        return mOverlay;
16057    }
16058
16059    /**
16060     * Override this if your view is known to always be drawn on top of a solid color background,
16061     * and needs to draw fading edges. Returning a non-zero color enables the view system to
16062     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
16063     * should be set to 0xFF.
16064     *
16065     * @see #setVerticalFadingEdgeEnabled(boolean)
16066     * @see #setHorizontalFadingEdgeEnabled(boolean)
16067     *
16068     * @return The known solid color background for this view, or 0 if the color may vary
16069     */
16070    @ViewDebug.ExportedProperty(category = "drawing")
16071    @ColorInt
16072    public int getSolidColor() {
16073        return 0;
16074    }
16075
16076    /**
16077     * Build a human readable string representation of the specified view flags.
16078     *
16079     * @param flags the view flags to convert to a string
16080     * @return a String representing the supplied flags
16081     */
16082    private static String printFlags(int flags) {
16083        String output = "";
16084        int numFlags = 0;
16085        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
16086            output += "TAKES_FOCUS";
16087            numFlags++;
16088        }
16089
16090        switch (flags & VISIBILITY_MASK) {
16091        case INVISIBLE:
16092            if (numFlags > 0) {
16093                output += " ";
16094            }
16095            output += "INVISIBLE";
16096            // USELESS HERE numFlags++;
16097            break;
16098        case GONE:
16099            if (numFlags > 0) {
16100                output += " ";
16101            }
16102            output += "GONE";
16103            // USELESS HERE numFlags++;
16104            break;
16105        default:
16106            break;
16107        }
16108        return output;
16109    }
16110
16111    /**
16112     * Build a human readable string representation of the specified private
16113     * view flags.
16114     *
16115     * @param privateFlags the private view flags to convert to a string
16116     * @return a String representing the supplied flags
16117     */
16118    private static String printPrivateFlags(int privateFlags) {
16119        String output = "";
16120        int numFlags = 0;
16121
16122        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
16123            output += "WANTS_FOCUS";
16124            numFlags++;
16125        }
16126
16127        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
16128            if (numFlags > 0) {
16129                output += " ";
16130            }
16131            output += "FOCUSED";
16132            numFlags++;
16133        }
16134
16135        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
16136            if (numFlags > 0) {
16137                output += " ";
16138            }
16139            output += "SELECTED";
16140            numFlags++;
16141        }
16142
16143        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
16144            if (numFlags > 0) {
16145                output += " ";
16146            }
16147            output += "IS_ROOT_NAMESPACE";
16148            numFlags++;
16149        }
16150
16151        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
16152            if (numFlags > 0) {
16153                output += " ";
16154            }
16155            output += "HAS_BOUNDS";
16156            numFlags++;
16157        }
16158
16159        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
16160            if (numFlags > 0) {
16161                output += " ";
16162            }
16163            output += "DRAWN";
16164            // USELESS HERE numFlags++;
16165        }
16166        return output;
16167    }
16168
16169    /**
16170     * <p>Indicates whether or not this view's layout will be requested during
16171     * the next hierarchy layout pass.</p>
16172     *
16173     * @return true if the layout will be forced during next layout pass
16174     */
16175    public boolean isLayoutRequested() {
16176        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
16177    }
16178
16179    /**
16180     * Return true if o is a ViewGroup that is laying out using optical bounds.
16181     * @hide
16182     */
16183    public static boolean isLayoutModeOptical(Object o) {
16184        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
16185    }
16186
16187    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
16188        Insets parentInsets = mParent instanceof View ?
16189                ((View) mParent).getOpticalInsets() : Insets.NONE;
16190        Insets childInsets = getOpticalInsets();
16191        return setFrame(
16192                left   + parentInsets.left - childInsets.left,
16193                top    + parentInsets.top  - childInsets.top,
16194                right  + parentInsets.left + childInsets.right,
16195                bottom + parentInsets.top  + childInsets.bottom);
16196    }
16197
16198    /**
16199     * Assign a size and position to a view and all of its
16200     * descendants
16201     *
16202     * <p>This is the second phase of the layout mechanism.
16203     * (The first is measuring). In this phase, each parent calls
16204     * layout on all of its children to position them.
16205     * This is typically done using the child measurements
16206     * that were stored in the measure pass().</p>
16207     *
16208     * <p>Derived classes should not override this method.
16209     * Derived classes with children should override
16210     * onLayout. In that method, they should
16211     * call layout on each of their children.</p>
16212     *
16213     * @param l Left position, relative to parent
16214     * @param t Top position, relative to parent
16215     * @param r Right position, relative to parent
16216     * @param b Bottom position, relative to parent
16217     */
16218    @SuppressWarnings({"unchecked"})
16219    public void layout(int l, int t, int r, int b) {
16220        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
16221            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
16222            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16223        }
16224
16225        int oldL = mLeft;
16226        int oldT = mTop;
16227        int oldB = mBottom;
16228        int oldR = mRight;
16229
16230        boolean changed = isLayoutModeOptical(mParent) ?
16231                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
16232
16233        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
16234            onLayout(changed, l, t, r, b);
16235            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
16236
16237            ListenerInfo li = mListenerInfo;
16238            if (li != null && li.mOnLayoutChangeListeners != null) {
16239                ArrayList<OnLayoutChangeListener> listenersCopy =
16240                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16241                int numListeners = listenersCopy.size();
16242                for (int i = 0; i < numListeners; ++i) {
16243                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16244                }
16245            }
16246        }
16247
16248        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16249        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16250    }
16251
16252    /**
16253     * Called from layout when this view should
16254     * assign a size and position to each of its children.
16255     *
16256     * Derived classes with children should override
16257     * this method and call layout on each of
16258     * their children.
16259     * @param changed This is a new size or position for this view
16260     * @param left Left position, relative to parent
16261     * @param top Top position, relative to parent
16262     * @param right Right position, relative to parent
16263     * @param bottom Bottom position, relative to parent
16264     */
16265    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16266    }
16267
16268    /**
16269     * Assign a size and position to this view.
16270     *
16271     * This is called from layout.
16272     *
16273     * @param left Left position, relative to parent
16274     * @param top Top position, relative to parent
16275     * @param right Right position, relative to parent
16276     * @param bottom Bottom position, relative to parent
16277     * @return true if the new size and position are different than the
16278     *         previous ones
16279     * {@hide}
16280     */
16281    protected boolean setFrame(int left, int top, int right, int bottom) {
16282        boolean changed = false;
16283
16284        if (DBG) {
16285            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16286                    + right + "," + bottom + ")");
16287        }
16288
16289        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16290            changed = true;
16291
16292            // Remember our drawn bit
16293            int drawn = mPrivateFlags & PFLAG_DRAWN;
16294
16295            int oldWidth = mRight - mLeft;
16296            int oldHeight = mBottom - mTop;
16297            int newWidth = right - left;
16298            int newHeight = bottom - top;
16299            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16300
16301            // Invalidate our old position
16302            invalidate(sizeChanged);
16303
16304            mLeft = left;
16305            mTop = top;
16306            mRight = right;
16307            mBottom = bottom;
16308            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16309
16310            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16311
16312
16313            if (sizeChanged) {
16314                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16315            }
16316
16317            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16318                // If we are visible, force the DRAWN bit to on so that
16319                // this invalidate will go through (at least to our parent).
16320                // This is because someone may have invalidated this view
16321                // before this call to setFrame came in, thereby clearing
16322                // the DRAWN bit.
16323                mPrivateFlags |= PFLAG_DRAWN;
16324                invalidate(sizeChanged);
16325                // parent display list may need to be recreated based on a change in the bounds
16326                // of any child
16327                invalidateParentCaches();
16328            }
16329
16330            // Reset drawn bit to original value (invalidate turns it off)
16331            mPrivateFlags |= drawn;
16332
16333            mBackgroundSizeChanged = true;
16334            if (mForegroundInfo != null) {
16335                mForegroundInfo.mBoundsChanged = true;
16336            }
16337
16338            notifySubtreeAccessibilityStateChangedIfNeeded();
16339        }
16340        return changed;
16341    }
16342
16343    /**
16344     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16345     * @hide
16346     */
16347    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16348        setFrame(left, top, right, bottom);
16349    }
16350
16351    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16352        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16353        if (mOverlay != null) {
16354            mOverlay.getOverlayView().setRight(newWidth);
16355            mOverlay.getOverlayView().setBottom(newHeight);
16356        }
16357        rebuildOutline();
16358    }
16359
16360    /**
16361     * Finalize inflating a view from XML.  This is called as the last phase
16362     * of inflation, after all child views have been added.
16363     *
16364     * <p>Even if the subclass overrides onFinishInflate, they should always be
16365     * sure to call the super method, so that we get called.
16366     */
16367    @CallSuper
16368    protected void onFinishInflate() {
16369    }
16370
16371    /**
16372     * Returns the resources associated with this view.
16373     *
16374     * @return Resources object.
16375     */
16376    public Resources getResources() {
16377        return mResources;
16378    }
16379
16380    /**
16381     * Invalidates the specified Drawable.
16382     *
16383     * @param drawable the drawable to invalidate
16384     */
16385    @Override
16386    public void invalidateDrawable(@NonNull Drawable drawable) {
16387        if (verifyDrawable(drawable)) {
16388            final Rect dirty = drawable.getDirtyBounds();
16389            final int scrollX = mScrollX;
16390            final int scrollY = mScrollY;
16391
16392            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16393                    dirty.right + scrollX, dirty.bottom + scrollY);
16394            rebuildOutline();
16395        }
16396    }
16397
16398    /**
16399     * Schedules an action on a drawable to occur at a specified time.
16400     *
16401     * @param who the recipient of the action
16402     * @param what the action to run on the drawable
16403     * @param when the time at which the action must occur. Uses the
16404     *        {@link SystemClock#uptimeMillis} timebase.
16405     */
16406    @Override
16407    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16408        if (verifyDrawable(who) && what != null) {
16409            final long delay = when - SystemClock.uptimeMillis();
16410            if (mAttachInfo != null) {
16411                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16412                        Choreographer.CALLBACK_ANIMATION, what, who,
16413                        Choreographer.subtractFrameDelay(delay));
16414            } else {
16415                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16416            }
16417        }
16418    }
16419
16420    /**
16421     * Cancels a scheduled action on a drawable.
16422     *
16423     * @param who the recipient of the action
16424     * @param what the action to cancel
16425     */
16426    @Override
16427    public void unscheduleDrawable(Drawable who, Runnable what) {
16428        if (verifyDrawable(who) && what != null) {
16429            if (mAttachInfo != null) {
16430                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16431                        Choreographer.CALLBACK_ANIMATION, what, who);
16432            }
16433            ViewRootImpl.getRunQueue().removeCallbacks(what);
16434        }
16435    }
16436
16437    /**
16438     * Unschedule any events associated with the given Drawable.  This can be
16439     * used when selecting a new Drawable into a view, so that the previous
16440     * one is completely unscheduled.
16441     *
16442     * @param who The Drawable to unschedule.
16443     *
16444     * @see #drawableStateChanged
16445     */
16446    public void unscheduleDrawable(Drawable who) {
16447        if (mAttachInfo != null && who != null) {
16448            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16449                    Choreographer.CALLBACK_ANIMATION, null, who);
16450        }
16451    }
16452
16453    /**
16454     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16455     * that the View directionality can and will be resolved before its Drawables.
16456     *
16457     * Will call {@link View#onResolveDrawables} when resolution is done.
16458     *
16459     * @hide
16460     */
16461    protected void resolveDrawables() {
16462        // Drawables resolution may need to happen before resolving the layout direction (which is
16463        // done only during the measure() call).
16464        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16465        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16466        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16467        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16468        // direction to be resolved as its resolved value will be the same as its raw value.
16469        if (!isLayoutDirectionResolved() &&
16470                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16471            return;
16472        }
16473
16474        final int layoutDirection = isLayoutDirectionResolved() ?
16475                getLayoutDirection() : getRawLayoutDirection();
16476
16477        if (mBackground != null) {
16478            mBackground.setLayoutDirection(layoutDirection);
16479        }
16480        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16481            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16482        }
16483        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16484        onResolveDrawables(layoutDirection);
16485    }
16486
16487    boolean areDrawablesResolved() {
16488        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16489    }
16490
16491    /**
16492     * Called when layout direction has been resolved.
16493     *
16494     * The default implementation does nothing.
16495     *
16496     * @param layoutDirection The resolved layout direction.
16497     *
16498     * @see #LAYOUT_DIRECTION_LTR
16499     * @see #LAYOUT_DIRECTION_RTL
16500     *
16501     * @hide
16502     */
16503    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16504    }
16505
16506    /**
16507     * @hide
16508     */
16509    protected void resetResolvedDrawables() {
16510        resetResolvedDrawablesInternal();
16511    }
16512
16513    void resetResolvedDrawablesInternal() {
16514        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16515    }
16516
16517    /**
16518     * If your view subclass is displaying its own Drawable objects, it should
16519     * override this function and return true for any Drawable it is
16520     * displaying.  This allows animations for those drawables to be
16521     * scheduled.
16522     *
16523     * <p>Be sure to call through to the super class when overriding this
16524     * function.
16525     *
16526     * @param who The Drawable to verify.  Return true if it is one you are
16527     *            displaying, else return the result of calling through to the
16528     *            super class.
16529     *
16530     * @return boolean If true than the Drawable is being displayed in the
16531     *         view; else false and it is not allowed to animate.
16532     *
16533     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16534     * @see #drawableStateChanged()
16535     */
16536    @CallSuper
16537    protected boolean verifyDrawable(Drawable who) {
16538        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16539                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16540    }
16541
16542    /**
16543     * This function is called whenever the state of the view changes in such
16544     * a way that it impacts the state of drawables being shown.
16545     * <p>
16546     * If the View has a StateListAnimator, it will also be called to run necessary state
16547     * change animations.
16548     * <p>
16549     * Be sure to call through to the superclass when overriding this function.
16550     *
16551     * @see Drawable#setState(int[])
16552     */
16553    @CallSuper
16554    protected void drawableStateChanged() {
16555        final int[] state = getDrawableState();
16556
16557        final Drawable bg = mBackground;
16558        if (bg != null && bg.isStateful()) {
16559            bg.setState(state);
16560        }
16561
16562        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16563        if (fg != null && fg.isStateful()) {
16564            fg.setState(state);
16565        }
16566
16567        if (mScrollCache != null) {
16568            final Drawable scrollBar = mScrollCache.scrollBar;
16569            if (scrollBar != null && scrollBar.isStateful()) {
16570                scrollBar.setState(state);
16571            }
16572        }
16573
16574        if (mStateListAnimator != null) {
16575            mStateListAnimator.setState(state);
16576        }
16577    }
16578
16579    /**
16580     * This function is called whenever the view hotspot changes and needs to
16581     * be propagated to drawables or child views managed by the view.
16582     * <p>
16583     * Dispatching to child views is handled by
16584     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16585     * <p>
16586     * Be sure to call through to the superclass when overriding this function.
16587     *
16588     * @param x hotspot x coordinate
16589     * @param y hotspot y coordinate
16590     */
16591    @CallSuper
16592    public void drawableHotspotChanged(float x, float y) {
16593        if (mBackground != null) {
16594            mBackground.setHotspot(x, y);
16595        }
16596        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16597            mForegroundInfo.mDrawable.setHotspot(x, y);
16598        }
16599
16600        dispatchDrawableHotspotChanged(x, y);
16601    }
16602
16603    /**
16604     * Dispatches drawableHotspotChanged to all of this View's children.
16605     *
16606     * @param x hotspot x coordinate
16607     * @param y hotspot y coordinate
16608     * @see #drawableHotspotChanged(float, float)
16609     */
16610    public void dispatchDrawableHotspotChanged(float x, float y) {
16611    }
16612
16613    /**
16614     * Call this to force a view to update its drawable state. This will cause
16615     * drawableStateChanged to be called on this view. Views that are interested
16616     * in the new state should call getDrawableState.
16617     *
16618     * @see #drawableStateChanged
16619     * @see #getDrawableState
16620     */
16621    public void refreshDrawableState() {
16622        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16623        drawableStateChanged();
16624
16625        ViewParent parent = mParent;
16626        if (parent != null) {
16627            parent.childDrawableStateChanged(this);
16628        }
16629    }
16630
16631    /**
16632     * Return an array of resource IDs of the drawable states representing the
16633     * current state of the view.
16634     *
16635     * @return The current drawable state
16636     *
16637     * @see Drawable#setState(int[])
16638     * @see #drawableStateChanged()
16639     * @see #onCreateDrawableState(int)
16640     */
16641    public final int[] getDrawableState() {
16642        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16643            return mDrawableState;
16644        } else {
16645            mDrawableState = onCreateDrawableState(0);
16646            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16647            return mDrawableState;
16648        }
16649    }
16650
16651    /**
16652     * Generate the new {@link android.graphics.drawable.Drawable} state for
16653     * this view. This is called by the view
16654     * system when the cached Drawable state is determined to be invalid.  To
16655     * retrieve the current state, you should use {@link #getDrawableState}.
16656     *
16657     * @param extraSpace if non-zero, this is the number of extra entries you
16658     * would like in the returned array in which you can place your own
16659     * states.
16660     *
16661     * @return Returns an array holding the current {@link Drawable} state of
16662     * the view.
16663     *
16664     * @see #mergeDrawableStates(int[], int[])
16665     */
16666    protected int[] onCreateDrawableState(int extraSpace) {
16667        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16668                mParent instanceof View) {
16669            return ((View) mParent).onCreateDrawableState(extraSpace);
16670        }
16671
16672        int[] drawableState;
16673
16674        int privateFlags = mPrivateFlags;
16675
16676        int viewStateIndex = 0;
16677        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16678        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16679        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16680        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16681        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16682        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16683        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16684                HardwareRenderer.isAvailable()) {
16685            // This is set if HW acceleration is requested, even if the current
16686            // process doesn't allow it.  This is just to allow app preview
16687            // windows to better match their app.
16688            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16689        }
16690        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16691
16692        final int privateFlags2 = mPrivateFlags2;
16693        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16694            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16695        }
16696        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16697            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16698        }
16699
16700        drawableState = StateSet.get(viewStateIndex);
16701
16702        //noinspection ConstantIfStatement
16703        if (false) {
16704            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16705            Log.i("View", toString()
16706                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16707                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16708                    + " fo=" + hasFocus()
16709                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16710                    + " wf=" + hasWindowFocus()
16711                    + ": " + Arrays.toString(drawableState));
16712        }
16713
16714        if (extraSpace == 0) {
16715            return drawableState;
16716        }
16717
16718        final int[] fullState;
16719        if (drawableState != null) {
16720            fullState = new int[drawableState.length + extraSpace];
16721            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16722        } else {
16723            fullState = new int[extraSpace];
16724        }
16725
16726        return fullState;
16727    }
16728
16729    /**
16730     * Merge your own state values in <var>additionalState</var> into the base
16731     * state values <var>baseState</var> that were returned by
16732     * {@link #onCreateDrawableState(int)}.
16733     *
16734     * @param baseState The base state values returned by
16735     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16736     * own additional state values.
16737     *
16738     * @param additionalState The additional state values you would like
16739     * added to <var>baseState</var>; this array is not modified.
16740     *
16741     * @return As a convenience, the <var>baseState</var> array you originally
16742     * passed into the function is returned.
16743     *
16744     * @see #onCreateDrawableState(int)
16745     */
16746    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16747        final int N = baseState.length;
16748        int i = N - 1;
16749        while (i >= 0 && baseState[i] == 0) {
16750            i--;
16751        }
16752        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16753        return baseState;
16754    }
16755
16756    /**
16757     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16758     * on all Drawable objects associated with this view.
16759     * <p>
16760     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16761     * attached to this view.
16762     */
16763    public void jumpDrawablesToCurrentState() {
16764        if (mBackground != null) {
16765            mBackground.jumpToCurrentState();
16766        }
16767        if (mStateListAnimator != null) {
16768            mStateListAnimator.jumpToCurrentState();
16769        }
16770        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16771            mForegroundInfo.mDrawable.jumpToCurrentState();
16772        }
16773    }
16774
16775    /**
16776     * Sets the background color for this view.
16777     * @param color the color of the background
16778     */
16779    @RemotableViewMethod
16780    public void setBackgroundColor(@ColorInt int color) {
16781        if (mBackground instanceof ColorDrawable) {
16782            ((ColorDrawable) mBackground.mutate()).setColor(color);
16783            computeOpaqueFlags();
16784            mBackgroundResource = 0;
16785        } else {
16786            setBackground(new ColorDrawable(color));
16787        }
16788    }
16789
16790    /**
16791     * If the view has a ColorDrawable background, returns the color of that
16792     * drawable.
16793     *
16794     * @return The color of the ColorDrawable background, if set, otherwise 0.
16795     */
16796    @ColorInt
16797    public int getBackgroundColor() {
16798        if (mBackground instanceof ColorDrawable) {
16799            return ((ColorDrawable) mBackground).getColor();
16800        }
16801        return 0;
16802    }
16803
16804    /**
16805     * Set the background to a given resource. The resource should refer to
16806     * a Drawable object or 0 to remove the background.
16807     * @param resid The identifier of the resource.
16808     *
16809     * @attr ref android.R.styleable#View_background
16810     */
16811    @RemotableViewMethod
16812    public void setBackgroundResource(@DrawableRes int resid) {
16813        if (resid != 0 && resid == mBackgroundResource) {
16814            return;
16815        }
16816
16817        Drawable d = null;
16818        if (resid != 0) {
16819            d = mContext.getDrawable(resid);
16820        }
16821        setBackground(d);
16822
16823        mBackgroundResource = resid;
16824    }
16825
16826    /**
16827     * Set the background to a given Drawable, or remove the background. If the
16828     * background has padding, this View's padding is set to the background's
16829     * padding. However, when a background is removed, this View's padding isn't
16830     * touched. If setting the padding is desired, please use
16831     * {@link #setPadding(int, int, int, int)}.
16832     *
16833     * @param background The Drawable to use as the background, or null to remove the
16834     *        background
16835     */
16836    public void setBackground(Drawable background) {
16837        //noinspection deprecation
16838        setBackgroundDrawable(background);
16839    }
16840
16841    /**
16842     * @deprecated use {@link #setBackground(Drawable)} instead
16843     */
16844    @Deprecated
16845    public void setBackgroundDrawable(Drawable background) {
16846        computeOpaqueFlags();
16847
16848        if (background == mBackground) {
16849            return;
16850        }
16851
16852        boolean requestLayout = false;
16853
16854        mBackgroundResource = 0;
16855
16856        /*
16857         * Regardless of whether we're setting a new background or not, we want
16858         * to clear the previous drawable.
16859         */
16860        if (mBackground != null) {
16861            mBackground.setCallback(null);
16862            unscheduleDrawable(mBackground);
16863        }
16864
16865        if (background != null) {
16866            Rect padding = sThreadLocal.get();
16867            if (padding == null) {
16868                padding = new Rect();
16869                sThreadLocal.set(padding);
16870            }
16871            resetResolvedDrawablesInternal();
16872            background.setLayoutDirection(getLayoutDirection());
16873            if (background.getPadding(padding)) {
16874                resetResolvedPaddingInternal();
16875                switch (background.getLayoutDirection()) {
16876                    case LAYOUT_DIRECTION_RTL:
16877                        mUserPaddingLeftInitial = padding.right;
16878                        mUserPaddingRightInitial = padding.left;
16879                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16880                        break;
16881                    case LAYOUT_DIRECTION_LTR:
16882                    default:
16883                        mUserPaddingLeftInitial = padding.left;
16884                        mUserPaddingRightInitial = padding.right;
16885                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16886                }
16887                mLeftPaddingDefined = false;
16888                mRightPaddingDefined = false;
16889            }
16890
16891            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16892            // if it has a different minimum size, we should layout again
16893            if (mBackground == null
16894                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16895                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16896                requestLayout = true;
16897            }
16898
16899            background.setCallback(this);
16900            if (background.isStateful()) {
16901                background.setState(getDrawableState());
16902            }
16903            background.setVisible(getVisibility() == VISIBLE, false);
16904            mBackground = background;
16905
16906            applyBackgroundTint();
16907
16908            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16909                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16910                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16911                requestLayout = true;
16912            }
16913        } else {
16914            /* Remove the background */
16915            mBackground = null;
16916
16917            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16918                /*
16919                 * This view ONLY drew the background before and we're removing
16920                 * the background, so now it won't draw anything
16921                 * (hence we SKIP_DRAW)
16922                 */
16923                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16924                mPrivateFlags |= PFLAG_SKIP_DRAW;
16925            }
16926
16927            /*
16928             * When the background is set, we try to apply its padding to this
16929             * View. When the background is removed, we don't touch this View's
16930             * padding. This is noted in the Javadocs. Hence, we don't need to
16931             * requestLayout(), the invalidate() below is sufficient.
16932             */
16933
16934            // The old background's minimum size could have affected this
16935            // View's layout, so let's requestLayout
16936            requestLayout = true;
16937        }
16938
16939        computeOpaqueFlags();
16940
16941        if (requestLayout) {
16942            requestLayout();
16943        }
16944
16945        mBackgroundSizeChanged = true;
16946        invalidate(true);
16947    }
16948
16949    /**
16950     * Gets the background drawable
16951     *
16952     * @return The drawable used as the background for this view, if any.
16953     *
16954     * @see #setBackground(Drawable)
16955     *
16956     * @attr ref android.R.styleable#View_background
16957     */
16958    public Drawable getBackground() {
16959        return mBackground;
16960    }
16961
16962    /**
16963     * Applies a tint to the background drawable. Does not modify the current tint
16964     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16965     * <p>
16966     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16967     * mutate the drawable and apply the specified tint and tint mode using
16968     * {@link Drawable#setTintList(ColorStateList)}.
16969     *
16970     * @param tint the tint to apply, may be {@code null} to clear tint
16971     *
16972     * @attr ref android.R.styleable#View_backgroundTint
16973     * @see #getBackgroundTintList()
16974     * @see Drawable#setTintList(ColorStateList)
16975     */
16976    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16977        if (mBackgroundTint == null) {
16978            mBackgroundTint = new TintInfo();
16979        }
16980        mBackgroundTint.mTintList = tint;
16981        mBackgroundTint.mHasTintList = true;
16982
16983        applyBackgroundTint();
16984    }
16985
16986    /**
16987     * Return the tint applied to the background drawable, if specified.
16988     *
16989     * @return the tint applied to the background drawable
16990     * @attr ref android.R.styleable#View_backgroundTint
16991     * @see #setBackgroundTintList(ColorStateList)
16992     */
16993    @Nullable
16994    public ColorStateList getBackgroundTintList() {
16995        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16996    }
16997
16998    /**
16999     * Specifies the blending mode used to apply the tint specified by
17000     * {@link #setBackgroundTintList(ColorStateList)}} to the background
17001     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17002     *
17003     * @param tintMode the blending mode used to apply the tint, may be
17004     *                 {@code null} to clear tint
17005     * @attr ref android.R.styleable#View_backgroundTintMode
17006     * @see #getBackgroundTintMode()
17007     * @see Drawable#setTintMode(PorterDuff.Mode)
17008     */
17009    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17010        if (mBackgroundTint == null) {
17011            mBackgroundTint = new TintInfo();
17012        }
17013        mBackgroundTint.mTintMode = tintMode;
17014        mBackgroundTint.mHasTintMode = true;
17015
17016        applyBackgroundTint();
17017    }
17018
17019    /**
17020     * Return the blending mode used to apply the tint to the background
17021     * drawable, if specified.
17022     *
17023     * @return the blending mode used to apply the tint to the background
17024     *         drawable
17025     * @attr ref android.R.styleable#View_backgroundTintMode
17026     * @see #setBackgroundTintMode(PorterDuff.Mode)
17027     */
17028    @Nullable
17029    public PorterDuff.Mode getBackgroundTintMode() {
17030        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
17031    }
17032
17033    private void applyBackgroundTint() {
17034        if (mBackground != null && mBackgroundTint != null) {
17035            final TintInfo tintInfo = mBackgroundTint;
17036            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17037                mBackground = mBackground.mutate();
17038
17039                if (tintInfo.mHasTintList) {
17040                    mBackground.setTintList(tintInfo.mTintList);
17041                }
17042
17043                if (tintInfo.mHasTintMode) {
17044                    mBackground.setTintMode(tintInfo.mTintMode);
17045                }
17046
17047                // The drawable (or one of its children) may not have been
17048                // stateful before applying the tint, so let's try again.
17049                if (mBackground.isStateful()) {
17050                    mBackground.setState(getDrawableState());
17051                }
17052            }
17053        }
17054    }
17055
17056    /**
17057     * Returns the drawable used as the foreground of this View. The
17058     * foreground drawable, if non-null, is always drawn on top of the view's content.
17059     *
17060     * @return a Drawable or null if no foreground was set
17061     *
17062     * @see #onDrawForeground(Canvas)
17063     */
17064    public Drawable getForeground() {
17065        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17066    }
17067
17068    /**
17069     * Supply a Drawable that is to be rendered on top of all of the content in the view.
17070     *
17071     * @param foreground the Drawable to be drawn on top of the children
17072     *
17073     * @attr ref android.R.styleable#View_foreground
17074     */
17075    public void setForeground(Drawable foreground) {
17076        if (mForegroundInfo == null) {
17077            if (foreground == null) {
17078                // Nothing to do.
17079                return;
17080            }
17081            mForegroundInfo = new ForegroundInfo();
17082        }
17083
17084        if (foreground == mForegroundInfo.mDrawable) {
17085            // Nothing to do
17086            return;
17087        }
17088
17089        if (mForegroundInfo.mDrawable != null) {
17090            mForegroundInfo.mDrawable.setCallback(null);
17091            unscheduleDrawable(mForegroundInfo.mDrawable);
17092        }
17093
17094        mForegroundInfo.mDrawable = foreground;
17095        mForegroundInfo.mBoundsChanged = true;
17096        if (foreground != null) {
17097            setWillNotDraw(false);
17098            foreground.setCallback(this);
17099            foreground.setLayoutDirection(getLayoutDirection());
17100            if (foreground.isStateful()) {
17101                foreground.setState(getDrawableState());
17102            }
17103            applyForegroundTint();
17104        }
17105        requestLayout();
17106        invalidate();
17107    }
17108
17109    /**
17110     * Magic bit used to support features of framework-internal window decor implementation details.
17111     * This used to live exclusively in FrameLayout.
17112     *
17113     * @return true if the foreground should draw inside the padding region or false
17114     *         if it should draw inset by the view's padding
17115     * @hide internal use only; only used by FrameLayout and internal screen layouts.
17116     */
17117    public boolean isForegroundInsidePadding() {
17118        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
17119    }
17120
17121    /**
17122     * Describes how the foreground is positioned.
17123     *
17124     * @return foreground gravity.
17125     *
17126     * @see #setForegroundGravity(int)
17127     *
17128     * @attr ref android.R.styleable#View_foregroundGravity
17129     */
17130    public int getForegroundGravity() {
17131        return mForegroundInfo != null ? mForegroundInfo.mGravity
17132                : Gravity.START | Gravity.TOP;
17133    }
17134
17135    /**
17136     * Describes how the foreground is positioned. Defaults to START and TOP.
17137     *
17138     * @param gravity see {@link android.view.Gravity}
17139     *
17140     * @see #getForegroundGravity()
17141     *
17142     * @attr ref android.R.styleable#View_foregroundGravity
17143     */
17144    public void setForegroundGravity(int gravity) {
17145        if (mForegroundInfo == null) {
17146            mForegroundInfo = new ForegroundInfo();
17147        }
17148
17149        if (mForegroundInfo.mGravity != gravity) {
17150            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
17151                gravity |= Gravity.START;
17152            }
17153
17154            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
17155                gravity |= Gravity.TOP;
17156            }
17157
17158            mForegroundInfo.mGravity = gravity;
17159            requestLayout();
17160        }
17161    }
17162
17163    /**
17164     * Applies a tint to the foreground drawable. Does not modify the current tint
17165     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17166     * <p>
17167     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
17168     * mutate the drawable and apply the specified tint and tint mode using
17169     * {@link Drawable#setTintList(ColorStateList)}.
17170     *
17171     * @param tint the tint to apply, may be {@code null} to clear tint
17172     *
17173     * @attr ref android.R.styleable#View_foregroundTint
17174     * @see #getForegroundTintList()
17175     * @see Drawable#setTintList(ColorStateList)
17176     */
17177    public void setForegroundTintList(@Nullable ColorStateList tint) {
17178        if (mForegroundInfo == null) {
17179            mForegroundInfo = new ForegroundInfo();
17180        }
17181        if (mForegroundInfo.mTintInfo == null) {
17182            mForegroundInfo.mTintInfo = new TintInfo();
17183        }
17184        mForegroundInfo.mTintInfo.mTintList = tint;
17185        mForegroundInfo.mTintInfo.mHasTintList = true;
17186
17187        applyForegroundTint();
17188    }
17189
17190    /**
17191     * Return the tint applied to the foreground drawable, if specified.
17192     *
17193     * @return the tint applied to the foreground drawable
17194     * @attr ref android.R.styleable#View_foregroundTint
17195     * @see #setForegroundTintList(ColorStateList)
17196     */
17197    @Nullable
17198    public ColorStateList getForegroundTintList() {
17199        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17200                ? mForegroundInfo.mTintInfo.mTintList : null;
17201    }
17202
17203    /**
17204     * Specifies the blending mode used to apply the tint specified by
17205     * {@link #setForegroundTintList(ColorStateList)}} to the background
17206     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17207     *
17208     * @param tintMode the blending mode used to apply the tint, may be
17209     *                 {@code null} to clear tint
17210     * @attr ref android.R.styleable#View_foregroundTintMode
17211     * @see #getForegroundTintMode()
17212     * @see Drawable#setTintMode(PorterDuff.Mode)
17213     */
17214    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17215        if (mBackgroundTint == null) {
17216            mBackgroundTint = new TintInfo();
17217        }
17218        mBackgroundTint.mTintMode = tintMode;
17219        mBackgroundTint.mHasTintMode = true;
17220
17221        applyBackgroundTint();
17222    }
17223
17224    /**
17225     * Return the blending mode used to apply the tint to the foreground
17226     * drawable, if specified.
17227     *
17228     * @return the blending mode used to apply the tint to the foreground
17229     *         drawable
17230     * @attr ref android.R.styleable#View_foregroundTintMode
17231     * @see #setBackgroundTintMode(PorterDuff.Mode)
17232     */
17233    @Nullable
17234    public PorterDuff.Mode getForegroundTintMode() {
17235        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17236                ? mForegroundInfo.mTintInfo.mTintMode : null;
17237    }
17238
17239    private void applyForegroundTint() {
17240        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17241                && mForegroundInfo.mTintInfo != null) {
17242            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17243            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17244                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17245
17246                if (tintInfo.mHasTintList) {
17247                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17248                }
17249
17250                if (tintInfo.mHasTintMode) {
17251                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17252                }
17253
17254                // The drawable (or one of its children) may not have been
17255                // stateful before applying the tint, so let's try again.
17256                if (mForegroundInfo.mDrawable.isStateful()) {
17257                    mForegroundInfo.mDrawable.setState(getDrawableState());
17258                }
17259            }
17260        }
17261    }
17262
17263    /**
17264     * Draw any foreground content for this view.
17265     *
17266     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17267     * drawable or other view-specific decorations. The foreground is drawn on top of the
17268     * primary view content.</p>
17269     *
17270     * @param canvas canvas to draw into
17271     */
17272    public void onDrawForeground(Canvas canvas) {
17273        onDrawScrollBars(canvas);
17274
17275        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17276        if (foreground != null) {
17277            if (mForegroundInfo.mBoundsChanged) {
17278                mForegroundInfo.mBoundsChanged = false;
17279                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17280                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17281
17282                if (mForegroundInfo.mInsidePadding) {
17283                    selfBounds.set(0, 0, getWidth(), getHeight());
17284                } else {
17285                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17286                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17287                }
17288
17289                final int ld = getLayoutDirection();
17290                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17291                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17292                foreground.setBounds(overlayBounds);
17293            }
17294
17295            foreground.draw(canvas);
17296        }
17297    }
17298
17299    /**
17300     * Sets the padding. The view may add on the space required to display
17301     * the scrollbars, depending on the style and visibility of the scrollbars.
17302     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17303     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17304     * from the values set in this call.
17305     *
17306     * @attr ref android.R.styleable#View_padding
17307     * @attr ref android.R.styleable#View_paddingBottom
17308     * @attr ref android.R.styleable#View_paddingLeft
17309     * @attr ref android.R.styleable#View_paddingRight
17310     * @attr ref android.R.styleable#View_paddingTop
17311     * @param left the left padding in pixels
17312     * @param top the top padding in pixels
17313     * @param right the right padding in pixels
17314     * @param bottom the bottom padding in pixels
17315     */
17316    public void setPadding(int left, int top, int right, int bottom) {
17317        resetResolvedPaddingInternal();
17318
17319        mUserPaddingStart = UNDEFINED_PADDING;
17320        mUserPaddingEnd = UNDEFINED_PADDING;
17321
17322        mUserPaddingLeftInitial = left;
17323        mUserPaddingRightInitial = right;
17324
17325        mLeftPaddingDefined = true;
17326        mRightPaddingDefined = true;
17327
17328        internalSetPadding(left, top, right, bottom);
17329    }
17330
17331    /**
17332     * @hide
17333     */
17334    protected void internalSetPadding(int left, int top, int right, int bottom) {
17335        mUserPaddingLeft = left;
17336        mUserPaddingRight = right;
17337        mUserPaddingBottom = bottom;
17338
17339        final int viewFlags = mViewFlags;
17340        boolean changed = false;
17341
17342        // Common case is there are no scroll bars.
17343        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17344            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17345                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17346                        ? 0 : getVerticalScrollbarWidth();
17347                switch (mVerticalScrollbarPosition) {
17348                    case SCROLLBAR_POSITION_DEFAULT:
17349                        if (isLayoutRtl()) {
17350                            left += offset;
17351                        } else {
17352                            right += offset;
17353                        }
17354                        break;
17355                    case SCROLLBAR_POSITION_RIGHT:
17356                        right += offset;
17357                        break;
17358                    case SCROLLBAR_POSITION_LEFT:
17359                        left += offset;
17360                        break;
17361                }
17362            }
17363            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17364                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17365                        ? 0 : getHorizontalScrollbarHeight();
17366            }
17367        }
17368
17369        if (mPaddingLeft != left) {
17370            changed = true;
17371            mPaddingLeft = left;
17372        }
17373        if (mPaddingTop != top) {
17374            changed = true;
17375            mPaddingTop = top;
17376        }
17377        if (mPaddingRight != right) {
17378            changed = true;
17379            mPaddingRight = right;
17380        }
17381        if (mPaddingBottom != bottom) {
17382            changed = true;
17383            mPaddingBottom = bottom;
17384        }
17385
17386        if (changed) {
17387            requestLayout();
17388            invalidateOutline();
17389        }
17390    }
17391
17392    /**
17393     * Sets the relative padding. The view may add on the space required to display
17394     * the scrollbars, depending on the style and visibility of the scrollbars.
17395     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17396     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17397     * from the values set in this call.
17398     *
17399     * @attr ref android.R.styleable#View_padding
17400     * @attr ref android.R.styleable#View_paddingBottom
17401     * @attr ref android.R.styleable#View_paddingStart
17402     * @attr ref android.R.styleable#View_paddingEnd
17403     * @attr ref android.R.styleable#View_paddingTop
17404     * @param start the start padding in pixels
17405     * @param top the top padding in pixels
17406     * @param end the end padding in pixels
17407     * @param bottom the bottom padding in pixels
17408     */
17409    public void setPaddingRelative(int start, int top, int end, int bottom) {
17410        resetResolvedPaddingInternal();
17411
17412        mUserPaddingStart = start;
17413        mUserPaddingEnd = end;
17414        mLeftPaddingDefined = true;
17415        mRightPaddingDefined = true;
17416
17417        switch(getLayoutDirection()) {
17418            case LAYOUT_DIRECTION_RTL:
17419                mUserPaddingLeftInitial = end;
17420                mUserPaddingRightInitial = start;
17421                internalSetPadding(end, top, start, bottom);
17422                break;
17423            case LAYOUT_DIRECTION_LTR:
17424            default:
17425                mUserPaddingLeftInitial = start;
17426                mUserPaddingRightInitial = end;
17427                internalSetPadding(start, top, end, bottom);
17428        }
17429    }
17430
17431    /**
17432     * Returns the top padding of this view.
17433     *
17434     * @return the top padding in pixels
17435     */
17436    public int getPaddingTop() {
17437        return mPaddingTop;
17438    }
17439
17440    /**
17441     * Returns the bottom padding of this view. If there are inset and enabled
17442     * scrollbars, this value may include the space required to display the
17443     * scrollbars as well.
17444     *
17445     * @return the bottom padding in pixels
17446     */
17447    public int getPaddingBottom() {
17448        return mPaddingBottom;
17449    }
17450
17451    /**
17452     * Returns the left padding of this view. If there are inset and enabled
17453     * scrollbars, this value may include the space required to display the
17454     * scrollbars as well.
17455     *
17456     * @return the left padding in pixels
17457     */
17458    public int getPaddingLeft() {
17459        if (!isPaddingResolved()) {
17460            resolvePadding();
17461        }
17462        return mPaddingLeft;
17463    }
17464
17465    /**
17466     * Returns the start padding of this view depending on its resolved layout direction.
17467     * If there are inset and enabled scrollbars, this value may include the space
17468     * required to display the scrollbars as well.
17469     *
17470     * @return the start padding in pixels
17471     */
17472    public int getPaddingStart() {
17473        if (!isPaddingResolved()) {
17474            resolvePadding();
17475        }
17476        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17477                mPaddingRight : mPaddingLeft;
17478    }
17479
17480    /**
17481     * Returns the right padding of this view. If there are inset and enabled
17482     * scrollbars, this value may include the space required to display the
17483     * scrollbars as well.
17484     *
17485     * @return the right padding in pixels
17486     */
17487    public int getPaddingRight() {
17488        if (!isPaddingResolved()) {
17489            resolvePadding();
17490        }
17491        return mPaddingRight;
17492    }
17493
17494    /**
17495     * Returns the end padding of this view depending on its resolved layout direction.
17496     * If there are inset and enabled scrollbars, this value may include the space
17497     * required to display the scrollbars as well.
17498     *
17499     * @return the end padding in pixels
17500     */
17501    public int getPaddingEnd() {
17502        if (!isPaddingResolved()) {
17503            resolvePadding();
17504        }
17505        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17506                mPaddingLeft : mPaddingRight;
17507    }
17508
17509    /**
17510     * Return if the padding has been set through relative values
17511     * {@link #setPaddingRelative(int, int, int, int)} or through
17512     * @attr ref android.R.styleable#View_paddingStart or
17513     * @attr ref android.R.styleable#View_paddingEnd
17514     *
17515     * @return true if the padding is relative or false if it is not.
17516     */
17517    public boolean isPaddingRelative() {
17518        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17519    }
17520
17521    Insets computeOpticalInsets() {
17522        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17523    }
17524
17525    /**
17526     * @hide
17527     */
17528    public void resetPaddingToInitialValues() {
17529        if (isRtlCompatibilityMode()) {
17530            mPaddingLeft = mUserPaddingLeftInitial;
17531            mPaddingRight = mUserPaddingRightInitial;
17532            return;
17533        }
17534        if (isLayoutRtl()) {
17535            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17536            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17537        } else {
17538            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17539            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17540        }
17541    }
17542
17543    /**
17544     * @hide
17545     */
17546    public Insets getOpticalInsets() {
17547        if (mLayoutInsets == null) {
17548            mLayoutInsets = computeOpticalInsets();
17549        }
17550        return mLayoutInsets;
17551    }
17552
17553    /**
17554     * Set this view's optical insets.
17555     *
17556     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17557     * property. Views that compute their own optical insets should call it as part of measurement.
17558     * This method does not request layout. If you are setting optical insets outside of
17559     * measure/layout itself you will want to call requestLayout() yourself.
17560     * </p>
17561     * @hide
17562     */
17563    public void setOpticalInsets(Insets insets) {
17564        mLayoutInsets = insets;
17565    }
17566
17567    /**
17568     * Changes the selection state of this view. A view can be selected or not.
17569     * Note that selection is not the same as focus. Views are typically
17570     * selected in the context of an AdapterView like ListView or GridView;
17571     * the selected view is the view that is highlighted.
17572     *
17573     * @param selected true if the view must be selected, false otherwise
17574     */
17575    public void setSelected(boolean selected) {
17576        //noinspection DoubleNegation
17577        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17578            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17579            if (!selected) resetPressedState();
17580            invalidate(true);
17581            refreshDrawableState();
17582            dispatchSetSelected(selected);
17583            if (selected) {
17584                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17585            } else {
17586                notifyViewAccessibilityStateChangedIfNeeded(
17587                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17588            }
17589        }
17590    }
17591
17592    /**
17593     * Dispatch setSelected to all of this View's children.
17594     *
17595     * @see #setSelected(boolean)
17596     *
17597     * @param selected The new selected state
17598     */
17599    protected void dispatchSetSelected(boolean selected) {
17600    }
17601
17602    /**
17603     * Indicates the selection state of this view.
17604     *
17605     * @return true if the view is selected, false otherwise
17606     */
17607    @ViewDebug.ExportedProperty
17608    public boolean isSelected() {
17609        return (mPrivateFlags & PFLAG_SELECTED) != 0;
17610    }
17611
17612    /**
17613     * Changes the activated state of this view. A view can be activated or not.
17614     * Note that activation is not the same as selection.  Selection is
17615     * a transient property, representing the view (hierarchy) the user is
17616     * currently interacting with.  Activation is a longer-term state that the
17617     * user can move views in and out of.  For example, in a list view with
17618     * single or multiple selection enabled, the views in the current selection
17619     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
17620     * here.)  The activated state is propagated down to children of the view it
17621     * is set on.
17622     *
17623     * @param activated true if the view must be activated, false otherwise
17624     */
17625    public void setActivated(boolean activated) {
17626        //noinspection DoubleNegation
17627        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
17628            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
17629            invalidate(true);
17630            refreshDrawableState();
17631            dispatchSetActivated(activated);
17632        }
17633    }
17634
17635    /**
17636     * Dispatch setActivated to all of this View's children.
17637     *
17638     * @see #setActivated(boolean)
17639     *
17640     * @param activated The new activated state
17641     */
17642    protected void dispatchSetActivated(boolean activated) {
17643    }
17644
17645    /**
17646     * Indicates the activation state of this view.
17647     *
17648     * @return true if the view is activated, false otherwise
17649     */
17650    @ViewDebug.ExportedProperty
17651    public boolean isActivated() {
17652        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
17653    }
17654
17655    /**
17656     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
17657     * observer can be used to get notifications when global events, like
17658     * layout, happen.
17659     *
17660     * The returned ViewTreeObserver observer is not guaranteed to remain
17661     * valid for the lifetime of this View. If the caller of this method keeps
17662     * a long-lived reference to ViewTreeObserver, it should always check for
17663     * the return value of {@link ViewTreeObserver#isAlive()}.
17664     *
17665     * @return The ViewTreeObserver for this view's hierarchy.
17666     */
17667    public ViewTreeObserver getViewTreeObserver() {
17668        if (mAttachInfo != null) {
17669            return mAttachInfo.mTreeObserver;
17670        }
17671        if (mFloatingTreeObserver == null) {
17672            mFloatingTreeObserver = new ViewTreeObserver();
17673        }
17674        return mFloatingTreeObserver;
17675    }
17676
17677    /**
17678     * <p>Finds the topmost view in the current view hierarchy.</p>
17679     *
17680     * @return the topmost view containing this view
17681     */
17682    public View getRootView() {
17683        if (mAttachInfo != null) {
17684            final View v = mAttachInfo.mRootView;
17685            if (v != null) {
17686                return v;
17687            }
17688        }
17689
17690        View parent = this;
17691
17692        while (parent.mParent != null && parent.mParent instanceof View) {
17693            parent = (View) parent.mParent;
17694        }
17695
17696        return parent;
17697    }
17698
17699    /**
17700     * Transforms a motion event from view-local coordinates to on-screen
17701     * coordinates.
17702     *
17703     * @param ev the view-local motion event
17704     * @return false if the transformation could not be applied
17705     * @hide
17706     */
17707    public boolean toGlobalMotionEvent(MotionEvent ev) {
17708        final AttachInfo info = mAttachInfo;
17709        if (info == null) {
17710            return false;
17711        }
17712
17713        final Matrix m = info.mTmpMatrix;
17714        m.set(Matrix.IDENTITY_MATRIX);
17715        transformMatrixToGlobal(m);
17716        ev.transform(m);
17717        return true;
17718    }
17719
17720    /**
17721     * Transforms a motion event from on-screen coordinates to view-local
17722     * coordinates.
17723     *
17724     * @param ev the on-screen motion event
17725     * @return false if the transformation could not be applied
17726     * @hide
17727     */
17728    public boolean toLocalMotionEvent(MotionEvent ev) {
17729        final AttachInfo info = mAttachInfo;
17730        if (info == null) {
17731            return false;
17732        }
17733
17734        final Matrix m = info.mTmpMatrix;
17735        m.set(Matrix.IDENTITY_MATRIX);
17736        transformMatrixToLocal(m);
17737        ev.transform(m);
17738        return true;
17739    }
17740
17741    /**
17742     * Modifies the input matrix such that it maps view-local coordinates to
17743     * on-screen coordinates.
17744     *
17745     * @param m input matrix to modify
17746     * @hide
17747     */
17748    public void transformMatrixToGlobal(Matrix m) {
17749        final ViewParent parent = mParent;
17750        if (parent instanceof View) {
17751            final View vp = (View) parent;
17752            vp.transformMatrixToGlobal(m);
17753            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
17754        } else if (parent instanceof ViewRootImpl) {
17755            final ViewRootImpl vr = (ViewRootImpl) parent;
17756            vr.transformMatrixToGlobal(m);
17757            m.preTranslate(0, -vr.mCurScrollY);
17758        }
17759
17760        m.preTranslate(mLeft, mTop);
17761
17762        if (!hasIdentityMatrix()) {
17763            m.preConcat(getMatrix());
17764        }
17765    }
17766
17767    /**
17768     * Modifies the input matrix such that it maps on-screen coordinates to
17769     * view-local coordinates.
17770     *
17771     * @param m input matrix to modify
17772     * @hide
17773     */
17774    public void transformMatrixToLocal(Matrix m) {
17775        final ViewParent parent = mParent;
17776        if (parent instanceof View) {
17777            final View vp = (View) parent;
17778            vp.transformMatrixToLocal(m);
17779            m.postTranslate(vp.mScrollX, vp.mScrollY);
17780        } else if (parent instanceof ViewRootImpl) {
17781            final ViewRootImpl vr = (ViewRootImpl) parent;
17782            vr.transformMatrixToLocal(m);
17783            m.postTranslate(0, vr.mCurScrollY);
17784        }
17785
17786        m.postTranslate(-mLeft, -mTop);
17787
17788        if (!hasIdentityMatrix()) {
17789            m.postConcat(getInverseMatrix());
17790        }
17791    }
17792
17793    /**
17794     * @hide
17795     */
17796    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17797            @ViewDebug.IntToString(from = 0, to = "x"),
17798            @ViewDebug.IntToString(from = 1, to = "y")
17799    })
17800    public int[] getLocationOnScreen() {
17801        int[] location = new int[2];
17802        getLocationOnScreen(location);
17803        return location;
17804    }
17805
17806    /**
17807     * <p>Computes the coordinates of this view on the screen. The argument
17808     * must be an array of two integers. After the method returns, the array
17809     * contains the x and y location in that order.</p>
17810     *
17811     * @param location an array of two integers in which to hold the coordinates
17812     */
17813    public void getLocationOnScreen(@Size(2) int[] location) {
17814        getLocationInWindow(location);
17815
17816        final AttachInfo info = mAttachInfo;
17817        if (info != null) {
17818            location[0] += info.mWindowLeft;
17819            location[1] += info.mWindowTop;
17820        }
17821    }
17822
17823    /**
17824     * <p>Computes the coordinates of this view in its window. The argument
17825     * must be an array of two integers. After the method returns, the array
17826     * contains the x and y location in that order.</p>
17827     *
17828     * @param location an array of two integers in which to hold the coordinates
17829     */
17830    public void getLocationInWindow(@Size(2) int[] location) {
17831        if (location == null || location.length < 2) {
17832            throw new IllegalArgumentException("location must be an array of two integers");
17833        }
17834
17835        if (mAttachInfo == null) {
17836            // When the view is not attached to a window, this method does not make sense
17837            location[0] = location[1] = 0;
17838            return;
17839        }
17840
17841        float[] position = mAttachInfo.mTmpTransformLocation;
17842        position[0] = position[1] = 0.0f;
17843
17844        if (!hasIdentityMatrix()) {
17845            getMatrix().mapPoints(position);
17846        }
17847
17848        position[0] += mLeft;
17849        position[1] += mTop;
17850
17851        ViewParent viewParent = mParent;
17852        while (viewParent instanceof View) {
17853            final View view = (View) viewParent;
17854
17855            position[0] -= view.mScrollX;
17856            position[1] -= view.mScrollY;
17857
17858            if (!view.hasIdentityMatrix()) {
17859                view.getMatrix().mapPoints(position);
17860            }
17861
17862            position[0] += view.mLeft;
17863            position[1] += view.mTop;
17864
17865            viewParent = view.mParent;
17866         }
17867
17868        if (viewParent instanceof ViewRootImpl) {
17869            // *cough*
17870            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17871            position[1] -= vr.mCurScrollY;
17872        }
17873
17874        location[0] = (int) (position[0] + 0.5f);
17875        location[1] = (int) (position[1] + 0.5f);
17876    }
17877
17878    /**
17879     * {@hide}
17880     * @param id the id of the view to be found
17881     * @return the view of the specified id, null if cannot be found
17882     */
17883    protected View findViewTraversal(@IdRes int id) {
17884        if (id == mID) {
17885            return this;
17886        }
17887        return null;
17888    }
17889
17890    /**
17891     * {@hide}
17892     * @param tag the tag of the view to be found
17893     * @return the view of specified tag, null if cannot be found
17894     */
17895    protected View findViewWithTagTraversal(Object tag) {
17896        if (tag != null && tag.equals(mTag)) {
17897            return this;
17898        }
17899        return null;
17900    }
17901
17902    /**
17903     * {@hide}
17904     * @param predicate The predicate to evaluate.
17905     * @param childToSkip If not null, ignores this child during the recursive traversal.
17906     * @return The first view that matches the predicate or null.
17907     */
17908    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17909        if (predicate.apply(this)) {
17910            return this;
17911        }
17912        return null;
17913    }
17914
17915    /**
17916     * Look for a child view with the given id.  If this view has the given
17917     * id, return this view.
17918     *
17919     * @param id The id to search for.
17920     * @return The view that has the given id in the hierarchy or null
17921     */
17922    @Nullable
17923    public final View findViewById(@IdRes int id) {
17924        if (id < 0) {
17925            return null;
17926        }
17927        return findViewTraversal(id);
17928    }
17929
17930    /**
17931     * Finds a view by its unuque and stable accessibility id.
17932     *
17933     * @param accessibilityId The searched accessibility id.
17934     * @return The found view.
17935     */
17936    final View findViewByAccessibilityId(int accessibilityId) {
17937        if (accessibilityId < 0) {
17938            return null;
17939        }
17940        return findViewByAccessibilityIdTraversal(accessibilityId);
17941    }
17942
17943    /**
17944     * Performs the traversal to find a view by its unuque and stable accessibility id.
17945     *
17946     * <strong>Note:</strong>This method does not stop at the root namespace
17947     * boundary since the user can touch the screen at an arbitrary location
17948     * potentially crossing the root namespace bounday which will send an
17949     * accessibility event to accessibility services and they should be able
17950     * to obtain the event source. Also accessibility ids are guaranteed to be
17951     * unique in the window.
17952     *
17953     * @param accessibilityId The accessibility id.
17954     * @return The found view.
17955     *
17956     * @hide
17957     */
17958    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17959        if (getAccessibilityViewId() == accessibilityId) {
17960            return this;
17961        }
17962        return null;
17963    }
17964
17965    /**
17966     * Look for a child view with the given tag.  If this view has the given
17967     * tag, return this view.
17968     *
17969     * @param tag The tag to search for, using "tag.equals(getTag())".
17970     * @return The View that has the given tag in the hierarchy or null
17971     */
17972    public final View findViewWithTag(Object tag) {
17973        if (tag == null) {
17974            return null;
17975        }
17976        return findViewWithTagTraversal(tag);
17977    }
17978
17979    /**
17980     * {@hide}
17981     * Look for a child view that matches the specified predicate.
17982     * If this view matches the predicate, return this view.
17983     *
17984     * @param predicate The predicate to evaluate.
17985     * @return The first view that matches the predicate or null.
17986     */
17987    public final View findViewByPredicate(Predicate<View> predicate) {
17988        return findViewByPredicateTraversal(predicate, null);
17989    }
17990
17991    /**
17992     * {@hide}
17993     * Look for a child view that matches the specified predicate,
17994     * starting with the specified view and its descendents and then
17995     * recusively searching the ancestors and siblings of that view
17996     * until this view is reached.
17997     *
17998     * This method is useful in cases where the predicate does not match
17999     * a single unique view (perhaps multiple views use the same id)
18000     * and we are trying to find the view that is "closest" in scope to the
18001     * starting view.
18002     *
18003     * @param start The view to start from.
18004     * @param predicate The predicate to evaluate.
18005     * @return The first view that matches the predicate or null.
18006     */
18007    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
18008        View childToSkip = null;
18009        for (;;) {
18010            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
18011            if (view != null || start == this) {
18012                return view;
18013            }
18014
18015            ViewParent parent = start.getParent();
18016            if (parent == null || !(parent instanceof View)) {
18017                return null;
18018            }
18019
18020            childToSkip = start;
18021            start = (View) parent;
18022        }
18023    }
18024
18025    /**
18026     * Sets the identifier for this view. The identifier does not have to be
18027     * unique in this view's hierarchy. The identifier should be a positive
18028     * number.
18029     *
18030     * @see #NO_ID
18031     * @see #getId()
18032     * @see #findViewById(int)
18033     *
18034     * @param id a number used to identify the view
18035     *
18036     * @attr ref android.R.styleable#View_id
18037     */
18038    public void setId(@IdRes int id) {
18039        mID = id;
18040        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
18041            mID = generateViewId();
18042        }
18043    }
18044
18045    /**
18046     * {@hide}
18047     *
18048     * @param isRoot true if the view belongs to the root namespace, false
18049     *        otherwise
18050     */
18051    public void setIsRootNamespace(boolean isRoot) {
18052        if (isRoot) {
18053            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
18054        } else {
18055            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
18056        }
18057    }
18058
18059    /**
18060     * {@hide}
18061     *
18062     * @return true if the view belongs to the root namespace, false otherwise
18063     */
18064    public boolean isRootNamespace() {
18065        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
18066    }
18067
18068    /**
18069     * Returns this view's identifier.
18070     *
18071     * @return a positive integer used to identify the view or {@link #NO_ID}
18072     *         if the view has no ID
18073     *
18074     * @see #setId(int)
18075     * @see #findViewById(int)
18076     * @attr ref android.R.styleable#View_id
18077     */
18078    @IdRes
18079    @ViewDebug.CapturedViewProperty
18080    public int getId() {
18081        return mID;
18082    }
18083
18084    /**
18085     * Returns this view's tag.
18086     *
18087     * @return the Object stored in this view as a tag, or {@code null} if not
18088     *         set
18089     *
18090     * @see #setTag(Object)
18091     * @see #getTag(int)
18092     */
18093    @ViewDebug.ExportedProperty
18094    public Object getTag() {
18095        return mTag;
18096    }
18097
18098    /**
18099     * Sets the tag associated with this view. A tag can be used to mark
18100     * a view in its hierarchy and does not have to be unique within the
18101     * hierarchy. Tags can also be used to store data within a view without
18102     * resorting to another data structure.
18103     *
18104     * @param tag an Object to tag the view with
18105     *
18106     * @see #getTag()
18107     * @see #setTag(int, Object)
18108     */
18109    public void setTag(final Object tag) {
18110        mTag = tag;
18111    }
18112
18113    /**
18114     * Returns the tag associated with this view and the specified key.
18115     *
18116     * @param key The key identifying the tag
18117     *
18118     * @return the Object stored in this view as a tag, or {@code null} if not
18119     *         set
18120     *
18121     * @see #setTag(int, Object)
18122     * @see #getTag()
18123     */
18124    public Object getTag(int key) {
18125        if (mKeyedTags != null) return mKeyedTags.get(key);
18126        return null;
18127    }
18128
18129    /**
18130     * Sets a tag associated with this view and a key. A tag can be used
18131     * to mark a view in its hierarchy and does not have to be unique within
18132     * the hierarchy. Tags can also be used to store data within a view
18133     * without resorting to another data structure.
18134     *
18135     * The specified key should be an id declared in the resources of the
18136     * application to ensure it is unique (see the <a
18137     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
18138     * Keys identified as belonging to
18139     * the Android framework or not associated with any package will cause
18140     * an {@link IllegalArgumentException} to be thrown.
18141     *
18142     * @param key The key identifying the tag
18143     * @param tag An Object to tag the view with
18144     *
18145     * @throws IllegalArgumentException If they specified key is not valid
18146     *
18147     * @see #setTag(Object)
18148     * @see #getTag(int)
18149     */
18150    public void setTag(int key, final Object tag) {
18151        // If the package id is 0x00 or 0x01, it's either an undefined package
18152        // or a framework id
18153        if ((key >>> 24) < 2) {
18154            throw new IllegalArgumentException("The key must be an application-specific "
18155                    + "resource id.");
18156        }
18157
18158        setKeyedTag(key, tag);
18159    }
18160
18161    /**
18162     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
18163     * framework id.
18164     *
18165     * @hide
18166     */
18167    public void setTagInternal(int key, Object tag) {
18168        if ((key >>> 24) != 0x1) {
18169            throw new IllegalArgumentException("The key must be a framework-specific "
18170                    + "resource id.");
18171        }
18172
18173        setKeyedTag(key, tag);
18174    }
18175
18176    private void setKeyedTag(int key, Object tag) {
18177        if (mKeyedTags == null) {
18178            mKeyedTags = new SparseArray<Object>(2);
18179        }
18180
18181        mKeyedTags.put(key, tag);
18182    }
18183
18184    /**
18185     * Prints information about this view in the log output, with the tag
18186     * {@link #VIEW_LOG_TAG}.
18187     *
18188     * @hide
18189     */
18190    public void debug() {
18191        debug(0);
18192    }
18193
18194    /**
18195     * Prints information about this view in the log output, with the tag
18196     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
18197     * indentation defined by the <code>depth</code>.
18198     *
18199     * @param depth the indentation level
18200     *
18201     * @hide
18202     */
18203    protected void debug(int depth) {
18204        String output = debugIndent(depth - 1);
18205
18206        output += "+ " + this;
18207        int id = getId();
18208        if (id != -1) {
18209            output += " (id=" + id + ")";
18210        }
18211        Object tag = getTag();
18212        if (tag != null) {
18213            output += " (tag=" + tag + ")";
18214        }
18215        Log.d(VIEW_LOG_TAG, output);
18216
18217        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
18218            output = debugIndent(depth) + " FOCUSED";
18219            Log.d(VIEW_LOG_TAG, output);
18220        }
18221
18222        output = debugIndent(depth);
18223        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
18224                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
18225                + "} ";
18226        Log.d(VIEW_LOG_TAG, output);
18227
18228        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
18229                || mPaddingBottom != 0) {
18230            output = debugIndent(depth);
18231            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
18232                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
18233            Log.d(VIEW_LOG_TAG, output);
18234        }
18235
18236        output = debugIndent(depth);
18237        output += "mMeasureWidth=" + mMeasuredWidth +
18238                " mMeasureHeight=" + mMeasuredHeight;
18239        Log.d(VIEW_LOG_TAG, output);
18240
18241        output = debugIndent(depth);
18242        if (mLayoutParams == null) {
18243            output += "BAD! no layout params";
18244        } else {
18245            output = mLayoutParams.debug(output);
18246        }
18247        Log.d(VIEW_LOG_TAG, output);
18248
18249        output = debugIndent(depth);
18250        output += "flags={";
18251        output += View.printFlags(mViewFlags);
18252        output += "}";
18253        Log.d(VIEW_LOG_TAG, output);
18254
18255        output = debugIndent(depth);
18256        output += "privateFlags={";
18257        output += View.printPrivateFlags(mPrivateFlags);
18258        output += "}";
18259        Log.d(VIEW_LOG_TAG, output);
18260    }
18261
18262    /**
18263     * Creates a string of whitespaces used for indentation.
18264     *
18265     * @param depth the indentation level
18266     * @return a String containing (depth * 2 + 3) * 2 white spaces
18267     *
18268     * @hide
18269     */
18270    protected static String debugIndent(int depth) {
18271        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18272        for (int i = 0; i < (depth * 2) + 3; i++) {
18273            spaces.append(' ').append(' ');
18274        }
18275        return spaces.toString();
18276    }
18277
18278    /**
18279     * <p>Return the offset of the widget's text baseline from the widget's top
18280     * boundary. If this widget does not support baseline alignment, this
18281     * method returns -1. </p>
18282     *
18283     * @return the offset of the baseline within the widget's bounds or -1
18284     *         if baseline alignment is not supported
18285     */
18286    @ViewDebug.ExportedProperty(category = "layout")
18287    public int getBaseline() {
18288        return -1;
18289    }
18290
18291    /**
18292     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18293     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18294     * a layout pass.
18295     *
18296     * @return whether the view hierarchy is currently undergoing a layout pass
18297     */
18298    public boolean isInLayout() {
18299        ViewRootImpl viewRoot = getViewRootImpl();
18300        return (viewRoot != null && viewRoot.isInLayout());
18301    }
18302
18303    /**
18304     * Call this when something has changed which has invalidated the
18305     * layout of this view. This will schedule a layout pass of the view
18306     * tree. This should not be called while the view hierarchy is currently in a layout
18307     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18308     * end of the current layout pass (and then layout will run again) or after the current
18309     * frame is drawn and the next layout occurs.
18310     *
18311     * <p>Subclasses which override this method should call the superclass method to
18312     * handle possible request-during-layout errors correctly.</p>
18313     */
18314    @CallSuper
18315    public void requestLayout() {
18316        if (mMeasureCache != null) mMeasureCache.clear();
18317
18318        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18319            // Only trigger request-during-layout logic if this is the view requesting it,
18320            // not the views in its parent hierarchy
18321            ViewRootImpl viewRoot = getViewRootImpl();
18322            if (viewRoot != null && viewRoot.isInLayout()) {
18323                if (!viewRoot.requestLayoutDuringLayout(this)) {
18324                    return;
18325                }
18326            }
18327            mAttachInfo.mViewRequestingLayout = this;
18328        }
18329
18330        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18331        mPrivateFlags |= PFLAG_INVALIDATED;
18332
18333        if (mParent != null && !mParent.isLayoutRequested()) {
18334            mParent.requestLayout();
18335        }
18336        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18337            mAttachInfo.mViewRequestingLayout = null;
18338        }
18339    }
18340
18341    /**
18342     * Forces this view to be laid out during the next layout pass.
18343     * This method does not call requestLayout() or forceLayout()
18344     * on the parent.
18345     */
18346    public void forceLayout() {
18347        if (mMeasureCache != null) mMeasureCache.clear();
18348
18349        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18350        mPrivateFlags |= PFLAG_INVALIDATED;
18351    }
18352
18353    /**
18354     * <p>
18355     * This is called to find out how big a view should be. The parent
18356     * supplies constraint information in the width and height parameters.
18357     * </p>
18358     *
18359     * <p>
18360     * The actual measurement work of a view is performed in
18361     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18362     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18363     * </p>
18364     *
18365     *
18366     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18367     *        parent
18368     * @param heightMeasureSpec Vertical space requirements as imposed by the
18369     *        parent
18370     *
18371     * @see #onMeasure(int, int)
18372     */
18373    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18374        boolean optical = isLayoutModeOptical(this);
18375        if (optical != isLayoutModeOptical(mParent)) {
18376            Insets insets = getOpticalInsets();
18377            int oWidth  = insets.left + insets.right;
18378            int oHeight = insets.top  + insets.bottom;
18379            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18380            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18381        }
18382
18383        // Suppress sign extension for the low bytes
18384        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18385        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18386
18387        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18388        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18389                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18390        final boolean matchingSize = isExactly &&
18391                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18392                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18393        if (forceLayout || !matchingSize &&
18394                (widthMeasureSpec != mOldWidthMeasureSpec ||
18395                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18396
18397            // first clears the measured dimension flag
18398            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18399
18400            resolveRtlPropertiesIfNeeded();
18401
18402            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18403            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18404                // measure ourselves, this should set the measured dimension flag back
18405                onMeasure(widthMeasureSpec, heightMeasureSpec);
18406                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18407            } else {
18408                long value = mMeasureCache.valueAt(cacheIndex);
18409                // Casting a long to int drops the high 32 bits, no mask needed
18410                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18411                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18412            }
18413
18414            // flag not set, setMeasuredDimension() was not invoked, we raise
18415            // an exception to warn the developer
18416            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18417                throw new IllegalStateException("View with id " + getId() + ": "
18418                        + getClass().getName() + "#onMeasure() did not set the"
18419                        + " measured dimension by calling"
18420                        + " setMeasuredDimension()");
18421            }
18422
18423            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18424        }
18425
18426        mOldWidthMeasureSpec = widthMeasureSpec;
18427        mOldHeightMeasureSpec = heightMeasureSpec;
18428
18429        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18430                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18431    }
18432
18433    /**
18434     * <p>
18435     * Measure the view and its content to determine the measured width and the
18436     * measured height. This method is invoked by {@link #measure(int, int)} and
18437     * should be overridden by subclasses to provide accurate and efficient
18438     * measurement of their contents.
18439     * </p>
18440     *
18441     * <p>
18442     * <strong>CONTRACT:</strong> When overriding this method, you
18443     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18444     * measured width and height of this view. Failure to do so will trigger an
18445     * <code>IllegalStateException</code>, thrown by
18446     * {@link #measure(int, int)}. Calling the superclass'
18447     * {@link #onMeasure(int, int)} is a valid use.
18448     * </p>
18449     *
18450     * <p>
18451     * The base class implementation of measure defaults to the background size,
18452     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18453     * override {@link #onMeasure(int, int)} to provide better measurements of
18454     * their content.
18455     * </p>
18456     *
18457     * <p>
18458     * If this method is overridden, it is the subclass's responsibility to make
18459     * sure the measured height and width are at least the view's minimum height
18460     * and width ({@link #getSuggestedMinimumHeight()} and
18461     * {@link #getSuggestedMinimumWidth()}).
18462     * </p>
18463     *
18464     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18465     *                         The requirements are encoded with
18466     *                         {@link android.view.View.MeasureSpec}.
18467     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18468     *                         The requirements are encoded with
18469     *                         {@link android.view.View.MeasureSpec}.
18470     *
18471     * @see #getMeasuredWidth()
18472     * @see #getMeasuredHeight()
18473     * @see #setMeasuredDimension(int, int)
18474     * @see #getSuggestedMinimumHeight()
18475     * @see #getSuggestedMinimumWidth()
18476     * @see android.view.View.MeasureSpec#getMode(int)
18477     * @see android.view.View.MeasureSpec#getSize(int)
18478     */
18479    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18480        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18481                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18482    }
18483
18484    /**
18485     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18486     * measured width and measured height. Failing to do so will trigger an
18487     * exception at measurement time.</p>
18488     *
18489     * @param measuredWidth The measured width of this view.  May be a complex
18490     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18491     * {@link #MEASURED_STATE_TOO_SMALL}.
18492     * @param measuredHeight The measured height of this view.  May be a complex
18493     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18494     * {@link #MEASURED_STATE_TOO_SMALL}.
18495     */
18496    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18497        boolean optical = isLayoutModeOptical(this);
18498        if (optical != isLayoutModeOptical(mParent)) {
18499            Insets insets = getOpticalInsets();
18500            int opticalWidth  = insets.left + insets.right;
18501            int opticalHeight = insets.top  + insets.bottom;
18502
18503            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18504            measuredHeight += optical ? opticalHeight : -opticalHeight;
18505        }
18506        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18507    }
18508
18509    /**
18510     * Sets the measured dimension without extra processing for things like optical bounds.
18511     * Useful for reapplying consistent values that have already been cooked with adjustments
18512     * for optical bounds, etc. such as those from the measurement cache.
18513     *
18514     * @param measuredWidth The measured width of this view.  May be a complex
18515     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18516     * {@link #MEASURED_STATE_TOO_SMALL}.
18517     * @param measuredHeight The measured height of this view.  May be a complex
18518     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18519     * {@link #MEASURED_STATE_TOO_SMALL}.
18520     */
18521    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18522        mMeasuredWidth = measuredWidth;
18523        mMeasuredHeight = measuredHeight;
18524
18525        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18526    }
18527
18528    /**
18529     * Merge two states as returned by {@link #getMeasuredState()}.
18530     * @param curState The current state as returned from a view or the result
18531     * of combining multiple views.
18532     * @param newState The new view state to combine.
18533     * @return Returns a new integer reflecting the combination of the two
18534     * states.
18535     */
18536    public static int combineMeasuredStates(int curState, int newState) {
18537        return curState | newState;
18538    }
18539
18540    /**
18541     * Version of {@link #resolveSizeAndState(int, int, int)}
18542     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18543     */
18544    public static int resolveSize(int size, int measureSpec) {
18545        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18546    }
18547
18548    /**
18549     * Utility to reconcile a desired size and state, with constraints imposed
18550     * by a MeasureSpec. Will take the desired size, unless a different size
18551     * is imposed by the constraints. The returned value is a compound integer,
18552     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18553     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18554     * resulting size is smaller than the size the view wants to be.
18555     *
18556     * @param size How big the view wants to be.
18557     * @param measureSpec Constraints imposed by the parent.
18558     * @param childMeasuredState Size information bit mask for the view's
18559     *                           children.
18560     * @return Size information bit mask as defined by
18561     *         {@link #MEASURED_SIZE_MASK} and
18562     *         {@link #MEASURED_STATE_TOO_SMALL}.
18563     */
18564    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18565        final int specMode = MeasureSpec.getMode(measureSpec);
18566        final int specSize = MeasureSpec.getSize(measureSpec);
18567        final int result;
18568        switch (specMode) {
18569            case MeasureSpec.AT_MOST:
18570                if (specSize < size) {
18571                    result = specSize | MEASURED_STATE_TOO_SMALL;
18572                } else {
18573                    result = size;
18574                }
18575                break;
18576            case MeasureSpec.EXACTLY:
18577                result = specSize;
18578                break;
18579            case MeasureSpec.UNSPECIFIED:
18580            default:
18581                result = size;
18582        }
18583        return result | (childMeasuredState & MEASURED_STATE_MASK);
18584    }
18585
18586    /**
18587     * Utility to return a default size. Uses the supplied size if the
18588     * MeasureSpec imposed no constraints. Will get larger if allowed
18589     * by the MeasureSpec.
18590     *
18591     * @param size Default size for this view
18592     * @param measureSpec Constraints imposed by the parent
18593     * @return The size this view should be.
18594     */
18595    public static int getDefaultSize(int size, int measureSpec) {
18596        int result = size;
18597        int specMode = MeasureSpec.getMode(measureSpec);
18598        int specSize = MeasureSpec.getSize(measureSpec);
18599
18600        switch (specMode) {
18601        case MeasureSpec.UNSPECIFIED:
18602            result = size;
18603            break;
18604        case MeasureSpec.AT_MOST:
18605        case MeasureSpec.EXACTLY:
18606            result = specSize;
18607            break;
18608        }
18609        return result;
18610    }
18611
18612    /**
18613     * Returns the suggested minimum height that the view should use. This
18614     * returns the maximum of the view's minimum height
18615     * and the background's minimum height
18616     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
18617     * <p>
18618     * When being used in {@link #onMeasure(int, int)}, the caller should still
18619     * ensure the returned height is within the requirements of the parent.
18620     *
18621     * @return The suggested minimum height of the view.
18622     */
18623    protected int getSuggestedMinimumHeight() {
18624        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
18625
18626    }
18627
18628    /**
18629     * Returns the suggested minimum width that the view should use. This
18630     * returns the maximum of the view's minimum width)
18631     * and the background's minimum width
18632     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
18633     * <p>
18634     * When being used in {@link #onMeasure(int, int)}, the caller should still
18635     * ensure the returned width is within the requirements of the parent.
18636     *
18637     * @return The suggested minimum width of the view.
18638     */
18639    protected int getSuggestedMinimumWidth() {
18640        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
18641    }
18642
18643    /**
18644     * Returns the minimum height of the view.
18645     *
18646     * @return the minimum height the view will try to be.
18647     *
18648     * @see #setMinimumHeight(int)
18649     *
18650     * @attr ref android.R.styleable#View_minHeight
18651     */
18652    public int getMinimumHeight() {
18653        return mMinHeight;
18654    }
18655
18656    /**
18657     * Sets the minimum height of the view. It is not guaranteed the view will
18658     * be able to achieve this minimum height (for example, if its parent layout
18659     * constrains it with less available height).
18660     *
18661     * @param minHeight The minimum height the view will try to be.
18662     *
18663     * @see #getMinimumHeight()
18664     *
18665     * @attr ref android.R.styleable#View_minHeight
18666     */
18667    public void setMinimumHeight(int minHeight) {
18668        mMinHeight = minHeight;
18669        requestLayout();
18670    }
18671
18672    /**
18673     * Returns the minimum width of the view.
18674     *
18675     * @return the minimum width the view will try to be.
18676     *
18677     * @see #setMinimumWidth(int)
18678     *
18679     * @attr ref android.R.styleable#View_minWidth
18680     */
18681    public int getMinimumWidth() {
18682        return mMinWidth;
18683    }
18684
18685    /**
18686     * Sets the minimum width of the view. It is not guaranteed the view will
18687     * be able to achieve this minimum width (for example, if its parent layout
18688     * constrains it with less available width).
18689     *
18690     * @param minWidth The minimum width the view will try to be.
18691     *
18692     * @see #getMinimumWidth()
18693     *
18694     * @attr ref android.R.styleable#View_minWidth
18695     */
18696    public void setMinimumWidth(int minWidth) {
18697        mMinWidth = minWidth;
18698        requestLayout();
18699
18700    }
18701
18702    /**
18703     * Get the animation currently associated with this view.
18704     *
18705     * @return The animation that is currently playing or
18706     *         scheduled to play for this view.
18707     */
18708    public Animation getAnimation() {
18709        return mCurrentAnimation;
18710    }
18711
18712    /**
18713     * Start the specified animation now.
18714     *
18715     * @param animation the animation to start now
18716     */
18717    public void startAnimation(Animation animation) {
18718        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
18719        setAnimation(animation);
18720        invalidateParentCaches();
18721        invalidate(true);
18722    }
18723
18724    /**
18725     * Cancels any animations for this view.
18726     */
18727    public void clearAnimation() {
18728        if (mCurrentAnimation != null) {
18729            mCurrentAnimation.detach();
18730        }
18731        mCurrentAnimation = null;
18732        invalidateParentIfNeeded();
18733    }
18734
18735    /**
18736     * Sets the next animation to play for this view.
18737     * If you want the animation to play immediately, use
18738     * {@link #startAnimation(android.view.animation.Animation)} instead.
18739     * This method provides allows fine-grained
18740     * control over the start time and invalidation, but you
18741     * must make sure that 1) the animation has a start time set, and
18742     * 2) the view's parent (which controls animations on its children)
18743     * will be invalidated when the animation is supposed to
18744     * start.
18745     *
18746     * @param animation The next animation, or null.
18747     */
18748    public void setAnimation(Animation animation) {
18749        mCurrentAnimation = animation;
18750
18751        if (animation != null) {
18752            // If the screen is off assume the animation start time is now instead of
18753            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
18754            // would cause the animation to start when the screen turns back on
18755            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
18756                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
18757                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
18758            }
18759            animation.reset();
18760        }
18761    }
18762
18763    /**
18764     * Invoked by a parent ViewGroup to notify the start of the animation
18765     * currently associated with this view. If you override this method,
18766     * always call super.onAnimationStart();
18767     *
18768     * @see #setAnimation(android.view.animation.Animation)
18769     * @see #getAnimation()
18770     */
18771    @CallSuper
18772    protected void onAnimationStart() {
18773        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
18774    }
18775
18776    /**
18777     * Invoked by a parent ViewGroup to notify the end of the animation
18778     * currently associated with this view. If you override this method,
18779     * always call super.onAnimationEnd();
18780     *
18781     * @see #setAnimation(android.view.animation.Animation)
18782     * @see #getAnimation()
18783     */
18784    @CallSuper
18785    protected void onAnimationEnd() {
18786        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
18787    }
18788
18789    /**
18790     * Invoked if there is a Transform that involves alpha. Subclass that can
18791     * draw themselves with the specified alpha should return true, and then
18792     * respect that alpha when their onDraw() is called. If this returns false
18793     * then the view may be redirected to draw into an offscreen buffer to
18794     * fulfill the request, which will look fine, but may be slower than if the
18795     * subclass handles it internally. The default implementation returns false.
18796     *
18797     * @param alpha The alpha (0..255) to apply to the view's drawing
18798     * @return true if the view can draw with the specified alpha.
18799     */
18800    protected boolean onSetAlpha(int alpha) {
18801        return false;
18802    }
18803
18804    /**
18805     * This is used by the RootView to perform an optimization when
18806     * the view hierarchy contains one or several SurfaceView.
18807     * SurfaceView is always considered transparent, but its children are not,
18808     * therefore all View objects remove themselves from the global transparent
18809     * region (passed as a parameter to this function).
18810     *
18811     * @param region The transparent region for this ViewAncestor (window).
18812     *
18813     * @return Returns true if the effective visibility of the view at this
18814     * point is opaque, regardless of the transparent region; returns false
18815     * if it is possible for underlying windows to be seen behind the view.
18816     *
18817     * {@hide}
18818     */
18819    public boolean gatherTransparentRegion(Region region) {
18820        final AttachInfo attachInfo = mAttachInfo;
18821        if (region != null && attachInfo != null) {
18822            final int pflags = mPrivateFlags;
18823            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18824                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18825                // remove it from the transparent region.
18826                final int[] location = attachInfo.mTransparentLocation;
18827                getLocationInWindow(location);
18828                region.op(location[0], location[1], location[0] + mRight - mLeft,
18829                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18830            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18831                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18832                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18833                // exists, so we remove the background drawable's non-transparent
18834                // parts from this transparent region.
18835                applyDrawableToTransparentRegion(mBackground, region);
18836            }
18837            final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18838            if (foreground != null) {
18839                applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
18840            }
18841        }
18842        return true;
18843    }
18844
18845    /**
18846     * Play a sound effect for this view.
18847     *
18848     * <p>The framework will play sound effects for some built in actions, such as
18849     * clicking, but you may wish to play these effects in your widget,
18850     * for instance, for internal navigation.
18851     *
18852     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18853     * {@link #isSoundEffectsEnabled()} is true.
18854     *
18855     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18856     */
18857    public void playSoundEffect(int soundConstant) {
18858        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18859            return;
18860        }
18861        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18862    }
18863
18864    /**
18865     * BZZZTT!!1!
18866     *
18867     * <p>Provide haptic feedback to the user for this view.
18868     *
18869     * <p>The framework will provide haptic feedback for some built in actions,
18870     * such as long presses, but you may wish to provide feedback for your
18871     * own widget.
18872     *
18873     * <p>The feedback will only be performed if
18874     * {@link #isHapticFeedbackEnabled()} is true.
18875     *
18876     * @param feedbackConstant One of the constants defined in
18877     * {@link HapticFeedbackConstants}
18878     */
18879    public boolean performHapticFeedback(int feedbackConstant) {
18880        return performHapticFeedback(feedbackConstant, 0);
18881    }
18882
18883    /**
18884     * BZZZTT!!1!
18885     *
18886     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18887     *
18888     * @param feedbackConstant One of the constants defined in
18889     * {@link HapticFeedbackConstants}
18890     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18891     */
18892    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18893        if (mAttachInfo == null) {
18894            return false;
18895        }
18896        //noinspection SimplifiableIfStatement
18897        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18898                && !isHapticFeedbackEnabled()) {
18899            return false;
18900        }
18901        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18902                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18903    }
18904
18905    /**
18906     * Request that the visibility of the status bar or other screen/window
18907     * decorations be changed.
18908     *
18909     * <p>This method is used to put the over device UI into temporary modes
18910     * where the user's attention is focused more on the application content,
18911     * by dimming or hiding surrounding system affordances.  This is typically
18912     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18913     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18914     * to be placed behind the action bar (and with these flags other system
18915     * affordances) so that smooth transitions between hiding and showing them
18916     * can be done.
18917     *
18918     * <p>Two representative examples of the use of system UI visibility is
18919     * implementing a content browsing application (like a magazine reader)
18920     * and a video playing application.
18921     *
18922     * <p>The first code shows a typical implementation of a View in a content
18923     * browsing application.  In this implementation, the application goes
18924     * into a content-oriented mode by hiding the status bar and action bar,
18925     * and putting the navigation elements into lights out mode.  The user can
18926     * then interact with content while in this mode.  Such an application should
18927     * provide an easy way for the user to toggle out of the mode (such as to
18928     * check information in the status bar or access notifications).  In the
18929     * implementation here, this is done simply by tapping on the content.
18930     *
18931     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18932     *      content}
18933     *
18934     * <p>This second code sample shows a typical implementation of a View
18935     * in a video playing application.  In this situation, while the video is
18936     * playing the application would like to go into a complete full-screen mode,
18937     * to use as much of the display as possible for the video.  When in this state
18938     * the user can not interact with the application; the system intercepts
18939     * touching on the screen to pop the UI out of full screen mode.  See
18940     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18941     *
18942     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18943     *      content}
18944     *
18945     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18946     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18947     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18948     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18949     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18950     */
18951    public void setSystemUiVisibility(int visibility) {
18952        if (visibility != mSystemUiVisibility) {
18953            mSystemUiVisibility = visibility;
18954            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18955                mParent.recomputeViewAttributes(this);
18956            }
18957        }
18958    }
18959
18960    /**
18961     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18962     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18963     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18964     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18965     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18966     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18967     */
18968    public int getSystemUiVisibility() {
18969        return mSystemUiVisibility;
18970    }
18971
18972    /**
18973     * Returns the current system UI visibility that is currently set for
18974     * the entire window.  This is the combination of the
18975     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18976     * views in the window.
18977     */
18978    public int getWindowSystemUiVisibility() {
18979        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18980    }
18981
18982    /**
18983     * Override to find out when the window's requested system UI visibility
18984     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18985     * This is different from the callbacks received through
18986     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18987     * in that this is only telling you about the local request of the window,
18988     * not the actual values applied by the system.
18989     */
18990    public void onWindowSystemUiVisibilityChanged(int visible) {
18991    }
18992
18993    /**
18994     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18995     * the view hierarchy.
18996     */
18997    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
18998        onWindowSystemUiVisibilityChanged(visible);
18999    }
19000
19001    /**
19002     * Set a listener to receive callbacks when the visibility of the system bar changes.
19003     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
19004     */
19005    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
19006        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
19007        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
19008            mParent.recomputeViewAttributes(this);
19009        }
19010    }
19011
19012    /**
19013     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
19014     * the view hierarchy.
19015     */
19016    public void dispatchSystemUiVisibilityChanged(int visibility) {
19017        ListenerInfo li = mListenerInfo;
19018        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
19019            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
19020                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
19021        }
19022    }
19023
19024    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
19025        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
19026        if (val != mSystemUiVisibility) {
19027            setSystemUiVisibility(val);
19028            return true;
19029        }
19030        return false;
19031    }
19032
19033    /** @hide */
19034    public void setDisabledSystemUiVisibility(int flags) {
19035        if (mAttachInfo != null) {
19036            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
19037                mAttachInfo.mDisabledSystemUiVisibility = flags;
19038                if (mParent != null) {
19039                    mParent.recomputeViewAttributes(this);
19040                }
19041            }
19042        }
19043    }
19044
19045    /**
19046     * Creates an image that the system displays during the drag and drop
19047     * operation. This is called a &quot;drag shadow&quot;. The default implementation
19048     * for a DragShadowBuilder based on a View returns an image that has exactly the same
19049     * appearance as the given View. The default also positions the center of the drag shadow
19050     * directly under the touch point. If no View is provided (the constructor with no parameters
19051     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
19052     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
19053     * default is an invisible drag shadow.
19054     * <p>
19055     * You are not required to use the View you provide to the constructor as the basis of the
19056     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
19057     * anything you want as the drag shadow.
19058     * </p>
19059     * <p>
19060     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
19061     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
19062     *  size and position of the drag shadow. It uses this data to construct a
19063     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
19064     *  so that your application can draw the shadow image in the Canvas.
19065     * </p>
19066     *
19067     * <div class="special reference">
19068     * <h3>Developer Guides</h3>
19069     * <p>For a guide to implementing drag and drop features, read the
19070     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19071     * </div>
19072     */
19073    public static class DragShadowBuilder {
19074        private final WeakReference<View> mView;
19075
19076        /**
19077         * Constructs a shadow image builder based on a View. By default, the resulting drag
19078         * shadow will have the same appearance and dimensions as the View, with the touch point
19079         * over the center of the View.
19080         * @param view A View. Any View in scope can be used.
19081         */
19082        public DragShadowBuilder(View view) {
19083            mView = new WeakReference<View>(view);
19084        }
19085
19086        /**
19087         * Construct a shadow builder object with no associated View.  This
19088         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
19089         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
19090         * to supply the drag shadow's dimensions and appearance without
19091         * reference to any View object. If they are not overridden, then the result is an
19092         * invisible drag shadow.
19093         */
19094        public DragShadowBuilder() {
19095            mView = new WeakReference<View>(null);
19096        }
19097
19098        /**
19099         * Returns the View object that had been passed to the
19100         * {@link #View.DragShadowBuilder(View)}
19101         * constructor.  If that View parameter was {@code null} or if the
19102         * {@link #View.DragShadowBuilder()}
19103         * constructor was used to instantiate the builder object, this method will return
19104         * null.
19105         *
19106         * @return The View object associate with this builder object.
19107         */
19108        @SuppressWarnings({"JavadocReference"})
19109        final public View getView() {
19110            return mView.get();
19111        }
19112
19113        /**
19114         * Provides the metrics for the shadow image. These include the dimensions of
19115         * the shadow image, and the point within that shadow that should
19116         * be centered under the touch location while dragging.
19117         * <p>
19118         * The default implementation sets the dimensions of the shadow to be the
19119         * same as the dimensions of the View itself and centers the shadow under
19120         * the touch point.
19121         * </p>
19122         *
19123         * @param shadowSize A {@link android.graphics.Point} containing the width and height
19124         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
19125         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
19126         * image.
19127         *
19128         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
19129         * shadow image that should be underneath the touch point during the drag and drop
19130         * operation. Your application must set {@link android.graphics.Point#x} to the
19131         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
19132         */
19133        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
19134            final View view = mView.get();
19135            if (view != null) {
19136                shadowSize.set(view.getWidth(), view.getHeight());
19137                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
19138            } else {
19139                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
19140            }
19141        }
19142
19143        /**
19144         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
19145         * based on the dimensions it received from the
19146         * {@link #onProvideShadowMetrics(Point, Point)} callback.
19147         *
19148         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
19149         */
19150        public void onDrawShadow(Canvas canvas) {
19151            final View view = mView.get();
19152            if (view != null) {
19153                view.draw(canvas);
19154            } else {
19155                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
19156            }
19157        }
19158    }
19159
19160    /**
19161     * Starts a drag and drop operation. When your application calls this method, it passes a
19162     * {@link android.view.View.DragShadowBuilder} object to the system. The
19163     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
19164     * to get metrics for the drag shadow, and then calls the object's
19165     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
19166     * <p>
19167     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
19168     *  drag events to all the View objects in your application that are currently visible. It does
19169     *  this either by calling the View object's drag listener (an implementation of
19170     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
19171     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
19172     *  Both are passed a {@link android.view.DragEvent} object that has a
19173     *  {@link android.view.DragEvent#getAction()} value of
19174     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
19175     * </p>
19176     * <p>
19177     * Your application can invoke startDrag() on any attached View object. The View object does not
19178     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
19179     * be related to the View the user selected for dragging.
19180     * </p>
19181     * @param data A {@link android.content.ClipData} object pointing to the data to be
19182     * transferred by the drag and drop operation.
19183     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
19184     * drag shadow.
19185     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
19186     * drop operation. This Object is put into every DragEvent object sent by the system during the
19187     * current drag.
19188     * <p>
19189     * myLocalState is a lightweight mechanism for the sending information from the dragged View
19190     * to the target Views. For example, it can contain flags that differentiate between a
19191     * a copy operation and a move operation.
19192     * </p>
19193     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
19194     * so the parameter should be set to 0.
19195     * @return {@code true} if the method completes successfully, or
19196     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
19197     * do a drag, and so no drag operation is in progress.
19198     */
19199    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
19200            Object myLocalState, int flags) {
19201        if (ViewDebug.DEBUG_DRAG) {
19202            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
19203        }
19204        boolean okay = false;
19205
19206        Point shadowSize = new Point();
19207        Point shadowTouchPoint = new Point();
19208        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
19209
19210        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
19211                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
19212            throw new IllegalStateException("Drag shadow dimensions must not be negative");
19213        }
19214
19215        if (ViewDebug.DEBUG_DRAG) {
19216            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
19217                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
19218        }
19219        Surface surface = new Surface();
19220        try {
19221            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
19222                    flags, shadowSize.x, shadowSize.y, surface);
19223            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
19224                    + " surface=" + surface);
19225            if (token != null) {
19226                Canvas canvas = surface.lockCanvas(null);
19227                try {
19228                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
19229                    shadowBuilder.onDrawShadow(canvas);
19230                } finally {
19231                    surface.unlockCanvasAndPost(canvas);
19232                }
19233
19234                final ViewRootImpl root = getViewRootImpl();
19235
19236                // Cache the local state object for delivery with DragEvents
19237                root.setLocalDragState(myLocalState);
19238
19239                // repurpose 'shadowSize' for the last touch point
19240                root.getLastTouchPoint(shadowSize);
19241
19242                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19243                        shadowSize.x, shadowSize.y,
19244                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19245                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19246
19247                // Off and running!  Release our local surface instance; the drag
19248                // shadow surface is now managed by the system process.
19249                surface.release();
19250            }
19251        } catch (Exception e) {
19252            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19253            surface.destroy();
19254        }
19255
19256        return okay;
19257    }
19258
19259    /**
19260     * Handles drag events sent by the system following a call to
19261     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19262     *<p>
19263     * When the system calls this method, it passes a
19264     * {@link android.view.DragEvent} object. A call to
19265     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19266     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19267     * operation.
19268     * @param event The {@link android.view.DragEvent} sent by the system.
19269     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19270     * in DragEvent, indicating the type of drag event represented by this object.
19271     * @return {@code true} if the method was successful, otherwise {@code false}.
19272     * <p>
19273     *  The method should return {@code true} in response to an action type of
19274     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19275     *  operation.
19276     * </p>
19277     * <p>
19278     *  The method should also return {@code true} in response to an action type of
19279     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19280     *  {@code false} if it didn't.
19281     * </p>
19282     */
19283    public boolean onDragEvent(DragEvent event) {
19284        return false;
19285    }
19286
19287    /**
19288     * Detects if this View is enabled and has a drag event listener.
19289     * If both are true, then it calls the drag event listener with the
19290     * {@link android.view.DragEvent} it received. If the drag event listener returns
19291     * {@code true}, then dispatchDragEvent() returns {@code true}.
19292     * <p>
19293     * For all other cases, the method calls the
19294     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19295     * method and returns its result.
19296     * </p>
19297     * <p>
19298     * This ensures that a drag event is always consumed, even if the View does not have a drag
19299     * event listener. However, if the View has a listener and the listener returns true, then
19300     * onDragEvent() is not called.
19301     * </p>
19302     */
19303    public boolean dispatchDragEvent(DragEvent event) {
19304        ListenerInfo li = mListenerInfo;
19305        //noinspection SimplifiableIfStatement
19306        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19307                && li.mOnDragListener.onDrag(this, event)) {
19308            return true;
19309        }
19310        return onDragEvent(event);
19311    }
19312
19313    boolean canAcceptDrag() {
19314        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19315    }
19316
19317    /**
19318     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19319     * it is ever exposed at all.
19320     * @hide
19321     */
19322    public void onCloseSystemDialogs(String reason) {
19323    }
19324
19325    /**
19326     * Given a Drawable whose bounds have been set to draw into this view,
19327     * update a Region being computed for
19328     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19329     * that any non-transparent parts of the Drawable are removed from the
19330     * given transparent region.
19331     *
19332     * @param dr The Drawable whose transparency is to be applied to the region.
19333     * @param region A Region holding the current transparency information,
19334     * where any parts of the region that are set are considered to be
19335     * transparent.  On return, this region will be modified to have the
19336     * transparency information reduced by the corresponding parts of the
19337     * Drawable that are not transparent.
19338     * {@hide}
19339     */
19340    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19341        if (DBG) {
19342            Log.i("View", "Getting transparent region for: " + this);
19343        }
19344        final Region r = dr.getTransparentRegion();
19345        final Rect db = dr.getBounds();
19346        final AttachInfo attachInfo = mAttachInfo;
19347        if (r != null && attachInfo != null) {
19348            final int w = getRight()-getLeft();
19349            final int h = getBottom()-getTop();
19350            if (db.left > 0) {
19351                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19352                r.op(0, 0, db.left, h, Region.Op.UNION);
19353            }
19354            if (db.right < w) {
19355                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19356                r.op(db.right, 0, w, h, Region.Op.UNION);
19357            }
19358            if (db.top > 0) {
19359                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19360                r.op(0, 0, w, db.top, Region.Op.UNION);
19361            }
19362            if (db.bottom < h) {
19363                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19364                r.op(0, db.bottom, w, h, Region.Op.UNION);
19365            }
19366            final int[] location = attachInfo.mTransparentLocation;
19367            getLocationInWindow(location);
19368            r.translate(location[0], location[1]);
19369            region.op(r, Region.Op.INTERSECT);
19370        } else {
19371            region.op(db, Region.Op.DIFFERENCE);
19372        }
19373    }
19374
19375    private void checkForLongClick(int delayOffset) {
19376        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19377            mHasPerformedLongPress = false;
19378
19379            if (mPendingCheckForLongPress == null) {
19380                mPendingCheckForLongPress = new CheckForLongPress();
19381            }
19382            mPendingCheckForLongPress.rememberWindowAttachCount();
19383            postDelayed(mPendingCheckForLongPress,
19384                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19385        }
19386    }
19387
19388    /**
19389     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19390     * LayoutInflater} class, which provides a full range of options for view inflation.
19391     *
19392     * @param context The Context object for your activity or application.
19393     * @param resource The resource ID to inflate
19394     * @param root A view group that will be the parent.  Used to properly inflate the
19395     * layout_* parameters.
19396     * @see LayoutInflater
19397     */
19398    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19399        LayoutInflater factory = LayoutInflater.from(context);
19400        return factory.inflate(resource, root);
19401    }
19402
19403    /**
19404     * Scroll the view with standard behavior for scrolling beyond the normal
19405     * content boundaries. Views that call this method should override
19406     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19407     * results of an over-scroll operation.
19408     *
19409     * Views can use this method to handle any touch or fling-based scrolling.
19410     *
19411     * @param deltaX Change in X in pixels
19412     * @param deltaY Change in Y in pixels
19413     * @param scrollX Current X scroll value in pixels before applying deltaX
19414     * @param scrollY Current Y scroll value in pixels before applying deltaY
19415     * @param scrollRangeX Maximum content scroll range along the X axis
19416     * @param scrollRangeY Maximum content scroll range along the Y axis
19417     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19418     *          along the X axis.
19419     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19420     *          along the Y axis.
19421     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19422     * @return true if scrolling was clamped to an over-scroll boundary along either
19423     *          axis, false otherwise.
19424     */
19425    @SuppressWarnings({"UnusedParameters"})
19426    protected boolean overScrollBy(int deltaX, int deltaY,
19427            int scrollX, int scrollY,
19428            int scrollRangeX, int scrollRangeY,
19429            int maxOverScrollX, int maxOverScrollY,
19430            boolean isTouchEvent) {
19431        final int overScrollMode = mOverScrollMode;
19432        final boolean canScrollHorizontal =
19433                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19434        final boolean canScrollVertical =
19435                computeVerticalScrollRange() > computeVerticalScrollExtent();
19436        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19437                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19438        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19439                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19440
19441        int newScrollX = scrollX + deltaX;
19442        if (!overScrollHorizontal) {
19443            maxOverScrollX = 0;
19444        }
19445
19446        int newScrollY = scrollY + deltaY;
19447        if (!overScrollVertical) {
19448            maxOverScrollY = 0;
19449        }
19450
19451        // Clamp values if at the limits and record
19452        final int left = -maxOverScrollX;
19453        final int right = maxOverScrollX + scrollRangeX;
19454        final int top = -maxOverScrollY;
19455        final int bottom = maxOverScrollY + scrollRangeY;
19456
19457        boolean clampedX = false;
19458        if (newScrollX > right) {
19459            newScrollX = right;
19460            clampedX = true;
19461        } else if (newScrollX < left) {
19462            newScrollX = left;
19463            clampedX = true;
19464        }
19465
19466        boolean clampedY = false;
19467        if (newScrollY > bottom) {
19468            newScrollY = bottom;
19469            clampedY = true;
19470        } else if (newScrollY < top) {
19471            newScrollY = top;
19472            clampedY = true;
19473        }
19474
19475        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19476
19477        return clampedX || clampedY;
19478    }
19479
19480    /**
19481     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19482     * respond to the results of an over-scroll operation.
19483     *
19484     * @param scrollX New X scroll value in pixels
19485     * @param scrollY New Y scroll value in pixels
19486     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19487     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19488     */
19489    protected void onOverScrolled(int scrollX, int scrollY,
19490            boolean clampedX, boolean clampedY) {
19491        // Intentionally empty.
19492    }
19493
19494    /**
19495     * Returns the over-scroll mode for this view. The result will be
19496     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19497     * (allow over-scrolling only if the view content is larger than the container),
19498     * or {@link #OVER_SCROLL_NEVER}.
19499     *
19500     * @return This view's over-scroll mode.
19501     */
19502    public int getOverScrollMode() {
19503        return mOverScrollMode;
19504    }
19505
19506    /**
19507     * Set the over-scroll mode for this view. Valid over-scroll modes are
19508     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19509     * (allow over-scrolling only if the view content is larger than the container),
19510     * or {@link #OVER_SCROLL_NEVER}.
19511     *
19512     * Setting the over-scroll mode of a view will have an effect only if the
19513     * view is capable of scrolling.
19514     *
19515     * @param overScrollMode The new over-scroll mode for this view.
19516     */
19517    public void setOverScrollMode(int overScrollMode) {
19518        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19519                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19520                overScrollMode != OVER_SCROLL_NEVER) {
19521            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19522        }
19523        mOverScrollMode = overScrollMode;
19524    }
19525
19526    /**
19527     * Enable or disable nested scrolling for this view.
19528     *
19529     * <p>If this property is set to true the view will be permitted to initiate nested
19530     * scrolling operations with a compatible parent view in the current hierarchy. If this
19531     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19532     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19533     * the nested scroll.</p>
19534     *
19535     * @param enabled true to enable nested scrolling, false to disable
19536     *
19537     * @see #isNestedScrollingEnabled()
19538     */
19539    public void setNestedScrollingEnabled(boolean enabled) {
19540        if (enabled) {
19541            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19542        } else {
19543            stopNestedScroll();
19544            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19545        }
19546    }
19547
19548    /**
19549     * Returns true if nested scrolling is enabled for this view.
19550     *
19551     * <p>If nested scrolling is enabled and this View class implementation supports it,
19552     * this view will act as a nested scrolling child view when applicable, forwarding data
19553     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19554     * parent.</p>
19555     *
19556     * @return true if nested scrolling is enabled
19557     *
19558     * @see #setNestedScrollingEnabled(boolean)
19559     */
19560    public boolean isNestedScrollingEnabled() {
19561        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19562                PFLAG3_NESTED_SCROLLING_ENABLED;
19563    }
19564
19565    /**
19566     * Begin a nestable scroll operation along the given axes.
19567     *
19568     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19569     *
19570     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19571     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19572     * In the case of touch scrolling the nested scroll will be terminated automatically in
19573     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19574     * In the event of programmatic scrolling the caller must explicitly call
19575     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19576     *
19577     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19578     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19579     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19580     *
19581     * <p>At each incremental step of the scroll the caller should invoke
19582     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19583     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19584     * parent at least partially consumed the scroll and the caller should adjust the amount it
19585     * scrolls by.</p>
19586     *
19587     * <p>After applying the remainder of the scroll delta the caller should invoke
19588     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19589     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19590     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19591     * </p>
19592     *
19593     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19594     *             {@link #SCROLL_AXIS_VERTICAL}.
19595     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19596     *         the current gesture.
19597     *
19598     * @see #stopNestedScroll()
19599     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19600     * @see #dispatchNestedScroll(int, int, int, int, int[])
19601     */
19602    public boolean startNestedScroll(int axes) {
19603        if (hasNestedScrollingParent()) {
19604            // Already in progress
19605            return true;
19606        }
19607        if (isNestedScrollingEnabled()) {
19608            ViewParent p = getParent();
19609            View child = this;
19610            while (p != null) {
19611                try {
19612                    if (p.onStartNestedScroll(child, this, axes)) {
19613                        mNestedScrollingParent = p;
19614                        p.onNestedScrollAccepted(child, this, axes);
19615                        return true;
19616                    }
19617                } catch (AbstractMethodError e) {
19618                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
19619                            "method onStartNestedScroll", e);
19620                    // Allow the search upward to continue
19621                }
19622                if (p instanceof View) {
19623                    child = (View) p;
19624                }
19625                p = p.getParent();
19626            }
19627        }
19628        return false;
19629    }
19630
19631    /**
19632     * Stop a nested scroll in progress.
19633     *
19634     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
19635     *
19636     * @see #startNestedScroll(int)
19637     */
19638    public void stopNestedScroll() {
19639        if (mNestedScrollingParent != null) {
19640            mNestedScrollingParent.onStopNestedScroll(this);
19641            mNestedScrollingParent = null;
19642        }
19643    }
19644
19645    /**
19646     * Returns true if this view has a nested scrolling parent.
19647     *
19648     * <p>The presence of a nested scrolling parent indicates that this view has initiated
19649     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
19650     *
19651     * @return whether this view has a nested scrolling parent
19652     */
19653    public boolean hasNestedScrollingParent() {
19654        return mNestedScrollingParent != null;
19655    }
19656
19657    /**
19658     * Dispatch one step of a nested scroll in progress.
19659     *
19660     * <p>Implementations of views that support nested scrolling should call this to report
19661     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
19662     * is not currently in progress or nested scrolling is not
19663     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
19664     *
19665     * <p>Compatible View implementations should also call
19666     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
19667     * consuming a component of the scroll event themselves.</p>
19668     *
19669     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
19670     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
19671     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
19672     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
19673     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19674     *                       in local view coordinates of this view from before this operation
19675     *                       to after it completes. View implementations may use this to adjust
19676     *                       expected input coordinate tracking.
19677     * @return true if the event was dispatched, false if it could not be dispatched.
19678     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19679     */
19680    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
19681            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
19682        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19683            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
19684                int startX = 0;
19685                int startY = 0;
19686                if (offsetInWindow != null) {
19687                    getLocationInWindow(offsetInWindow);
19688                    startX = offsetInWindow[0];
19689                    startY = offsetInWindow[1];
19690                }
19691
19692                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
19693                        dxUnconsumed, dyUnconsumed);
19694
19695                if (offsetInWindow != null) {
19696                    getLocationInWindow(offsetInWindow);
19697                    offsetInWindow[0] -= startX;
19698                    offsetInWindow[1] -= startY;
19699                }
19700                return true;
19701            } else if (offsetInWindow != null) {
19702                // No motion, no dispatch. Keep offsetInWindow up to date.
19703                offsetInWindow[0] = 0;
19704                offsetInWindow[1] = 0;
19705            }
19706        }
19707        return false;
19708    }
19709
19710    /**
19711     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
19712     *
19713     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
19714     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
19715     * scrolling operation to consume some or all of the scroll operation before the child view
19716     * consumes it.</p>
19717     *
19718     * @param dx Horizontal scroll distance in pixels
19719     * @param dy Vertical scroll distance in pixels
19720     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
19721     *                 and consumed[1] the consumed dy.
19722     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19723     *                       in local view coordinates of this view from before this operation
19724     *                       to after it completes. View implementations may use this to adjust
19725     *                       expected input coordinate tracking.
19726     * @return true if the parent consumed some or all of the scroll delta
19727     * @see #dispatchNestedScroll(int, int, int, int, int[])
19728     */
19729    public boolean dispatchNestedPreScroll(int dx, int dy,
19730            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
19731        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19732            if (dx != 0 || dy != 0) {
19733                int startX = 0;
19734                int startY = 0;
19735                if (offsetInWindow != null) {
19736                    getLocationInWindow(offsetInWindow);
19737                    startX = offsetInWindow[0];
19738                    startY = offsetInWindow[1];
19739                }
19740
19741                if (consumed == null) {
19742                    if (mTempNestedScrollConsumed == null) {
19743                        mTempNestedScrollConsumed = new int[2];
19744                    }
19745                    consumed = mTempNestedScrollConsumed;
19746                }
19747                consumed[0] = 0;
19748                consumed[1] = 0;
19749                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
19750
19751                if (offsetInWindow != null) {
19752                    getLocationInWindow(offsetInWindow);
19753                    offsetInWindow[0] -= startX;
19754                    offsetInWindow[1] -= startY;
19755                }
19756                return consumed[0] != 0 || consumed[1] != 0;
19757            } else if (offsetInWindow != null) {
19758                offsetInWindow[0] = 0;
19759                offsetInWindow[1] = 0;
19760            }
19761        }
19762        return false;
19763    }
19764
19765    /**
19766     * Dispatch a fling to a nested scrolling parent.
19767     *
19768     * <p>This method should be used to indicate that a nested scrolling child has detected
19769     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
19770     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
19771     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
19772     * along a scrollable axis.</p>
19773     *
19774     * <p>If a nested scrolling child view would normally fling but it is at the edge of
19775     * its own content, it can use this method to delegate the fling to its nested scrolling
19776     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
19777     *
19778     * @param velocityX Horizontal fling velocity in pixels per second
19779     * @param velocityY Vertical fling velocity in pixels per second
19780     * @param consumed true if the child consumed the fling, false otherwise
19781     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
19782     */
19783    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
19784        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19785            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
19786        }
19787        return false;
19788    }
19789
19790    /**
19791     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
19792     *
19793     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
19794     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
19795     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
19796     * before the child view consumes it. If this method returns <code>true</code>, a nested
19797     * parent view consumed the fling and this view should not scroll as a result.</p>
19798     *
19799     * <p>For a better user experience, only one view in a nested scrolling chain should consume
19800     * the fling at a time. If a parent view consumed the fling this method will return false.
19801     * Custom view implementations should account for this in two ways:</p>
19802     *
19803     * <ul>
19804     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19805     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19806     *     position regardless.</li>
19807     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19808     *     even to settle back to a valid idle position.</li>
19809     * </ul>
19810     *
19811     * <p>Views should also not offer fling velocities to nested parent views along an axis
19812     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19813     * should not offer a horizontal fling velocity to its parents since scrolling along that
19814     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19815     *
19816     * @param velocityX Horizontal fling velocity in pixels per second
19817     * @param velocityY Vertical fling velocity in pixels per second
19818     * @return true if a nested scrolling parent consumed the fling
19819     */
19820    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19821        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19822            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19823        }
19824        return false;
19825    }
19826
19827    /**
19828     * Gets a scale factor that determines the distance the view should scroll
19829     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19830     * @return The vertical scroll scale factor.
19831     * @hide
19832     */
19833    protected float getVerticalScrollFactor() {
19834        if (mVerticalScrollFactor == 0) {
19835            TypedValue outValue = new TypedValue();
19836            if (!mContext.getTheme().resolveAttribute(
19837                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19838                throw new IllegalStateException(
19839                        "Expected theme to define listPreferredItemHeight.");
19840            }
19841            mVerticalScrollFactor = outValue.getDimension(
19842                    mContext.getResources().getDisplayMetrics());
19843        }
19844        return mVerticalScrollFactor;
19845    }
19846
19847    /**
19848     * Gets a scale factor that determines the distance the view should scroll
19849     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19850     * @return The horizontal scroll scale factor.
19851     * @hide
19852     */
19853    protected float getHorizontalScrollFactor() {
19854        // TODO: Should use something else.
19855        return getVerticalScrollFactor();
19856    }
19857
19858    /**
19859     * Return the value specifying the text direction or policy that was set with
19860     * {@link #setTextDirection(int)}.
19861     *
19862     * @return the defined text direction. It can be one of:
19863     *
19864     * {@link #TEXT_DIRECTION_INHERIT},
19865     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19866     * {@link #TEXT_DIRECTION_ANY_RTL},
19867     * {@link #TEXT_DIRECTION_LTR},
19868     * {@link #TEXT_DIRECTION_RTL},
19869     * {@link #TEXT_DIRECTION_LOCALE},
19870     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19871     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19872     *
19873     * @attr ref android.R.styleable#View_textDirection
19874     *
19875     * @hide
19876     */
19877    @ViewDebug.ExportedProperty(category = "text", mapping = {
19878            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19879            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19880            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19881            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19882            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19883            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19884            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19885            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19886    })
19887    public int getRawTextDirection() {
19888        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19889    }
19890
19891    /**
19892     * Set the text direction.
19893     *
19894     * @param textDirection the direction to set. Should be one of:
19895     *
19896     * {@link #TEXT_DIRECTION_INHERIT},
19897     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19898     * {@link #TEXT_DIRECTION_ANY_RTL},
19899     * {@link #TEXT_DIRECTION_LTR},
19900     * {@link #TEXT_DIRECTION_RTL},
19901     * {@link #TEXT_DIRECTION_LOCALE}
19902     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19903     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
19904     *
19905     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19906     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19907     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19908     *
19909     * @attr ref android.R.styleable#View_textDirection
19910     */
19911    public void setTextDirection(int textDirection) {
19912        if (getRawTextDirection() != textDirection) {
19913            // Reset the current text direction and the resolved one
19914            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19915            resetResolvedTextDirection();
19916            // Set the new text direction
19917            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19918            // Do resolution
19919            resolveTextDirection();
19920            // Notify change
19921            onRtlPropertiesChanged(getLayoutDirection());
19922            // Refresh
19923            requestLayout();
19924            invalidate(true);
19925        }
19926    }
19927
19928    /**
19929     * Return the resolved text direction.
19930     *
19931     * @return the resolved text direction. Returns one of:
19932     *
19933     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19934     * {@link #TEXT_DIRECTION_ANY_RTL},
19935     * {@link #TEXT_DIRECTION_LTR},
19936     * {@link #TEXT_DIRECTION_RTL},
19937     * {@link #TEXT_DIRECTION_LOCALE},
19938     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19939     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19940     *
19941     * @attr ref android.R.styleable#View_textDirection
19942     */
19943    @ViewDebug.ExportedProperty(category = "text", mapping = {
19944            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19945            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19946            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19947            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19948            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19949            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19950            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19951            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19952    })
19953    public int getTextDirection() {
19954        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19955    }
19956
19957    /**
19958     * Resolve the text direction.
19959     *
19960     * @return true if resolution has been done, false otherwise.
19961     *
19962     * @hide
19963     */
19964    public boolean resolveTextDirection() {
19965        // Reset any previous text direction resolution
19966        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19967
19968        if (hasRtlSupport()) {
19969            // Set resolved text direction flag depending on text direction flag
19970            final int textDirection = getRawTextDirection();
19971            switch(textDirection) {
19972                case TEXT_DIRECTION_INHERIT:
19973                    if (!canResolveTextDirection()) {
19974                        // We cannot do the resolution if there is no parent, so use the default one
19975                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19976                        // Resolution will need to happen again later
19977                        return false;
19978                    }
19979
19980                    // Parent has not yet resolved, so we still return the default
19981                    try {
19982                        if (!mParent.isTextDirectionResolved()) {
19983                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19984                            // Resolution will need to happen again later
19985                            return false;
19986                        }
19987                    } catch (AbstractMethodError e) {
19988                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19989                                " does not fully implement ViewParent", e);
19990                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19991                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19992                        return true;
19993                    }
19994
19995                    // Set current resolved direction to the same value as the parent's one
19996                    int parentResolvedDirection;
19997                    try {
19998                        parentResolvedDirection = mParent.getTextDirection();
19999                    } catch (AbstractMethodError e) {
20000                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20001                                " does not fully implement ViewParent", e);
20002                        parentResolvedDirection = TEXT_DIRECTION_LTR;
20003                    }
20004                    switch (parentResolvedDirection) {
20005                        case TEXT_DIRECTION_FIRST_STRONG:
20006                        case TEXT_DIRECTION_ANY_RTL:
20007                        case TEXT_DIRECTION_LTR:
20008                        case TEXT_DIRECTION_RTL:
20009                        case TEXT_DIRECTION_LOCALE:
20010                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
20011                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
20012                            mPrivateFlags2 |=
20013                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20014                            break;
20015                        default:
20016                            // Default resolved direction is "first strong" heuristic
20017                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20018                    }
20019                    break;
20020                case TEXT_DIRECTION_FIRST_STRONG:
20021                case TEXT_DIRECTION_ANY_RTL:
20022                case TEXT_DIRECTION_LTR:
20023                case TEXT_DIRECTION_RTL:
20024                case TEXT_DIRECTION_LOCALE:
20025                case TEXT_DIRECTION_FIRST_STRONG_LTR:
20026                case TEXT_DIRECTION_FIRST_STRONG_RTL:
20027                    // Resolved direction is the same as text direction
20028                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20029                    break;
20030                default:
20031                    // Default resolved direction is "first strong" heuristic
20032                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20033            }
20034        } else {
20035            // Default resolved direction is "first strong" heuristic
20036            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20037        }
20038
20039        // Set to resolved
20040        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
20041        return true;
20042    }
20043
20044    /**
20045     * Check if text direction resolution can be done.
20046     *
20047     * @return true if text direction resolution can be done otherwise return false.
20048     */
20049    public boolean canResolveTextDirection() {
20050        switch (getRawTextDirection()) {
20051            case TEXT_DIRECTION_INHERIT:
20052                if (mParent != null) {
20053                    try {
20054                        return mParent.canResolveTextDirection();
20055                    } catch (AbstractMethodError e) {
20056                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20057                                " does not fully implement ViewParent", e);
20058                    }
20059                }
20060                return false;
20061
20062            default:
20063                return true;
20064        }
20065    }
20066
20067    /**
20068     * Reset resolved text direction. Text direction will be resolved during a call to
20069     * {@link #onMeasure(int, int)}.
20070     *
20071     * @hide
20072     */
20073    public void resetResolvedTextDirection() {
20074        // Reset any previous text direction resolution
20075        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
20076        // Set to default value
20077        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20078    }
20079
20080    /**
20081     * @return true if text direction is inherited.
20082     *
20083     * @hide
20084     */
20085    public boolean isTextDirectionInherited() {
20086        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
20087    }
20088
20089    /**
20090     * @return true if text direction is resolved.
20091     */
20092    public boolean isTextDirectionResolved() {
20093        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
20094    }
20095
20096    /**
20097     * Return the value specifying the text alignment or policy that was set with
20098     * {@link #setTextAlignment(int)}.
20099     *
20100     * @return the defined text alignment. It can be one of:
20101     *
20102     * {@link #TEXT_ALIGNMENT_INHERIT},
20103     * {@link #TEXT_ALIGNMENT_GRAVITY},
20104     * {@link #TEXT_ALIGNMENT_CENTER},
20105     * {@link #TEXT_ALIGNMENT_TEXT_START},
20106     * {@link #TEXT_ALIGNMENT_TEXT_END},
20107     * {@link #TEXT_ALIGNMENT_VIEW_START},
20108     * {@link #TEXT_ALIGNMENT_VIEW_END}
20109     *
20110     * @attr ref android.R.styleable#View_textAlignment
20111     *
20112     * @hide
20113     */
20114    @ViewDebug.ExportedProperty(category = "text", mapping = {
20115            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20116            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20117            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20118            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20119            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20120            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20121            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20122    })
20123    @TextAlignment
20124    public int getRawTextAlignment() {
20125        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
20126    }
20127
20128    /**
20129     * Set the text alignment.
20130     *
20131     * @param textAlignment The text alignment to set. Should be one of
20132     *
20133     * {@link #TEXT_ALIGNMENT_INHERIT},
20134     * {@link #TEXT_ALIGNMENT_GRAVITY},
20135     * {@link #TEXT_ALIGNMENT_CENTER},
20136     * {@link #TEXT_ALIGNMENT_TEXT_START},
20137     * {@link #TEXT_ALIGNMENT_TEXT_END},
20138     * {@link #TEXT_ALIGNMENT_VIEW_START},
20139     * {@link #TEXT_ALIGNMENT_VIEW_END}
20140     *
20141     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
20142     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
20143     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
20144     *
20145     * @attr ref android.R.styleable#View_textAlignment
20146     */
20147    public void setTextAlignment(@TextAlignment int textAlignment) {
20148        if (textAlignment != getRawTextAlignment()) {
20149            // Reset the current and resolved text alignment
20150            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
20151            resetResolvedTextAlignment();
20152            // Set the new text alignment
20153            mPrivateFlags2 |=
20154                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
20155            // Do resolution
20156            resolveTextAlignment();
20157            // Notify change
20158            onRtlPropertiesChanged(getLayoutDirection());
20159            // Refresh
20160            requestLayout();
20161            invalidate(true);
20162        }
20163    }
20164
20165    /**
20166     * Return the resolved text alignment.
20167     *
20168     * @return the resolved text alignment. Returns one of:
20169     *
20170     * {@link #TEXT_ALIGNMENT_GRAVITY},
20171     * {@link #TEXT_ALIGNMENT_CENTER},
20172     * {@link #TEXT_ALIGNMENT_TEXT_START},
20173     * {@link #TEXT_ALIGNMENT_TEXT_END},
20174     * {@link #TEXT_ALIGNMENT_VIEW_START},
20175     * {@link #TEXT_ALIGNMENT_VIEW_END}
20176     *
20177     * @attr ref android.R.styleable#View_textAlignment
20178     */
20179    @ViewDebug.ExportedProperty(category = "text", mapping = {
20180            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20181            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20182            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20183            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20184            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20185            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20186            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20187    })
20188    @TextAlignment
20189    public int getTextAlignment() {
20190        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
20191                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
20192    }
20193
20194    /**
20195     * Resolve the text alignment.
20196     *
20197     * @return true if resolution has been done, false otherwise.
20198     *
20199     * @hide
20200     */
20201    public boolean resolveTextAlignment() {
20202        // Reset any previous text alignment resolution
20203        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20204
20205        if (hasRtlSupport()) {
20206            // Set resolved text alignment flag depending on text alignment flag
20207            final int textAlignment = getRawTextAlignment();
20208            switch (textAlignment) {
20209                case TEXT_ALIGNMENT_INHERIT:
20210                    // Check if we can resolve the text alignment
20211                    if (!canResolveTextAlignment()) {
20212                        // We cannot do the resolution if there is no parent so use the default
20213                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20214                        // Resolution will need to happen again later
20215                        return false;
20216                    }
20217
20218                    // Parent has not yet resolved, so we still return the default
20219                    try {
20220                        if (!mParent.isTextAlignmentResolved()) {
20221                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20222                            // Resolution will need to happen again later
20223                            return false;
20224                        }
20225                    } catch (AbstractMethodError e) {
20226                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20227                                " does not fully implement ViewParent", e);
20228                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
20229                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20230                        return true;
20231                    }
20232
20233                    int parentResolvedTextAlignment;
20234                    try {
20235                        parentResolvedTextAlignment = mParent.getTextAlignment();
20236                    } catch (AbstractMethodError e) {
20237                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20238                                " does not fully implement ViewParent", e);
20239                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
20240                    }
20241                    switch (parentResolvedTextAlignment) {
20242                        case TEXT_ALIGNMENT_GRAVITY:
20243                        case TEXT_ALIGNMENT_TEXT_START:
20244                        case TEXT_ALIGNMENT_TEXT_END:
20245                        case TEXT_ALIGNMENT_CENTER:
20246                        case TEXT_ALIGNMENT_VIEW_START:
20247                        case TEXT_ALIGNMENT_VIEW_END:
20248                            // Resolved text alignment is the same as the parent resolved
20249                            // text alignment
20250                            mPrivateFlags2 |=
20251                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20252                            break;
20253                        default:
20254                            // Use default resolved text alignment
20255                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20256                    }
20257                    break;
20258                case TEXT_ALIGNMENT_GRAVITY:
20259                case TEXT_ALIGNMENT_TEXT_START:
20260                case TEXT_ALIGNMENT_TEXT_END:
20261                case TEXT_ALIGNMENT_CENTER:
20262                case TEXT_ALIGNMENT_VIEW_START:
20263                case TEXT_ALIGNMENT_VIEW_END:
20264                    // Resolved text alignment is the same as text alignment
20265                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20266                    break;
20267                default:
20268                    // Use default resolved text alignment
20269                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20270            }
20271        } else {
20272            // Use default resolved text alignment
20273            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20274        }
20275
20276        // Set the resolved
20277        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20278        return true;
20279    }
20280
20281    /**
20282     * Check if text alignment resolution can be done.
20283     *
20284     * @return true if text alignment resolution can be done otherwise return false.
20285     */
20286    public boolean canResolveTextAlignment() {
20287        switch (getRawTextAlignment()) {
20288            case TEXT_DIRECTION_INHERIT:
20289                if (mParent != null) {
20290                    try {
20291                        return mParent.canResolveTextAlignment();
20292                    } catch (AbstractMethodError e) {
20293                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20294                                " does not fully implement ViewParent", e);
20295                    }
20296                }
20297                return false;
20298
20299            default:
20300                return true;
20301        }
20302    }
20303
20304    /**
20305     * Reset resolved text alignment. Text alignment will be resolved during a call to
20306     * {@link #onMeasure(int, int)}.
20307     *
20308     * @hide
20309     */
20310    public void resetResolvedTextAlignment() {
20311        // Reset any previous text alignment resolution
20312        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20313        // Set to default
20314        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20315    }
20316
20317    /**
20318     * @return true if text alignment is inherited.
20319     *
20320     * @hide
20321     */
20322    public boolean isTextAlignmentInherited() {
20323        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20324    }
20325
20326    /**
20327     * @return true if text alignment is resolved.
20328     */
20329    public boolean isTextAlignmentResolved() {
20330        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20331    }
20332
20333    /**
20334     * Generate a value suitable for use in {@link #setId(int)}.
20335     * This value will not collide with ID values generated at build time by aapt for R.id.
20336     *
20337     * @return a generated ID value
20338     */
20339    public static int generateViewId() {
20340        for (;;) {
20341            final int result = sNextGeneratedId.get();
20342            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20343            int newValue = result + 1;
20344            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20345            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20346                return result;
20347            }
20348        }
20349    }
20350
20351    /**
20352     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20353     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20354     *                           a normal View or a ViewGroup with
20355     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20356     * @hide
20357     */
20358    public void captureTransitioningViews(List<View> transitioningViews) {
20359        if (getVisibility() == View.VISIBLE) {
20360            transitioningViews.add(this);
20361        }
20362    }
20363
20364    /**
20365     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20366     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20367     * @hide
20368     */
20369    public void findNamedViews(Map<String, View> namedElements) {
20370        if (getVisibility() == VISIBLE || mGhostView != null) {
20371            String transitionName = getTransitionName();
20372            if (transitionName != null) {
20373                namedElements.put(transitionName, this);
20374            }
20375        }
20376    }
20377
20378    //
20379    // Properties
20380    //
20381    /**
20382     * A Property wrapper around the <code>alpha</code> functionality handled by the
20383     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20384     */
20385    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20386        @Override
20387        public void setValue(View object, float value) {
20388            object.setAlpha(value);
20389        }
20390
20391        @Override
20392        public Float get(View object) {
20393            return object.getAlpha();
20394        }
20395    };
20396
20397    /**
20398     * A Property wrapper around the <code>translationX</code> functionality handled by the
20399     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20400     */
20401    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20402        @Override
20403        public void setValue(View object, float value) {
20404            object.setTranslationX(value);
20405        }
20406
20407                @Override
20408        public Float get(View object) {
20409            return object.getTranslationX();
20410        }
20411    };
20412
20413    /**
20414     * A Property wrapper around the <code>translationY</code> functionality handled by the
20415     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20416     */
20417    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20418        @Override
20419        public void setValue(View object, float value) {
20420            object.setTranslationY(value);
20421        }
20422
20423        @Override
20424        public Float get(View object) {
20425            return object.getTranslationY();
20426        }
20427    };
20428
20429    /**
20430     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20431     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20432     */
20433    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20434        @Override
20435        public void setValue(View object, float value) {
20436            object.setTranslationZ(value);
20437        }
20438
20439        @Override
20440        public Float get(View object) {
20441            return object.getTranslationZ();
20442        }
20443    };
20444
20445    /**
20446     * A Property wrapper around the <code>x</code> functionality handled by the
20447     * {@link View#setX(float)} and {@link View#getX()} methods.
20448     */
20449    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20450        @Override
20451        public void setValue(View object, float value) {
20452            object.setX(value);
20453        }
20454
20455        @Override
20456        public Float get(View object) {
20457            return object.getX();
20458        }
20459    };
20460
20461    /**
20462     * A Property wrapper around the <code>y</code> functionality handled by the
20463     * {@link View#setY(float)} and {@link View#getY()} methods.
20464     */
20465    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20466        @Override
20467        public void setValue(View object, float value) {
20468            object.setY(value);
20469        }
20470
20471        @Override
20472        public Float get(View object) {
20473            return object.getY();
20474        }
20475    };
20476
20477    /**
20478     * A Property wrapper around the <code>z</code> functionality handled by the
20479     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20480     */
20481    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20482        @Override
20483        public void setValue(View object, float value) {
20484            object.setZ(value);
20485        }
20486
20487        @Override
20488        public Float get(View object) {
20489            return object.getZ();
20490        }
20491    };
20492
20493    /**
20494     * A Property wrapper around the <code>rotation</code> functionality handled by the
20495     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20496     */
20497    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20498        @Override
20499        public void setValue(View object, float value) {
20500            object.setRotation(value);
20501        }
20502
20503        @Override
20504        public Float get(View object) {
20505            return object.getRotation();
20506        }
20507    };
20508
20509    /**
20510     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20511     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20512     */
20513    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20514        @Override
20515        public void setValue(View object, float value) {
20516            object.setRotationX(value);
20517        }
20518
20519        @Override
20520        public Float get(View object) {
20521            return object.getRotationX();
20522        }
20523    };
20524
20525    /**
20526     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20527     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20528     */
20529    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20530        @Override
20531        public void setValue(View object, float value) {
20532            object.setRotationY(value);
20533        }
20534
20535        @Override
20536        public Float get(View object) {
20537            return object.getRotationY();
20538        }
20539    };
20540
20541    /**
20542     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20543     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20544     */
20545    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20546        @Override
20547        public void setValue(View object, float value) {
20548            object.setScaleX(value);
20549        }
20550
20551        @Override
20552        public Float get(View object) {
20553            return object.getScaleX();
20554        }
20555    };
20556
20557    /**
20558     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20559     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20560     */
20561    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20562        @Override
20563        public void setValue(View object, float value) {
20564            object.setScaleY(value);
20565        }
20566
20567        @Override
20568        public Float get(View object) {
20569            return object.getScaleY();
20570        }
20571    };
20572
20573    /**
20574     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20575     * Each MeasureSpec represents a requirement for either the width or the height.
20576     * A MeasureSpec is comprised of a size and a mode. There are three possible
20577     * modes:
20578     * <dl>
20579     * <dt>UNSPECIFIED</dt>
20580     * <dd>
20581     * The parent has not imposed any constraint on the child. It can be whatever size
20582     * it wants.
20583     * </dd>
20584     *
20585     * <dt>EXACTLY</dt>
20586     * <dd>
20587     * The parent has determined an exact size for the child. The child is going to be
20588     * given those bounds regardless of how big it wants to be.
20589     * </dd>
20590     *
20591     * <dt>AT_MOST</dt>
20592     * <dd>
20593     * The child can be as large as it wants up to the specified size.
20594     * </dd>
20595     * </dl>
20596     *
20597     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20598     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20599     */
20600    public static class MeasureSpec {
20601        private static final int MODE_SHIFT = 30;
20602        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
20603
20604        /**
20605         * Measure specification mode: The parent has not imposed any constraint
20606         * on the child. It can be whatever size it wants.
20607         */
20608        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
20609
20610        /**
20611         * Measure specification mode: The parent has determined an exact size
20612         * for the child. The child is going to be given those bounds regardless
20613         * of how big it wants to be.
20614         */
20615        public static final int EXACTLY     = 1 << MODE_SHIFT;
20616
20617        /**
20618         * Measure specification mode: The child can be as large as it wants up
20619         * to the specified size.
20620         */
20621        public static final int AT_MOST     = 2 << MODE_SHIFT;
20622
20623        /**
20624         * Creates a measure specification based on the supplied size and mode.
20625         *
20626         * The mode must always be one of the following:
20627         * <ul>
20628         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
20629         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
20630         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
20631         * </ul>
20632         *
20633         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
20634         * implementation was such that the order of arguments did not matter
20635         * and overflow in either value could impact the resulting MeasureSpec.
20636         * {@link android.widget.RelativeLayout} was affected by this bug.
20637         * Apps targeting API levels greater than 17 will get the fixed, more strict
20638         * behavior.</p>
20639         *
20640         * @param size the size of the measure specification
20641         * @param mode the mode of the measure specification
20642         * @return the measure specification based on size and mode
20643         */
20644        public static int makeMeasureSpec(int size, int mode) {
20645            if (sUseBrokenMakeMeasureSpec) {
20646                return size + mode;
20647            } else {
20648                return (size & ~MODE_MASK) | (mode & MODE_MASK);
20649            }
20650        }
20651
20652        /**
20653         * Extracts the mode from the supplied measure specification.
20654         *
20655         * @param measureSpec the measure specification to extract the mode from
20656         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
20657         *         {@link android.view.View.MeasureSpec#AT_MOST} or
20658         *         {@link android.view.View.MeasureSpec#EXACTLY}
20659         */
20660        public static int getMode(int measureSpec) {
20661            return (measureSpec & MODE_MASK);
20662        }
20663
20664        /**
20665         * Extracts the size from the supplied measure specification.
20666         *
20667         * @param measureSpec the measure specification to extract the size from
20668         * @return the size in pixels defined in the supplied measure specification
20669         */
20670        public static int getSize(int measureSpec) {
20671            return (measureSpec & ~MODE_MASK);
20672        }
20673
20674        static int adjust(int measureSpec, int delta) {
20675            final int mode = getMode(measureSpec);
20676            int size = getSize(measureSpec);
20677            if (mode == UNSPECIFIED) {
20678                // No need to adjust size for UNSPECIFIED mode.
20679                return makeMeasureSpec(size, UNSPECIFIED);
20680            }
20681            size += delta;
20682            if (size < 0) {
20683                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
20684                        ") spec: " + toString(measureSpec) + " delta: " + delta);
20685                size = 0;
20686            }
20687            return makeMeasureSpec(size, mode);
20688        }
20689
20690        /**
20691         * Returns a String representation of the specified measure
20692         * specification.
20693         *
20694         * @param measureSpec the measure specification to convert to a String
20695         * @return a String with the following format: "MeasureSpec: MODE SIZE"
20696         */
20697        public static String toString(int measureSpec) {
20698            int mode = getMode(measureSpec);
20699            int size = getSize(measureSpec);
20700
20701            StringBuilder sb = new StringBuilder("MeasureSpec: ");
20702
20703            if (mode == UNSPECIFIED)
20704                sb.append("UNSPECIFIED ");
20705            else if (mode == EXACTLY)
20706                sb.append("EXACTLY ");
20707            else if (mode == AT_MOST)
20708                sb.append("AT_MOST ");
20709            else
20710                sb.append(mode).append(" ");
20711
20712            sb.append(size);
20713            return sb.toString();
20714        }
20715    }
20716
20717    private final class CheckForLongPress implements Runnable {
20718        private int mOriginalWindowAttachCount;
20719
20720        @Override
20721        public void run() {
20722            if (isPressed() && (mParent != null)
20723                    && mOriginalWindowAttachCount == mWindowAttachCount) {
20724                if (performLongClick()) {
20725                    mHasPerformedLongPress = true;
20726                }
20727            }
20728        }
20729
20730        public void rememberWindowAttachCount() {
20731            mOriginalWindowAttachCount = mWindowAttachCount;
20732        }
20733    }
20734
20735    private final class CheckForTap implements Runnable {
20736        public float x;
20737        public float y;
20738
20739        @Override
20740        public void run() {
20741            mPrivateFlags &= ~PFLAG_PREPRESSED;
20742            setPressed(true, x, y);
20743            checkForLongClick(ViewConfiguration.getTapTimeout());
20744        }
20745    }
20746
20747    private final class PerformClick implements Runnable {
20748        @Override
20749        public void run() {
20750            performClick();
20751        }
20752    }
20753
20754    /** @hide */
20755    public void hackTurnOffWindowResizeAnim(boolean off) {
20756        mAttachInfo.mTurnOffWindowResizeAnim = off;
20757    }
20758
20759    /**
20760     * This method returns a ViewPropertyAnimator object, which can be used to animate
20761     * specific properties on this View.
20762     *
20763     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
20764     */
20765    public ViewPropertyAnimator animate() {
20766        if (mAnimator == null) {
20767            mAnimator = new ViewPropertyAnimator(this);
20768        }
20769        return mAnimator;
20770    }
20771
20772    /**
20773     * Sets the name of the View to be used to identify Views in Transitions.
20774     * Names should be unique in the View hierarchy.
20775     *
20776     * @param transitionName The name of the View to uniquely identify it for Transitions.
20777     */
20778    public final void setTransitionName(String transitionName) {
20779        mTransitionName = transitionName;
20780    }
20781
20782    /**
20783     * Returns the name of the View to be used to identify Views in Transitions.
20784     * Names should be unique in the View hierarchy.
20785     *
20786     * <p>This returns null if the View has not been given a name.</p>
20787     *
20788     * @return The name used of the View to be used to identify Views in Transitions or null
20789     * if no name has been given.
20790     */
20791    @ViewDebug.ExportedProperty
20792    public String getTransitionName() {
20793        return mTransitionName;
20794    }
20795
20796    /**
20797     * Interface definition for a callback to be invoked when a hardware key event is
20798     * dispatched to this view. The callback will be invoked before the key event is
20799     * given to the view. This is only useful for hardware keyboards; a software input
20800     * method has no obligation to trigger this listener.
20801     */
20802    public interface OnKeyListener {
20803        /**
20804         * Called when a hardware key is dispatched to a view. This allows listeners to
20805         * get a chance to respond before the target view.
20806         * <p>Key presses in software keyboards will generally NOT trigger this method,
20807         * although some may elect to do so in some situations. Do not assume a
20808         * software input method has to be key-based; even if it is, it may use key presses
20809         * in a different way than you expect, so there is no way to reliably catch soft
20810         * input key presses.
20811         *
20812         * @param v The view the key has been dispatched to.
20813         * @param keyCode The code for the physical key that was pressed
20814         * @param event The KeyEvent object containing full information about
20815         *        the event.
20816         * @return True if the listener has consumed the event, false otherwise.
20817         */
20818        boolean onKey(View v, int keyCode, KeyEvent event);
20819    }
20820
20821    /**
20822     * Interface definition for a callback to be invoked when a touch event is
20823     * dispatched to this view. The callback will be invoked before the touch
20824     * event is given to the view.
20825     */
20826    public interface OnTouchListener {
20827        /**
20828         * Called when a touch event is dispatched to a view. This allows listeners to
20829         * get a chance to respond before the target view.
20830         *
20831         * @param v The view the touch event has been dispatched to.
20832         * @param event The MotionEvent object containing full information about
20833         *        the event.
20834         * @return True if the listener has consumed the event, false otherwise.
20835         */
20836        boolean onTouch(View v, MotionEvent event);
20837    }
20838
20839    /**
20840     * Interface definition for a callback to be invoked when a hover event is
20841     * dispatched to this view. The callback will be invoked before the hover
20842     * event is given to the view.
20843     */
20844    public interface OnHoverListener {
20845        /**
20846         * Called when a hover event is dispatched to a view. This allows listeners to
20847         * get a chance to respond before the target view.
20848         *
20849         * @param v The view the hover event has been dispatched to.
20850         * @param event The MotionEvent object containing full information about
20851         *        the event.
20852         * @return True if the listener has consumed the event, false otherwise.
20853         */
20854        boolean onHover(View v, MotionEvent event);
20855    }
20856
20857    /**
20858     * Interface definition for a callback to be invoked when a generic motion event is
20859     * dispatched to this view. The callback will be invoked before the generic motion
20860     * event is given to the view.
20861     */
20862    public interface OnGenericMotionListener {
20863        /**
20864         * Called when a generic motion event is dispatched to a view. This allows listeners to
20865         * get a chance to respond before the target view.
20866         *
20867         * @param v The view the generic motion event has been dispatched to.
20868         * @param event The MotionEvent object containing full information about
20869         *        the event.
20870         * @return True if the listener has consumed the event, false otherwise.
20871         */
20872        boolean onGenericMotion(View v, MotionEvent event);
20873    }
20874
20875    /**
20876     * Interface definition for a callback to be invoked when a view has been clicked and held.
20877     */
20878    public interface OnLongClickListener {
20879        /**
20880         * Called when a view has been clicked and held.
20881         *
20882         * @param v The view that was clicked and held.
20883         *
20884         * @return true if the callback consumed the long click, false otherwise.
20885         */
20886        boolean onLongClick(View v);
20887    }
20888
20889    /**
20890     * Interface definition for a callback to be invoked when a drag is being dispatched
20891     * to this view.  The callback will be invoked before the hosting view's own
20892     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20893     * onDrag(event) behavior, it should return 'false' from this callback.
20894     *
20895     * <div class="special reference">
20896     * <h3>Developer Guides</h3>
20897     * <p>For a guide to implementing drag and drop features, read the
20898     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20899     * </div>
20900     */
20901    public interface OnDragListener {
20902        /**
20903         * Called when a drag event is dispatched to a view. This allows listeners
20904         * to get a chance to override base View behavior.
20905         *
20906         * @param v The View that received the drag event.
20907         * @param event The {@link android.view.DragEvent} object for the drag event.
20908         * @return {@code true} if the drag event was handled successfully, or {@code false}
20909         * if the drag event was not handled. Note that {@code false} will trigger the View
20910         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20911         */
20912        boolean onDrag(View v, DragEvent event);
20913    }
20914
20915    /**
20916     * Interface definition for a callback to be invoked when the focus state of
20917     * a view changed.
20918     */
20919    public interface OnFocusChangeListener {
20920        /**
20921         * Called when the focus state of a view has changed.
20922         *
20923         * @param v The view whose state has changed.
20924         * @param hasFocus The new focus state of v.
20925         */
20926        void onFocusChange(View v, boolean hasFocus);
20927    }
20928
20929    /**
20930     * Interface definition for a callback to be invoked when a view is clicked.
20931     */
20932    public interface OnClickListener {
20933        /**
20934         * Called when a view has been clicked.
20935         *
20936         * @param v The view that was clicked.
20937         */
20938        void onClick(View v);
20939    }
20940
20941    /**
20942     * Interface definition for a callback to be invoked when a view is touched with a stylus while
20943     * the stylus button is pressed.
20944     */
20945    public interface OnStylusButtonPressListener {
20946        /**
20947         * Called when a view is touched with a stylus while the stylus button is pressed.
20948         *
20949         * @param v The view that was touched.
20950         * @return true if the callback consumed the stylus button press, false otherwise.
20951         */
20952        boolean onStylusButtonPress(View v);
20953    }
20954
20955    /**
20956     * Interface definition for a callback to be invoked when the context menu
20957     * for this view is being built.
20958     */
20959    public interface OnCreateContextMenuListener {
20960        /**
20961         * Called when the context menu for this view is being built. It is not
20962         * safe to hold onto the menu after this method returns.
20963         *
20964         * @param menu The context menu that is being built
20965         * @param v The view for which the context menu is being built
20966         * @param menuInfo Extra information about the item for which the
20967         *            context menu should be shown. This information will vary
20968         *            depending on the class of v.
20969         */
20970        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20971    }
20972
20973    /**
20974     * Interface definition for a callback to be invoked when the status bar changes
20975     * visibility.  This reports <strong>global</strong> changes to the system UI
20976     * state, not what the application is requesting.
20977     *
20978     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20979     */
20980    public interface OnSystemUiVisibilityChangeListener {
20981        /**
20982         * Called when the status bar changes visibility because of a call to
20983         * {@link View#setSystemUiVisibility(int)}.
20984         *
20985         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20986         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20987         * This tells you the <strong>global</strong> state of these UI visibility
20988         * flags, not what your app is currently applying.
20989         */
20990        public void onSystemUiVisibilityChange(int visibility);
20991    }
20992
20993    /**
20994     * Interface definition for a callback to be invoked when this view is attached
20995     * or detached from its window.
20996     */
20997    public interface OnAttachStateChangeListener {
20998        /**
20999         * Called when the view is attached to a window.
21000         * @param v The view that was attached
21001         */
21002        public void onViewAttachedToWindow(View v);
21003        /**
21004         * Called when the view is detached from a window.
21005         * @param v The view that was detached
21006         */
21007        public void onViewDetachedFromWindow(View v);
21008    }
21009
21010    /**
21011     * Listener for applying window insets on a view in a custom way.
21012     *
21013     * <p>Apps may choose to implement this interface if they want to apply custom policy
21014     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
21015     * is set, its
21016     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
21017     * method will be called instead of the View's own
21018     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
21019     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
21020     * the View's normal behavior as part of its own.</p>
21021     */
21022    public interface OnApplyWindowInsetsListener {
21023        /**
21024         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
21025         * on a View, this listener method will be called instead of the view's own
21026         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
21027         *
21028         * @param v The view applying window insets
21029         * @param insets The insets to apply
21030         * @return The insets supplied, minus any insets that were consumed
21031         */
21032        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
21033    }
21034
21035    private final class UnsetPressedState implements Runnable {
21036        @Override
21037        public void run() {
21038            setPressed(false);
21039        }
21040    }
21041
21042    /**
21043     * Base class for derived classes that want to save and restore their own
21044     * state in {@link android.view.View#onSaveInstanceState()}.
21045     */
21046    public static class BaseSavedState extends AbsSavedState {
21047        String mStartActivityRequestWhoSaved;
21048
21049        /**
21050         * Constructor used when reading from a parcel. Reads the state of the superclass.
21051         *
21052         * @param source
21053         */
21054        public BaseSavedState(Parcel source) {
21055            super(source);
21056            mStartActivityRequestWhoSaved = source.readString();
21057        }
21058
21059        /**
21060         * Constructor called by derived classes when creating their SavedState objects
21061         *
21062         * @param superState The state of the superclass of this view
21063         */
21064        public BaseSavedState(Parcelable superState) {
21065            super(superState);
21066        }
21067
21068        @Override
21069        public void writeToParcel(Parcel out, int flags) {
21070            super.writeToParcel(out, flags);
21071            out.writeString(mStartActivityRequestWhoSaved);
21072        }
21073
21074        public static final Parcelable.Creator<BaseSavedState> CREATOR =
21075                new Parcelable.Creator<BaseSavedState>() {
21076            public BaseSavedState createFromParcel(Parcel in) {
21077                return new BaseSavedState(in);
21078            }
21079
21080            public BaseSavedState[] newArray(int size) {
21081                return new BaseSavedState[size];
21082            }
21083        };
21084    }
21085
21086    /**
21087     * A set of information given to a view when it is attached to its parent
21088     * window.
21089     */
21090    final static class AttachInfo {
21091        interface Callbacks {
21092            void playSoundEffect(int effectId);
21093            boolean performHapticFeedback(int effectId, boolean always);
21094        }
21095
21096        /**
21097         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
21098         * to a Handler. This class contains the target (View) to invalidate and
21099         * the coordinates of the dirty rectangle.
21100         *
21101         * For performance purposes, this class also implements a pool of up to
21102         * POOL_LIMIT objects that get reused. This reduces memory allocations
21103         * whenever possible.
21104         */
21105        static class InvalidateInfo {
21106            private static final int POOL_LIMIT = 10;
21107
21108            private static final SynchronizedPool<InvalidateInfo> sPool =
21109                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
21110
21111            View target;
21112
21113            int left;
21114            int top;
21115            int right;
21116            int bottom;
21117
21118            public static InvalidateInfo obtain() {
21119                InvalidateInfo instance = sPool.acquire();
21120                return (instance != null) ? instance : new InvalidateInfo();
21121            }
21122
21123            public void recycle() {
21124                target = null;
21125                sPool.release(this);
21126            }
21127        }
21128
21129        final IWindowSession mSession;
21130
21131        final IWindow mWindow;
21132
21133        final IBinder mWindowToken;
21134
21135        final Display mDisplay;
21136
21137        final Callbacks mRootCallbacks;
21138
21139        IWindowId mIWindowId;
21140        WindowId mWindowId;
21141
21142        /**
21143         * The top view of the hierarchy.
21144         */
21145        View mRootView;
21146
21147        IBinder mPanelParentWindowToken;
21148
21149        boolean mHardwareAccelerated;
21150        boolean mHardwareAccelerationRequested;
21151        HardwareRenderer mHardwareRenderer;
21152        List<RenderNode> mPendingAnimatingRenderNodes;
21153
21154        /**
21155         * The state of the display to which the window is attached, as reported
21156         * by {@link Display#getState()}.  Note that the display state constants
21157         * declared by {@link Display} do not exactly line up with the screen state
21158         * constants declared by {@link View} (there are more display states than
21159         * screen states).
21160         */
21161        int mDisplayState = Display.STATE_UNKNOWN;
21162
21163        /**
21164         * Scale factor used by the compatibility mode
21165         */
21166        float mApplicationScale;
21167
21168        /**
21169         * Indicates whether the application is in compatibility mode
21170         */
21171        boolean mScalingRequired;
21172
21173        /**
21174         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
21175         */
21176        boolean mTurnOffWindowResizeAnim;
21177
21178        /**
21179         * Left position of this view's window
21180         */
21181        int mWindowLeft;
21182
21183        /**
21184         * Top position of this view's window
21185         */
21186        int mWindowTop;
21187
21188        /**
21189         * Indicates whether views need to use 32-bit drawing caches
21190         */
21191        boolean mUse32BitDrawingCache;
21192
21193        /**
21194         * For windows that are full-screen but using insets to layout inside
21195         * of the screen areas, these are the current insets to appear inside
21196         * the overscan area of the display.
21197         */
21198        final Rect mOverscanInsets = new Rect();
21199
21200        /**
21201         * For windows that are full-screen but using insets to layout inside
21202         * of the screen decorations, these are the current insets for the
21203         * content of the window.
21204         */
21205        final Rect mContentInsets = new Rect();
21206
21207        /**
21208         * For windows that are full-screen but using insets to layout inside
21209         * of the screen decorations, these are the current insets for the
21210         * actual visible parts of the window.
21211         */
21212        final Rect mVisibleInsets = new Rect();
21213
21214        /**
21215         * For windows that are full-screen but using insets to layout inside
21216         * of the screen decorations, these are the current insets for the
21217         * stable system windows.
21218         */
21219        final Rect mStableInsets = new Rect();
21220
21221        /**
21222         * The internal insets given by this window.  This value is
21223         * supplied by the client (through
21224         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
21225         * be given to the window manager when changed to be used in laying
21226         * out windows behind it.
21227         */
21228        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
21229                = new ViewTreeObserver.InternalInsetsInfo();
21230
21231        /**
21232         * Set to true when mGivenInternalInsets is non-empty.
21233         */
21234        boolean mHasNonEmptyGivenInternalInsets;
21235
21236        /**
21237         * All views in the window's hierarchy that serve as scroll containers,
21238         * used to determine if the window can be resized or must be panned
21239         * to adjust for a soft input area.
21240         */
21241        final ArrayList<View> mScrollContainers = new ArrayList<View>();
21242
21243        final KeyEvent.DispatcherState mKeyDispatchState
21244                = new KeyEvent.DispatcherState();
21245
21246        /**
21247         * Indicates whether the view's window currently has the focus.
21248         */
21249        boolean mHasWindowFocus;
21250
21251        /**
21252         * The current visibility of the window.
21253         */
21254        int mWindowVisibility;
21255
21256        /**
21257         * Indicates the time at which drawing started to occur.
21258         */
21259        long mDrawingTime;
21260
21261        /**
21262         * Indicates whether or not ignoring the DIRTY_MASK flags.
21263         */
21264        boolean mIgnoreDirtyState;
21265
21266        /**
21267         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21268         * to avoid clearing that flag prematurely.
21269         */
21270        boolean mSetIgnoreDirtyState = false;
21271
21272        /**
21273         * Indicates whether the view's window is currently in touch mode.
21274         */
21275        boolean mInTouchMode;
21276
21277        /**
21278         * Indicates whether the view has requested unbuffered input dispatching for the current
21279         * event stream.
21280         */
21281        boolean mUnbufferedDispatchRequested;
21282
21283        /**
21284         * Indicates that ViewAncestor should trigger a global layout change
21285         * the next time it performs a traversal
21286         */
21287        boolean mRecomputeGlobalAttributes;
21288
21289        /**
21290         * Always report new attributes at next traversal.
21291         */
21292        boolean mForceReportNewAttributes;
21293
21294        /**
21295         * Set during a traveral if any views want to keep the screen on.
21296         */
21297        boolean mKeepScreenOn;
21298
21299        /**
21300         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21301         */
21302        int mSystemUiVisibility;
21303
21304        /**
21305         * Hack to force certain system UI visibility flags to be cleared.
21306         */
21307        int mDisabledSystemUiVisibility;
21308
21309        /**
21310         * Last global system UI visibility reported by the window manager.
21311         */
21312        int mGlobalSystemUiVisibility;
21313
21314        /**
21315         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21316         * attached.
21317         */
21318        boolean mHasSystemUiListeners;
21319
21320        /**
21321         * Set if the window has requested to extend into the overscan region
21322         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21323         */
21324        boolean mOverscanRequested;
21325
21326        /**
21327         * Set if the visibility of any views has changed.
21328         */
21329        boolean mViewVisibilityChanged;
21330
21331        /**
21332         * Set to true if a view has been scrolled.
21333         */
21334        boolean mViewScrollChanged;
21335
21336        /**
21337         * Set to true if high contrast mode enabled
21338         */
21339        boolean mHighContrastText;
21340
21341        /**
21342         * Global to the view hierarchy used as a temporary for dealing with
21343         * x/y points in the transparent region computations.
21344         */
21345        final int[] mTransparentLocation = new int[2];
21346
21347        /**
21348         * Global to the view hierarchy used as a temporary for dealing with
21349         * x/y points in the ViewGroup.invalidateChild implementation.
21350         */
21351        final int[] mInvalidateChildLocation = new int[2];
21352
21353        /**
21354         * Global to the view hierarchy used as a temporary for dealng with
21355         * computing absolute on-screen location.
21356         */
21357        final int[] mTmpLocation = new int[2];
21358
21359        /**
21360         * Global to the view hierarchy used as a temporary for dealing with
21361         * x/y location when view is transformed.
21362         */
21363        final float[] mTmpTransformLocation = new float[2];
21364
21365        /**
21366         * The view tree observer used to dispatch global events like
21367         * layout, pre-draw, touch mode change, etc.
21368         */
21369        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21370
21371        /**
21372         * A Canvas used by the view hierarchy to perform bitmap caching.
21373         */
21374        Canvas mCanvas;
21375
21376        /**
21377         * The view root impl.
21378         */
21379        final ViewRootImpl mViewRootImpl;
21380
21381        /**
21382         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21383         * handler can be used to pump events in the UI events queue.
21384         */
21385        final Handler mHandler;
21386
21387        /**
21388         * Temporary for use in computing invalidate rectangles while
21389         * calling up the hierarchy.
21390         */
21391        final Rect mTmpInvalRect = new Rect();
21392
21393        /**
21394         * Temporary for use in computing hit areas with transformed views
21395         */
21396        final RectF mTmpTransformRect = new RectF();
21397
21398        /**
21399         * Temporary for use in computing hit areas with transformed views
21400         */
21401        final RectF mTmpTransformRect1 = new RectF();
21402
21403        /**
21404         * Temporary list of rectanges.
21405         */
21406        final List<RectF> mTmpRectList = new ArrayList<>();
21407
21408        /**
21409         * Temporary for use in transforming invalidation rect
21410         */
21411        final Matrix mTmpMatrix = new Matrix();
21412
21413        /**
21414         * Temporary for use in transforming invalidation rect
21415         */
21416        final Transformation mTmpTransformation = new Transformation();
21417
21418        /**
21419         * Temporary for use in querying outlines from OutlineProviders
21420         */
21421        final Outline mTmpOutline = new Outline();
21422
21423        /**
21424         * Temporary list for use in collecting focusable descendents of a view.
21425         */
21426        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21427
21428        /**
21429         * The id of the window for accessibility purposes.
21430         */
21431        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21432
21433        /**
21434         * Flags related to accessibility processing.
21435         *
21436         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21437         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21438         */
21439        int mAccessibilityFetchFlags;
21440
21441        /**
21442         * The drawable for highlighting accessibility focus.
21443         */
21444        Drawable mAccessibilityFocusDrawable;
21445
21446        /**
21447         * Show where the margins, bounds and layout bounds are for each view.
21448         */
21449        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21450
21451        /**
21452         * Point used to compute visible regions.
21453         */
21454        final Point mPoint = new Point();
21455
21456        /**
21457         * Used to track which View originated a requestLayout() call, used when
21458         * requestLayout() is called during layout.
21459         */
21460        View mViewRequestingLayout;
21461
21462        /**
21463         * Creates a new set of attachment information with the specified
21464         * events handler and thread.
21465         *
21466         * @param handler the events handler the view must use
21467         */
21468        AttachInfo(IWindowSession session, IWindow window, Display display,
21469                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21470            mSession = session;
21471            mWindow = window;
21472            mWindowToken = window.asBinder();
21473            mDisplay = display;
21474            mViewRootImpl = viewRootImpl;
21475            mHandler = handler;
21476            mRootCallbacks = effectPlayer;
21477        }
21478    }
21479
21480    /**
21481     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21482     * is supported. This avoids keeping too many unused fields in most
21483     * instances of View.</p>
21484     */
21485    private static class ScrollabilityCache implements Runnable {
21486
21487        /**
21488         * Scrollbars are not visible
21489         */
21490        public static final int OFF = 0;
21491
21492        /**
21493         * Scrollbars are visible
21494         */
21495        public static final int ON = 1;
21496
21497        /**
21498         * Scrollbars are fading away
21499         */
21500        public static final int FADING = 2;
21501
21502        public boolean fadeScrollBars;
21503
21504        public int fadingEdgeLength;
21505        public int scrollBarDefaultDelayBeforeFade;
21506        public int scrollBarFadeDuration;
21507
21508        public int scrollBarSize;
21509        public ScrollBarDrawable scrollBar;
21510        public float[] interpolatorValues;
21511        public View host;
21512
21513        public final Paint paint;
21514        public final Matrix matrix;
21515        public Shader shader;
21516
21517        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21518
21519        private static final float[] OPAQUE = { 255 };
21520        private static final float[] TRANSPARENT = { 0.0f };
21521
21522        /**
21523         * When fading should start. This time moves into the future every time
21524         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21525         */
21526        public long fadeStartTime;
21527
21528
21529        /**
21530         * The current state of the scrollbars: ON, OFF, or FADING
21531         */
21532        public int state = OFF;
21533
21534        private int mLastColor;
21535
21536        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21537            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21538            scrollBarSize = configuration.getScaledScrollBarSize();
21539            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21540            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21541
21542            paint = new Paint();
21543            matrix = new Matrix();
21544            // use use a height of 1, and then wack the matrix each time we
21545            // actually use it.
21546            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21547            paint.setShader(shader);
21548            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21549
21550            this.host = host;
21551        }
21552
21553        public void setFadeColor(int color) {
21554            if (color != mLastColor) {
21555                mLastColor = color;
21556
21557                if (color != 0) {
21558                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21559                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21560                    paint.setShader(shader);
21561                    // Restore the default transfer mode (src_over)
21562                    paint.setXfermode(null);
21563                } else {
21564                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21565                    paint.setShader(shader);
21566                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21567                }
21568            }
21569        }
21570
21571        public void run() {
21572            long now = AnimationUtils.currentAnimationTimeMillis();
21573            if (now >= fadeStartTime) {
21574
21575                // the animation fades the scrollbars out by changing
21576                // the opacity (alpha) from fully opaque to fully
21577                // transparent
21578                int nextFrame = (int) now;
21579                int framesCount = 0;
21580
21581                Interpolator interpolator = scrollBarInterpolator;
21582
21583                // Start opaque
21584                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21585
21586                // End transparent
21587                nextFrame += scrollBarFadeDuration;
21588                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
21589
21590                state = FADING;
21591
21592                // Kick off the fade animation
21593                host.invalidate(true);
21594            }
21595        }
21596    }
21597
21598    /**
21599     * Resuable callback for sending
21600     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
21601     */
21602    private class SendViewScrolledAccessibilityEvent implements Runnable {
21603        public volatile boolean mIsPending;
21604
21605        public void run() {
21606            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
21607            mIsPending = false;
21608        }
21609    }
21610
21611    /**
21612     * <p>
21613     * This class represents a delegate that can be registered in a {@link View}
21614     * to enhance accessibility support via composition rather via inheritance.
21615     * It is specifically targeted to widget developers that extend basic View
21616     * classes i.e. classes in package android.view, that would like their
21617     * applications to be backwards compatible.
21618     * </p>
21619     * <div class="special reference">
21620     * <h3>Developer Guides</h3>
21621     * <p>For more information about making applications accessible, read the
21622     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
21623     * developer guide.</p>
21624     * </div>
21625     * <p>
21626     * A scenario in which a developer would like to use an accessibility delegate
21627     * is overriding a method introduced in a later API version then the minimal API
21628     * version supported by the application. For example, the method
21629     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
21630     * in API version 4 when the accessibility APIs were first introduced. If a
21631     * developer would like his application to run on API version 4 devices (assuming
21632     * all other APIs used by the application are version 4 or lower) and take advantage
21633     * of this method, instead of overriding the method which would break the application's
21634     * backwards compatibility, he can override the corresponding method in this
21635     * delegate and register the delegate in the target View if the API version of
21636     * the system is high enough i.e. the API version is same or higher to the API
21637     * version that introduced
21638     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
21639     * </p>
21640     * <p>
21641     * Here is an example implementation:
21642     * </p>
21643     * <code><pre><p>
21644     * if (Build.VERSION.SDK_INT >= 14) {
21645     *     // If the API version is equal of higher than the version in
21646     *     // which onInitializeAccessibilityNodeInfo was introduced we
21647     *     // register a delegate with a customized implementation.
21648     *     View view = findViewById(R.id.view_id);
21649     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
21650     *         public void onInitializeAccessibilityNodeInfo(View host,
21651     *                 AccessibilityNodeInfo info) {
21652     *             // Let the default implementation populate the info.
21653     *             super.onInitializeAccessibilityNodeInfo(host, info);
21654     *             // Set some other information.
21655     *             info.setEnabled(host.isEnabled());
21656     *         }
21657     *     });
21658     * }
21659     * </code></pre></p>
21660     * <p>
21661     * This delegate contains methods that correspond to the accessibility methods
21662     * in View. If a delegate has been specified the implementation in View hands
21663     * off handling to the corresponding method in this delegate. The default
21664     * implementation the delegate methods behaves exactly as the corresponding
21665     * method in View for the case of no accessibility delegate been set. Hence,
21666     * to customize the behavior of a View method, clients can override only the
21667     * corresponding delegate method without altering the behavior of the rest
21668     * accessibility related methods of the host view.
21669     * </p>
21670     */
21671    public static class AccessibilityDelegate {
21672
21673        /**
21674         * Sends an accessibility event of the given type. If accessibility is not
21675         * enabled this method has no effect.
21676         * <p>
21677         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
21678         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
21679         * been set.
21680         * </p>
21681         *
21682         * @param host The View hosting the delegate.
21683         * @param eventType The type of the event to send.
21684         *
21685         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
21686         */
21687        public void sendAccessibilityEvent(View host, int eventType) {
21688            host.sendAccessibilityEventInternal(eventType);
21689        }
21690
21691        /**
21692         * Performs the specified accessibility action on the view. For
21693         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
21694         * <p>
21695         * The default implementation behaves as
21696         * {@link View#performAccessibilityAction(int, Bundle)
21697         *  View#performAccessibilityAction(int, Bundle)} for the case of
21698         *  no accessibility delegate been set.
21699         * </p>
21700         *
21701         * @param action The action to perform.
21702         * @return Whether the action was performed.
21703         *
21704         * @see View#performAccessibilityAction(int, Bundle)
21705         *      View#performAccessibilityAction(int, Bundle)
21706         */
21707        public boolean performAccessibilityAction(View host, int action, Bundle args) {
21708            return host.performAccessibilityActionInternal(action, args);
21709        }
21710
21711        /**
21712         * Sends an accessibility event. This method behaves exactly as
21713         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
21714         * empty {@link AccessibilityEvent} and does not perform a check whether
21715         * accessibility is enabled.
21716         * <p>
21717         * The default implementation behaves as
21718         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21719         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
21720         * the case of no accessibility delegate been set.
21721         * </p>
21722         *
21723         * @param host The View hosting the delegate.
21724         * @param event The event to send.
21725         *
21726         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21727         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21728         */
21729        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
21730            host.sendAccessibilityEventUncheckedInternal(event);
21731        }
21732
21733        /**
21734         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
21735         * to its children for adding their text content to the event.
21736         * <p>
21737         * The default implementation behaves as
21738         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21739         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
21740         * the case of no accessibility delegate been set.
21741         * </p>
21742         *
21743         * @param host The View hosting the delegate.
21744         * @param event The event.
21745         * @return True if the event population was completed.
21746         *
21747         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21748         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21749         */
21750        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21751            return host.dispatchPopulateAccessibilityEventInternal(event);
21752        }
21753
21754        /**
21755         * Gives a chance to the host View to populate the accessibility event with its
21756         * text content.
21757         * <p>
21758         * The default implementation behaves as
21759         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
21760         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
21761         * the case of no accessibility delegate been set.
21762         * </p>
21763         *
21764         * @param host The View hosting the delegate.
21765         * @param event The accessibility event which to populate.
21766         *
21767         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
21768         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
21769         */
21770        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21771            host.onPopulateAccessibilityEventInternal(event);
21772        }
21773
21774        /**
21775         * Initializes an {@link AccessibilityEvent} with information about the
21776         * the host View which is the event source.
21777         * <p>
21778         * The default implementation behaves as
21779         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
21780         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
21781         * the case of no accessibility delegate been set.
21782         * </p>
21783         *
21784         * @param host The View hosting the delegate.
21785         * @param event The event to initialize.
21786         *
21787         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
21788         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
21789         */
21790        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
21791            host.onInitializeAccessibilityEventInternal(event);
21792        }
21793
21794        /**
21795         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
21796         * <p>
21797         * The default implementation behaves as
21798         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21799         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
21800         * the case of no accessibility delegate been set.
21801         * </p>
21802         *
21803         * @param host The View hosting the delegate.
21804         * @param info The instance to initialize.
21805         *
21806         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21807         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21808         */
21809        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
21810            host.onInitializeAccessibilityNodeInfoInternal(info);
21811        }
21812
21813        /**
21814         * Called when a child of the host View has requested sending an
21815         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
21816         * to augment the event.
21817         * <p>
21818         * The default implementation behaves as
21819         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21820         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
21821         * the case of no accessibility delegate been set.
21822         * </p>
21823         *
21824         * @param host The View hosting the delegate.
21825         * @param child The child which requests sending the event.
21826         * @param event The event to be sent.
21827         * @return True if the event should be sent
21828         *
21829         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21830         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21831         */
21832        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
21833                AccessibilityEvent event) {
21834            return host.onRequestSendAccessibilityEventInternal(child, event);
21835        }
21836
21837        /**
21838         * Gets the provider for managing a virtual view hierarchy rooted at this View
21839         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21840         * that explore the window content.
21841         * <p>
21842         * The default implementation behaves as
21843         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21844         * the case of no accessibility delegate been set.
21845         * </p>
21846         *
21847         * @return The provider.
21848         *
21849         * @see AccessibilityNodeProvider
21850         */
21851        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21852            return null;
21853        }
21854
21855        /**
21856         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21857         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21858         * This method is responsible for obtaining an accessibility node info from a
21859         * pool of reusable instances and calling
21860         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21861         * view to initialize the former.
21862         * <p>
21863         * <strong>Note:</strong> The client is responsible for recycling the obtained
21864         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21865         * creation.
21866         * </p>
21867         * <p>
21868         * The default implementation behaves as
21869         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21870         * the case of no accessibility delegate been set.
21871         * </p>
21872         * @return A populated {@link AccessibilityNodeInfo}.
21873         *
21874         * @see AccessibilityNodeInfo
21875         *
21876         * @hide
21877         */
21878        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21879            return host.createAccessibilityNodeInfoInternal();
21880        }
21881    }
21882
21883    private class MatchIdPredicate implements Predicate<View> {
21884        public int mId;
21885
21886        @Override
21887        public boolean apply(View view) {
21888            return (view.mID == mId);
21889        }
21890    }
21891
21892    private class MatchLabelForPredicate implements Predicate<View> {
21893        private int mLabeledId;
21894
21895        @Override
21896        public boolean apply(View view) {
21897            return (view.mLabelForId == mLabeledId);
21898        }
21899    }
21900
21901    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21902        private int mChangeTypes = 0;
21903        private boolean mPosted;
21904        private boolean mPostedWithDelay;
21905        private long mLastEventTimeMillis;
21906
21907        @Override
21908        public void run() {
21909            mPosted = false;
21910            mPostedWithDelay = false;
21911            mLastEventTimeMillis = SystemClock.uptimeMillis();
21912            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21913                final AccessibilityEvent event = AccessibilityEvent.obtain();
21914                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21915                event.setContentChangeTypes(mChangeTypes);
21916                sendAccessibilityEventUnchecked(event);
21917            }
21918            mChangeTypes = 0;
21919        }
21920
21921        public void runOrPost(int changeType) {
21922            mChangeTypes |= changeType;
21923
21924            // If this is a live region or the child of a live region, collect
21925            // all events from this frame and send them on the next frame.
21926            if (inLiveRegion()) {
21927                // If we're already posted with a delay, remove that.
21928                if (mPostedWithDelay) {
21929                    removeCallbacks(this);
21930                    mPostedWithDelay = false;
21931                }
21932                // Only post if we're not already posted.
21933                if (!mPosted) {
21934                    post(this);
21935                    mPosted = true;
21936                }
21937                return;
21938            }
21939
21940            if (mPosted) {
21941                return;
21942            }
21943
21944            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21945            final long minEventIntevalMillis =
21946                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21947            if (timeSinceLastMillis >= minEventIntevalMillis) {
21948                removeCallbacks(this);
21949                run();
21950            } else {
21951                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21952                mPostedWithDelay = true;
21953            }
21954        }
21955    }
21956
21957    private boolean inLiveRegion() {
21958        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21959            return true;
21960        }
21961
21962        ViewParent parent = getParent();
21963        while (parent instanceof View) {
21964            if (((View) parent).getAccessibilityLiveRegion()
21965                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21966                return true;
21967            }
21968            parent = parent.getParent();
21969        }
21970
21971        return false;
21972    }
21973
21974    /**
21975     * Dump all private flags in readable format, useful for documentation and
21976     * sanity checking.
21977     */
21978    private static void dumpFlags() {
21979        final HashMap<String, String> found = Maps.newHashMap();
21980        try {
21981            for (Field field : View.class.getDeclaredFields()) {
21982                final int modifiers = field.getModifiers();
21983                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21984                    if (field.getType().equals(int.class)) {
21985                        final int value = field.getInt(null);
21986                        dumpFlag(found, field.getName(), value);
21987                    } else if (field.getType().equals(int[].class)) {
21988                        final int[] values = (int[]) field.get(null);
21989                        for (int i = 0; i < values.length; i++) {
21990                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21991                        }
21992                    }
21993                }
21994            }
21995        } catch (IllegalAccessException e) {
21996            throw new RuntimeException(e);
21997        }
21998
21999        final ArrayList<String> keys = Lists.newArrayList();
22000        keys.addAll(found.keySet());
22001        Collections.sort(keys);
22002        for (String key : keys) {
22003            Log.d(VIEW_LOG_TAG, found.get(key));
22004        }
22005    }
22006
22007    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
22008        // Sort flags by prefix, then by bits, always keeping unique keys
22009        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
22010        final int prefix = name.indexOf('_');
22011        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
22012        final String output = bits + " " + name;
22013        found.put(key, output);
22014    }
22015}
22016