View.java revision d1808401ca3bfd6b6b9a975c1e739b194d18f849
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     * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is
11101     * completely transparent and 1 means the view is completely opaque.
11102     *
11103     * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1)
11104     * can have significant performance implications, especially for large views. It is best to use
11105     * the alpha property 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 <code>false</code> if appropriate, or setting a
11110     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration
11111     * of the animation. On versions {@link android.os.Build.VERSION_CODES#MNC} and below,
11112     * the default path for rendering an unlayered View with alpha could add multiple milliseconds
11113     * of rendering cost, even for simple or small views. Starting with
11114     * {@link android.os.Build.VERSION_CODES#MNC}, {@link #LAYER_TYPE_HARDWARE} is automatically
11115     * applied to the view at the rendering level.</p>
11116     *
11117     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
11118     * responsible for applying the opacity itself.</p>
11119     *
11120     * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if
11121     * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is
11122     * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an
11123     * alpha value less than 1.0 will supersede the alpha of the layer paint.</p>
11124     *
11125     * <p>Starting with {@link android.os.Build.VERSION_CODES#MNC}, setting a translucent alpha
11126     * value will clip a View to its bounds, unless the View returns <code>false</code> from
11127     * {@link #hasOverlappingRendering}.</p>
11128     *
11129     * @param alpha The opacity of the view.
11130     *
11131     * @see #hasOverlappingRendering()
11132     * @see #setLayerType(int, android.graphics.Paint)
11133     *
11134     * @attr ref android.R.styleable#View_alpha
11135     */
11136    public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) {
11137        ensureTransformationInfo();
11138        if (mTransformationInfo.mAlpha != alpha) {
11139            mTransformationInfo.mAlpha = alpha;
11140            if (onSetAlpha((int) (alpha * 255))) {
11141                mPrivateFlags |= PFLAG_ALPHA_SET;
11142                // subclass is handling alpha - don't optimize rendering cache invalidation
11143                invalidateParentCaches();
11144                invalidate(true);
11145            } else {
11146                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11147                invalidateViewProperty(true, false);
11148                mRenderNode.setAlpha(getFinalAlpha());
11149                notifyViewAccessibilityStateChangedIfNeeded(
11150                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
11151            }
11152        }
11153    }
11154
11155    /**
11156     * Faster version of setAlpha() which performs the same steps except there are
11157     * no calls to invalidate(). The caller of this function should perform proper invalidation
11158     * on the parent and this object. The return value indicates whether the subclass handles
11159     * alpha (the return value for onSetAlpha()).
11160     *
11161     * @param alpha The new value for the alpha property
11162     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
11163     *         the new value for the alpha property is different from the old value
11164     */
11165    boolean setAlphaNoInvalidation(float alpha) {
11166        ensureTransformationInfo();
11167        if (mTransformationInfo.mAlpha != alpha) {
11168            mTransformationInfo.mAlpha = alpha;
11169            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
11170            if (subclassHandlesAlpha) {
11171                mPrivateFlags |= PFLAG_ALPHA_SET;
11172                return true;
11173            } else {
11174                mPrivateFlags &= ~PFLAG_ALPHA_SET;
11175                mRenderNode.setAlpha(getFinalAlpha());
11176            }
11177        }
11178        return false;
11179    }
11180
11181    /**
11182     * This property is hidden and intended only for use by the Fade transition, which
11183     * animates it to produce a visual translucency that does not side-effect (or get
11184     * affected by) the real alpha property. This value is composited with the other
11185     * alpha value (and the AlphaAnimation value, when that is present) to produce
11186     * a final visual translucency result, which is what is passed into the DisplayList.
11187     *
11188     * @hide
11189     */
11190    public void setTransitionAlpha(float alpha) {
11191        ensureTransformationInfo();
11192        if (mTransformationInfo.mTransitionAlpha != alpha) {
11193            mTransformationInfo.mTransitionAlpha = alpha;
11194            mPrivateFlags &= ~PFLAG_ALPHA_SET;
11195            invalidateViewProperty(true, false);
11196            mRenderNode.setAlpha(getFinalAlpha());
11197        }
11198    }
11199
11200    /**
11201     * Calculates the visual alpha of this view, which is a combination of the actual
11202     * alpha value and the transitionAlpha value (if set).
11203     */
11204    private float getFinalAlpha() {
11205        if (mTransformationInfo != null) {
11206            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
11207        }
11208        return 1;
11209    }
11210
11211    /**
11212     * This property is hidden and intended only for use by the Fade transition, which
11213     * animates it to produce a visual translucency that does not side-effect (or get
11214     * affected by) the real alpha property. This value is composited with the other
11215     * alpha value (and the AlphaAnimation value, when that is present) to produce
11216     * a final visual translucency result, which is what is passed into the DisplayList.
11217     *
11218     * @hide
11219     */
11220    @ViewDebug.ExportedProperty(category = "drawing")
11221    public float getTransitionAlpha() {
11222        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
11223    }
11224
11225    /**
11226     * Top position of this view relative to its parent.
11227     *
11228     * @return The top of this view, in pixels.
11229     */
11230    @ViewDebug.CapturedViewProperty
11231    public final int getTop() {
11232        return mTop;
11233    }
11234
11235    /**
11236     * Sets the top position of this view relative to its parent. This method is meant to be called
11237     * by the layout system and should not generally be called otherwise, because the property
11238     * may be changed at any time by the layout.
11239     *
11240     * @param top The top of this view, in pixels.
11241     */
11242    public final void setTop(int top) {
11243        if (top != mTop) {
11244            final boolean matrixIsIdentity = hasIdentityMatrix();
11245            if (matrixIsIdentity) {
11246                if (mAttachInfo != null) {
11247                    int minTop;
11248                    int yLoc;
11249                    if (top < mTop) {
11250                        minTop = top;
11251                        yLoc = top - mTop;
11252                    } else {
11253                        minTop = mTop;
11254                        yLoc = 0;
11255                    }
11256                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
11257                }
11258            } else {
11259                // Double-invalidation is necessary to capture view's old and new areas
11260                invalidate(true);
11261            }
11262
11263            int width = mRight - mLeft;
11264            int oldHeight = mBottom - mTop;
11265
11266            mTop = top;
11267            mRenderNode.setTop(mTop);
11268
11269            sizeChange(width, mBottom - mTop, width, oldHeight);
11270
11271            if (!matrixIsIdentity) {
11272                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11273                invalidate(true);
11274            }
11275            mBackgroundSizeChanged = true;
11276            if (mForegroundInfo != null) {
11277                mForegroundInfo.mBoundsChanged = true;
11278            }
11279            invalidateParentIfNeeded();
11280            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11281                // View was rejected last time it was drawn by its parent; this may have changed
11282                invalidateParentIfNeeded();
11283            }
11284        }
11285    }
11286
11287    /**
11288     * Bottom position of this view relative to its parent.
11289     *
11290     * @return The bottom of this view, in pixels.
11291     */
11292    @ViewDebug.CapturedViewProperty
11293    public final int getBottom() {
11294        return mBottom;
11295    }
11296
11297    /**
11298     * True if this view has changed since the last time being drawn.
11299     *
11300     * @return The dirty state of this view.
11301     */
11302    public boolean isDirty() {
11303        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
11304    }
11305
11306    /**
11307     * Sets the bottom position of this view relative to its parent. This method is meant to be
11308     * called by the layout system and should not generally be called otherwise, because the
11309     * property may be changed at any time by the layout.
11310     *
11311     * @param bottom The bottom of this view, in pixels.
11312     */
11313    public final void setBottom(int bottom) {
11314        if (bottom != mBottom) {
11315            final boolean matrixIsIdentity = hasIdentityMatrix();
11316            if (matrixIsIdentity) {
11317                if (mAttachInfo != null) {
11318                    int maxBottom;
11319                    if (bottom < mBottom) {
11320                        maxBottom = mBottom;
11321                    } else {
11322                        maxBottom = bottom;
11323                    }
11324                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
11325                }
11326            } else {
11327                // Double-invalidation is necessary to capture view's old and new areas
11328                invalidate(true);
11329            }
11330
11331            int width = mRight - mLeft;
11332            int oldHeight = mBottom - mTop;
11333
11334            mBottom = bottom;
11335            mRenderNode.setBottom(mBottom);
11336
11337            sizeChange(width, mBottom - mTop, width, oldHeight);
11338
11339            if (!matrixIsIdentity) {
11340                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11341                invalidate(true);
11342            }
11343            mBackgroundSizeChanged = true;
11344            if (mForegroundInfo != null) {
11345                mForegroundInfo.mBoundsChanged = true;
11346            }
11347            invalidateParentIfNeeded();
11348            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11349                // View was rejected last time it was drawn by its parent; this may have changed
11350                invalidateParentIfNeeded();
11351            }
11352        }
11353    }
11354
11355    /**
11356     * Left position of this view relative to its parent.
11357     *
11358     * @return The left edge of this view, in pixels.
11359     */
11360    @ViewDebug.CapturedViewProperty
11361    public final int getLeft() {
11362        return mLeft;
11363    }
11364
11365    /**
11366     * Sets the left position of this view relative to its parent. This method is meant to be called
11367     * by the layout system and should not generally be called otherwise, because the property
11368     * may be changed at any time by the layout.
11369     *
11370     * @param left The left of this view, in pixels.
11371     */
11372    public final void setLeft(int left) {
11373        if (left != mLeft) {
11374            final boolean matrixIsIdentity = hasIdentityMatrix();
11375            if (matrixIsIdentity) {
11376                if (mAttachInfo != null) {
11377                    int minLeft;
11378                    int xLoc;
11379                    if (left < mLeft) {
11380                        minLeft = left;
11381                        xLoc = left - mLeft;
11382                    } else {
11383                        minLeft = mLeft;
11384                        xLoc = 0;
11385                    }
11386                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
11387                }
11388            } else {
11389                // Double-invalidation is necessary to capture view's old and new areas
11390                invalidate(true);
11391            }
11392
11393            int oldWidth = mRight - mLeft;
11394            int height = mBottom - mTop;
11395
11396            mLeft = left;
11397            mRenderNode.setLeft(left);
11398
11399            sizeChange(mRight - mLeft, height, oldWidth, height);
11400
11401            if (!matrixIsIdentity) {
11402                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11403                invalidate(true);
11404            }
11405            mBackgroundSizeChanged = true;
11406            if (mForegroundInfo != null) {
11407                mForegroundInfo.mBoundsChanged = true;
11408            }
11409            invalidateParentIfNeeded();
11410            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11411                // View was rejected last time it was drawn by its parent; this may have changed
11412                invalidateParentIfNeeded();
11413            }
11414        }
11415    }
11416
11417    /**
11418     * Right position of this view relative to its parent.
11419     *
11420     * @return The right edge of this view, in pixels.
11421     */
11422    @ViewDebug.CapturedViewProperty
11423    public final int getRight() {
11424        return mRight;
11425    }
11426
11427    /**
11428     * Sets the right position of this view relative to its parent. This method is meant to be called
11429     * by the layout system and should not generally be called otherwise, because the property
11430     * may be changed at any time by the layout.
11431     *
11432     * @param right The right of this view, in pixels.
11433     */
11434    public final void setRight(int right) {
11435        if (right != mRight) {
11436            final boolean matrixIsIdentity = hasIdentityMatrix();
11437            if (matrixIsIdentity) {
11438                if (mAttachInfo != null) {
11439                    int maxRight;
11440                    if (right < mRight) {
11441                        maxRight = mRight;
11442                    } else {
11443                        maxRight = right;
11444                    }
11445                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
11446                }
11447            } else {
11448                // Double-invalidation is necessary to capture view's old and new areas
11449                invalidate(true);
11450            }
11451
11452            int oldWidth = mRight - mLeft;
11453            int height = mBottom - mTop;
11454
11455            mRight = right;
11456            mRenderNode.setRight(mRight);
11457
11458            sizeChange(mRight - mLeft, height, oldWidth, height);
11459
11460            if (!matrixIsIdentity) {
11461                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11462                invalidate(true);
11463            }
11464            mBackgroundSizeChanged = true;
11465            if (mForegroundInfo != null) {
11466                mForegroundInfo.mBoundsChanged = true;
11467            }
11468            invalidateParentIfNeeded();
11469            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
11470                // View was rejected last time it was drawn by its parent; this may have changed
11471                invalidateParentIfNeeded();
11472            }
11473        }
11474    }
11475
11476    /**
11477     * The visual x position of this view, in pixels. This is equivalent to the
11478     * {@link #setTranslationX(float) translationX} property plus the current
11479     * {@link #getLeft() left} property.
11480     *
11481     * @return The visual x position of this view, in pixels.
11482     */
11483    @ViewDebug.ExportedProperty(category = "drawing")
11484    public float getX() {
11485        return mLeft + getTranslationX();
11486    }
11487
11488    /**
11489     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
11490     * {@link #setTranslationX(float) translationX} property to be the difference between
11491     * the x value passed in and the current {@link #getLeft() left} property.
11492     *
11493     * @param x The visual x position of this view, in pixels.
11494     */
11495    public void setX(float x) {
11496        setTranslationX(x - mLeft);
11497    }
11498
11499    /**
11500     * The visual y position of this view, in pixels. This is equivalent to the
11501     * {@link #setTranslationY(float) translationY} property plus the current
11502     * {@link #getTop() top} property.
11503     *
11504     * @return The visual y position of this view, in pixels.
11505     */
11506    @ViewDebug.ExportedProperty(category = "drawing")
11507    public float getY() {
11508        return mTop + getTranslationY();
11509    }
11510
11511    /**
11512     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
11513     * {@link #setTranslationY(float) translationY} property to be the difference between
11514     * the y value passed in and the current {@link #getTop() top} property.
11515     *
11516     * @param y The visual y position of this view, in pixels.
11517     */
11518    public void setY(float y) {
11519        setTranslationY(y - mTop);
11520    }
11521
11522    /**
11523     * The visual z position of this view, in pixels. This is equivalent to the
11524     * {@link #setTranslationZ(float) translationZ} property plus the current
11525     * {@link #getElevation() elevation} property.
11526     *
11527     * @return The visual z position of this view, in pixels.
11528     */
11529    @ViewDebug.ExportedProperty(category = "drawing")
11530    public float getZ() {
11531        return getElevation() + getTranslationZ();
11532    }
11533
11534    /**
11535     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
11536     * {@link #setTranslationZ(float) translationZ} property to be the difference between
11537     * the x value passed in and the current {@link #getElevation() elevation} property.
11538     *
11539     * @param z The visual z position of this view, in pixels.
11540     */
11541    public void setZ(float z) {
11542        setTranslationZ(z - getElevation());
11543    }
11544
11545    /**
11546     * The base elevation of this view relative to its parent, in pixels.
11547     *
11548     * @return The base depth position of the view, in pixels.
11549     */
11550    @ViewDebug.ExportedProperty(category = "drawing")
11551    public float getElevation() {
11552        return mRenderNode.getElevation();
11553    }
11554
11555    /**
11556     * Sets the base elevation of this view, in pixels.
11557     *
11558     * @attr ref android.R.styleable#View_elevation
11559     */
11560    public void setElevation(float elevation) {
11561        if (elevation != getElevation()) {
11562            invalidateViewProperty(true, false);
11563            mRenderNode.setElevation(elevation);
11564            invalidateViewProperty(false, true);
11565
11566            invalidateParentIfNeededAndWasQuickRejected();
11567        }
11568    }
11569
11570    /**
11571     * The horizontal location of this view relative to its {@link #getLeft() left} position.
11572     * This position is post-layout, in addition to wherever the object's
11573     * layout placed it.
11574     *
11575     * @return The horizontal position of this view relative to its left position, in pixels.
11576     */
11577    @ViewDebug.ExportedProperty(category = "drawing")
11578    public float getTranslationX() {
11579        return mRenderNode.getTranslationX();
11580    }
11581
11582    /**
11583     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
11584     * This effectively positions the object post-layout, in addition to wherever the object's
11585     * layout placed it.
11586     *
11587     * @param translationX The horizontal position of this view relative to its left position,
11588     * in pixels.
11589     *
11590     * @attr ref android.R.styleable#View_translationX
11591     */
11592    public void setTranslationX(float translationX) {
11593        if (translationX != getTranslationX()) {
11594            invalidateViewProperty(true, false);
11595            mRenderNode.setTranslationX(translationX);
11596            invalidateViewProperty(false, true);
11597
11598            invalidateParentIfNeededAndWasQuickRejected();
11599            notifySubtreeAccessibilityStateChangedIfNeeded();
11600        }
11601    }
11602
11603    /**
11604     * The vertical location of this view relative to its {@link #getTop() top} position.
11605     * This position is post-layout, in addition to wherever the object's
11606     * layout placed it.
11607     *
11608     * @return The vertical position of this view relative to its top position,
11609     * in pixels.
11610     */
11611    @ViewDebug.ExportedProperty(category = "drawing")
11612    public float getTranslationY() {
11613        return mRenderNode.getTranslationY();
11614    }
11615
11616    /**
11617     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
11618     * This effectively positions the object post-layout, in addition to wherever the object's
11619     * layout placed it.
11620     *
11621     * @param translationY The vertical position of this view relative to its top position,
11622     * in pixels.
11623     *
11624     * @attr ref android.R.styleable#View_translationY
11625     */
11626    public void setTranslationY(float translationY) {
11627        if (translationY != getTranslationY()) {
11628            invalidateViewProperty(true, false);
11629            mRenderNode.setTranslationY(translationY);
11630            invalidateViewProperty(false, true);
11631
11632            invalidateParentIfNeededAndWasQuickRejected();
11633            notifySubtreeAccessibilityStateChangedIfNeeded();
11634        }
11635    }
11636
11637    /**
11638     * The depth location of this view relative to its {@link #getElevation() elevation}.
11639     *
11640     * @return The depth of this view relative to its elevation.
11641     */
11642    @ViewDebug.ExportedProperty(category = "drawing")
11643    public float getTranslationZ() {
11644        return mRenderNode.getTranslationZ();
11645    }
11646
11647    /**
11648     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
11649     *
11650     * @attr ref android.R.styleable#View_translationZ
11651     */
11652    public void setTranslationZ(float translationZ) {
11653        if (translationZ != getTranslationZ()) {
11654            invalidateViewProperty(true, false);
11655            mRenderNode.setTranslationZ(translationZ);
11656            invalidateViewProperty(false, true);
11657
11658            invalidateParentIfNeededAndWasQuickRejected();
11659        }
11660    }
11661
11662    /** @hide */
11663    public void setAnimationMatrix(Matrix matrix) {
11664        invalidateViewProperty(true, false);
11665        mRenderNode.setAnimationMatrix(matrix);
11666        invalidateViewProperty(false, true);
11667
11668        invalidateParentIfNeededAndWasQuickRejected();
11669    }
11670
11671    /**
11672     * Returns the current StateListAnimator if exists.
11673     *
11674     * @return StateListAnimator or null if it does not exists
11675     * @see    #setStateListAnimator(android.animation.StateListAnimator)
11676     */
11677    public StateListAnimator getStateListAnimator() {
11678        return mStateListAnimator;
11679    }
11680
11681    /**
11682     * Attaches the provided StateListAnimator to this View.
11683     * <p>
11684     * Any previously attached StateListAnimator will be detached.
11685     *
11686     * @param stateListAnimator The StateListAnimator to update the view
11687     * @see {@link android.animation.StateListAnimator}
11688     */
11689    public void setStateListAnimator(StateListAnimator stateListAnimator) {
11690        if (mStateListAnimator == stateListAnimator) {
11691            return;
11692        }
11693        if (mStateListAnimator != null) {
11694            mStateListAnimator.setTarget(null);
11695        }
11696        mStateListAnimator = stateListAnimator;
11697        if (stateListAnimator != null) {
11698            stateListAnimator.setTarget(this);
11699            if (isAttachedToWindow()) {
11700                stateListAnimator.setState(getDrawableState());
11701            }
11702        }
11703    }
11704
11705    /**
11706     * Returns whether the Outline should be used to clip the contents of the View.
11707     * <p>
11708     * Note that this flag will only be respected if the View's Outline returns true from
11709     * {@link Outline#canClip()}.
11710     *
11711     * @see #setOutlineProvider(ViewOutlineProvider)
11712     * @see #setClipToOutline(boolean)
11713     */
11714    public final boolean getClipToOutline() {
11715        return mRenderNode.getClipToOutline();
11716    }
11717
11718    /**
11719     * Sets whether the View's Outline should be used to clip the contents of the View.
11720     * <p>
11721     * Only a single non-rectangular clip can be applied on a View at any time.
11722     * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float)
11723     * circular reveal} animation take priority over Outline clipping, and
11724     * child Outline clipping takes priority over Outline clipping done by a
11725     * parent.
11726     * <p>
11727     * Note that this flag will only be respected if the View's Outline returns true from
11728     * {@link Outline#canClip()}.
11729     *
11730     * @see #setOutlineProvider(ViewOutlineProvider)
11731     * @see #getClipToOutline()
11732     */
11733    public void setClipToOutline(boolean clipToOutline) {
11734        damageInParent();
11735        if (getClipToOutline() != clipToOutline) {
11736            mRenderNode.setClipToOutline(clipToOutline);
11737        }
11738    }
11739
11740    // correspond to the enum values of View_outlineProvider
11741    private static final int PROVIDER_BACKGROUND = 0;
11742    private static final int PROVIDER_NONE = 1;
11743    private static final int PROVIDER_BOUNDS = 2;
11744    private static final int PROVIDER_PADDED_BOUNDS = 3;
11745    private void setOutlineProviderFromAttribute(int providerInt) {
11746        switch (providerInt) {
11747            case PROVIDER_BACKGROUND:
11748                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
11749                break;
11750            case PROVIDER_NONE:
11751                setOutlineProvider(null);
11752                break;
11753            case PROVIDER_BOUNDS:
11754                setOutlineProvider(ViewOutlineProvider.BOUNDS);
11755                break;
11756            case PROVIDER_PADDED_BOUNDS:
11757                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
11758                break;
11759        }
11760    }
11761
11762    /**
11763     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
11764     * the shape of the shadow it casts, and enables outline clipping.
11765     * <p>
11766     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
11767     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
11768     * outline provider with this method allows this behavior to be overridden.
11769     * <p>
11770     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
11771     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
11772     * <p>
11773     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
11774     *
11775     * @see #setClipToOutline(boolean)
11776     * @see #getClipToOutline()
11777     * @see #getOutlineProvider()
11778     */
11779    public void setOutlineProvider(ViewOutlineProvider provider) {
11780        mOutlineProvider = provider;
11781        invalidateOutline();
11782    }
11783
11784    /**
11785     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
11786     * that defines the shape of the shadow it casts, and enables outline clipping.
11787     *
11788     * @see #setOutlineProvider(ViewOutlineProvider)
11789     */
11790    public ViewOutlineProvider getOutlineProvider() {
11791        return mOutlineProvider;
11792    }
11793
11794    /**
11795     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
11796     *
11797     * @see #setOutlineProvider(ViewOutlineProvider)
11798     */
11799    public void invalidateOutline() {
11800        rebuildOutline();
11801
11802        notifySubtreeAccessibilityStateChangedIfNeeded();
11803        invalidateViewProperty(false, false);
11804    }
11805
11806    /**
11807     * Internal version of {@link #invalidateOutline()} which invalidates the
11808     * outline without invalidating the view itself. This is intended to be called from
11809     * within methods in the View class itself which are the result of the view being
11810     * invalidated already. For example, when we are drawing the background of a View,
11811     * we invalidate the outline in case it changed in the meantime, but we do not
11812     * need to invalidate the view because we're already drawing the background as part
11813     * of drawing the view in response to an earlier invalidation of the view.
11814     */
11815    private void rebuildOutline() {
11816        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
11817        if (mAttachInfo == null) return;
11818
11819        if (mOutlineProvider == null) {
11820            // no provider, remove outline
11821            mRenderNode.setOutline(null);
11822        } else {
11823            final Outline outline = mAttachInfo.mTmpOutline;
11824            outline.setEmpty();
11825            outline.setAlpha(1.0f);
11826
11827            mOutlineProvider.getOutline(this, outline);
11828            mRenderNode.setOutline(outline);
11829        }
11830    }
11831
11832    /**
11833     * HierarchyViewer only
11834     *
11835     * @hide
11836     */
11837    @ViewDebug.ExportedProperty(category = "drawing")
11838    public boolean hasShadow() {
11839        return mRenderNode.hasShadow();
11840    }
11841
11842
11843    /** @hide */
11844    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
11845        mRenderNode.setRevealClip(shouldClip, x, y, radius);
11846        invalidateViewProperty(false, false);
11847    }
11848
11849    /**
11850     * Hit rectangle in parent's coordinates
11851     *
11852     * @param outRect The hit rectangle of the view.
11853     */
11854    public void getHitRect(Rect outRect) {
11855        if (hasIdentityMatrix() || mAttachInfo == null) {
11856            outRect.set(mLeft, mTop, mRight, mBottom);
11857        } else {
11858            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
11859            tmpRect.set(0, 0, getWidth(), getHeight());
11860            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
11861            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
11862                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
11863        }
11864    }
11865
11866    /**
11867     * Determines whether the given point, in local coordinates is inside the view.
11868     */
11869    /*package*/ final boolean pointInView(float localX, float localY) {
11870        return localX >= 0 && localX < (mRight - mLeft)
11871                && localY >= 0 && localY < (mBottom - mTop);
11872    }
11873
11874    /**
11875     * Utility method to determine whether the given point, in local coordinates,
11876     * is inside the view, where the area of the view is expanded by the slop factor.
11877     * This method is called while processing touch-move events to determine if the event
11878     * is still within the view.
11879     *
11880     * @hide
11881     */
11882    public boolean pointInView(float localX, float localY, float slop) {
11883        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
11884                localY < ((mBottom - mTop) + slop);
11885    }
11886
11887    /**
11888     * When a view has focus and the user navigates away from it, the next view is searched for
11889     * starting from the rectangle filled in by this method.
11890     *
11891     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
11892     * of the view.  However, if your view maintains some idea of internal selection,
11893     * such as a cursor, or a selected row or column, you should override this method and
11894     * fill in a more specific rectangle.
11895     *
11896     * @param r The rectangle to fill in, in this view's coordinates.
11897     */
11898    public void getFocusedRect(Rect r) {
11899        getDrawingRect(r);
11900    }
11901
11902    /**
11903     * If some part of this view is not clipped by any of its parents, then
11904     * return that area in r in global (root) coordinates. To convert r to local
11905     * coordinates (without taking possible View rotations into account), offset
11906     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11907     * If the view is completely clipped or translated out, return false.
11908     *
11909     * @param r If true is returned, r holds the global coordinates of the
11910     *        visible portion of this view.
11911     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11912     *        between this view and its root. globalOffet may be null.
11913     * @return true if r is non-empty (i.e. part of the view is visible at the
11914     *         root level.
11915     */
11916    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11917        int width = mRight - mLeft;
11918        int height = mBottom - mTop;
11919        if (width > 0 && height > 0) {
11920            r.set(0, 0, width, height);
11921            if (globalOffset != null) {
11922                globalOffset.set(-mScrollX, -mScrollY);
11923            }
11924            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11925        }
11926        return false;
11927    }
11928
11929    public final boolean getGlobalVisibleRect(Rect r) {
11930        return getGlobalVisibleRect(r, null);
11931    }
11932
11933    public final boolean getLocalVisibleRect(Rect r) {
11934        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11935        if (getGlobalVisibleRect(r, offset)) {
11936            r.offset(-offset.x, -offset.y); // make r local
11937            return true;
11938        }
11939        return false;
11940    }
11941
11942    /**
11943     * Offset this view's vertical location by the specified number of pixels.
11944     *
11945     * @param offset the number of pixels to offset the view by
11946     */
11947    public void offsetTopAndBottom(int offset) {
11948        if (offset != 0) {
11949            final boolean matrixIsIdentity = hasIdentityMatrix();
11950            if (matrixIsIdentity) {
11951                if (isHardwareAccelerated()) {
11952                    invalidateViewProperty(false, false);
11953                } else {
11954                    final ViewParent p = mParent;
11955                    if (p != null && mAttachInfo != null) {
11956                        final Rect r = mAttachInfo.mTmpInvalRect;
11957                        int minTop;
11958                        int maxBottom;
11959                        int yLoc;
11960                        if (offset < 0) {
11961                            minTop = mTop + offset;
11962                            maxBottom = mBottom;
11963                            yLoc = offset;
11964                        } else {
11965                            minTop = mTop;
11966                            maxBottom = mBottom + offset;
11967                            yLoc = 0;
11968                        }
11969                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11970                        p.invalidateChild(this, r);
11971                    }
11972                }
11973            } else {
11974                invalidateViewProperty(false, false);
11975            }
11976
11977            mTop += offset;
11978            mBottom += offset;
11979            mRenderNode.offsetTopAndBottom(offset);
11980            if (isHardwareAccelerated()) {
11981                invalidateViewProperty(false, false);
11982            } else {
11983                if (!matrixIsIdentity) {
11984                    invalidateViewProperty(false, true);
11985                }
11986                invalidateParentIfNeeded();
11987            }
11988            notifySubtreeAccessibilityStateChangedIfNeeded();
11989        }
11990    }
11991
11992    /**
11993     * Offset this view's horizontal location by the specified amount of pixels.
11994     *
11995     * @param offset the number of pixels to offset the view by
11996     */
11997    public void offsetLeftAndRight(int offset) {
11998        if (offset != 0) {
11999            final boolean matrixIsIdentity = hasIdentityMatrix();
12000            if (matrixIsIdentity) {
12001                if (isHardwareAccelerated()) {
12002                    invalidateViewProperty(false, false);
12003                } else {
12004                    final ViewParent p = mParent;
12005                    if (p != null && mAttachInfo != null) {
12006                        final Rect r = mAttachInfo.mTmpInvalRect;
12007                        int minLeft;
12008                        int maxRight;
12009                        if (offset < 0) {
12010                            minLeft = mLeft + offset;
12011                            maxRight = mRight;
12012                        } else {
12013                            minLeft = mLeft;
12014                            maxRight = mRight + offset;
12015                        }
12016                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
12017                        p.invalidateChild(this, r);
12018                    }
12019                }
12020            } else {
12021                invalidateViewProperty(false, false);
12022            }
12023
12024            mLeft += offset;
12025            mRight += offset;
12026            mRenderNode.offsetLeftAndRight(offset);
12027            if (isHardwareAccelerated()) {
12028                invalidateViewProperty(false, false);
12029            } else {
12030                if (!matrixIsIdentity) {
12031                    invalidateViewProperty(false, true);
12032                }
12033                invalidateParentIfNeeded();
12034            }
12035            notifySubtreeAccessibilityStateChangedIfNeeded();
12036        }
12037    }
12038
12039    /**
12040     * Get the LayoutParams associated with this view. All views should have
12041     * layout parameters. These supply parameters to the <i>parent</i> of this
12042     * view specifying how it should be arranged. There are many subclasses of
12043     * ViewGroup.LayoutParams, and these correspond to the different subclasses
12044     * of ViewGroup that are responsible for arranging their children.
12045     *
12046     * This method may return null if this View is not attached to a parent
12047     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
12048     * was not invoked successfully. When a View is attached to a parent
12049     * ViewGroup, this method must not return null.
12050     *
12051     * @return The LayoutParams associated with this view, or null if no
12052     *         parameters have been set yet
12053     */
12054    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
12055    public ViewGroup.LayoutParams getLayoutParams() {
12056        return mLayoutParams;
12057    }
12058
12059    /**
12060     * Set the layout parameters associated with this view. These supply
12061     * parameters to the <i>parent</i> of this view specifying how it should be
12062     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
12063     * correspond to the different subclasses of ViewGroup that are responsible
12064     * for arranging their children.
12065     *
12066     * @param params The layout parameters for this view, cannot be null
12067     */
12068    public void setLayoutParams(ViewGroup.LayoutParams params) {
12069        if (params == null) {
12070            throw new NullPointerException("Layout parameters cannot be null");
12071        }
12072        mLayoutParams = params;
12073        resolveLayoutParams();
12074        if (mParent instanceof ViewGroup) {
12075            ((ViewGroup) mParent).onSetLayoutParams(this, params);
12076        }
12077        requestLayout();
12078    }
12079
12080    /**
12081     * Resolve the layout parameters depending on the resolved layout direction
12082     *
12083     * @hide
12084     */
12085    public void resolveLayoutParams() {
12086        if (mLayoutParams != null) {
12087            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
12088        }
12089    }
12090
12091    /**
12092     * Set the scrolled position of your view. This will cause a call to
12093     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12094     * invalidated.
12095     * @param x the x position to scroll to
12096     * @param y the y position to scroll to
12097     */
12098    public void scrollTo(int x, int y) {
12099        if (mScrollX != x || mScrollY != y) {
12100            int oldX = mScrollX;
12101            int oldY = mScrollY;
12102            mScrollX = x;
12103            mScrollY = y;
12104            invalidateParentCaches();
12105            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
12106            if (!awakenScrollBars()) {
12107                postInvalidateOnAnimation();
12108            }
12109        }
12110    }
12111
12112    /**
12113     * Move the scrolled position of your view. This will cause a call to
12114     * {@link #onScrollChanged(int, int, int, int)} and the view will be
12115     * invalidated.
12116     * @param x the amount of pixels to scroll by horizontally
12117     * @param y the amount of pixels to scroll by vertically
12118     */
12119    public void scrollBy(int x, int y) {
12120        scrollTo(mScrollX + x, mScrollY + y);
12121    }
12122
12123    /**
12124     * <p>Trigger the scrollbars to draw. When invoked this method starts an
12125     * animation to fade the scrollbars out after a default delay. If a subclass
12126     * provides animated scrolling, the start delay should equal the duration
12127     * of the scrolling animation.</p>
12128     *
12129     * <p>The animation starts only if at least one of the scrollbars is
12130     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
12131     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12132     * this method returns true, and false otherwise. If the animation is
12133     * started, this method calls {@link #invalidate()}; in that case the
12134     * caller should not call {@link #invalidate()}.</p>
12135     *
12136     * <p>This method should be invoked every time a subclass directly updates
12137     * the scroll parameters.</p>
12138     *
12139     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
12140     * and {@link #scrollTo(int, int)}.</p>
12141     *
12142     * @return true if the animation is played, false otherwise
12143     *
12144     * @see #awakenScrollBars(int)
12145     * @see #scrollBy(int, int)
12146     * @see #scrollTo(int, int)
12147     * @see #isHorizontalScrollBarEnabled()
12148     * @see #isVerticalScrollBarEnabled()
12149     * @see #setHorizontalScrollBarEnabled(boolean)
12150     * @see #setVerticalScrollBarEnabled(boolean)
12151     */
12152    protected boolean awakenScrollBars() {
12153        return mScrollCache != null &&
12154                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
12155    }
12156
12157    /**
12158     * Trigger the scrollbars to draw.
12159     * This method differs from awakenScrollBars() only in its default duration.
12160     * initialAwakenScrollBars() will show the scroll bars for longer than
12161     * usual to give the user more of a chance to notice them.
12162     *
12163     * @return true if the animation is played, false otherwise.
12164     */
12165    private boolean initialAwakenScrollBars() {
12166        return mScrollCache != null &&
12167                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
12168    }
12169
12170    /**
12171     * <p>
12172     * Trigger the scrollbars to draw. When invoked this method starts an
12173     * animation to fade the scrollbars out after a fixed delay. If a subclass
12174     * provides animated scrolling, the start delay should equal the duration of
12175     * the scrolling animation.
12176     * </p>
12177     *
12178     * <p>
12179     * The animation starts only if at least one of the scrollbars is enabled,
12180     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12181     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12182     * this method returns true, and false otherwise. If the animation is
12183     * started, this method calls {@link #invalidate()}; in that case the caller
12184     * should not call {@link #invalidate()}.
12185     * </p>
12186     *
12187     * <p>
12188     * This method should be invoked every time a subclass directly updates the
12189     * scroll parameters.
12190     * </p>
12191     *
12192     * @param startDelay the delay, in milliseconds, after which the animation
12193     *        should start; when the delay is 0, the animation starts
12194     *        immediately
12195     * @return true if the animation is played, false otherwise
12196     *
12197     * @see #scrollBy(int, int)
12198     * @see #scrollTo(int, int)
12199     * @see #isHorizontalScrollBarEnabled()
12200     * @see #isVerticalScrollBarEnabled()
12201     * @see #setHorizontalScrollBarEnabled(boolean)
12202     * @see #setVerticalScrollBarEnabled(boolean)
12203     */
12204    protected boolean awakenScrollBars(int startDelay) {
12205        return awakenScrollBars(startDelay, true);
12206    }
12207
12208    /**
12209     * <p>
12210     * Trigger the scrollbars to draw. When invoked this method starts an
12211     * animation to fade the scrollbars out after a fixed delay. If a subclass
12212     * provides animated scrolling, the start delay should equal the duration of
12213     * the scrolling animation.
12214     * </p>
12215     *
12216     * <p>
12217     * The animation starts only if at least one of the scrollbars is enabled,
12218     * as specified by {@link #isHorizontalScrollBarEnabled()} and
12219     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
12220     * this method returns true, and false otherwise. If the animation is
12221     * started, this method calls {@link #invalidate()} if the invalidate parameter
12222     * is set to true; in that case the caller
12223     * should not call {@link #invalidate()}.
12224     * </p>
12225     *
12226     * <p>
12227     * This method should be invoked every time a subclass directly updates the
12228     * scroll parameters.
12229     * </p>
12230     *
12231     * @param startDelay the delay, in milliseconds, after which the animation
12232     *        should start; when the delay is 0, the animation starts
12233     *        immediately
12234     *
12235     * @param invalidate Whether this method should call invalidate
12236     *
12237     * @return true if the animation is played, false otherwise
12238     *
12239     * @see #scrollBy(int, int)
12240     * @see #scrollTo(int, int)
12241     * @see #isHorizontalScrollBarEnabled()
12242     * @see #isVerticalScrollBarEnabled()
12243     * @see #setHorizontalScrollBarEnabled(boolean)
12244     * @see #setVerticalScrollBarEnabled(boolean)
12245     */
12246    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
12247        final ScrollabilityCache scrollCache = mScrollCache;
12248
12249        if (scrollCache == null || !scrollCache.fadeScrollBars) {
12250            return false;
12251        }
12252
12253        if (scrollCache.scrollBar == null) {
12254            scrollCache.scrollBar = new ScrollBarDrawable();
12255            scrollCache.scrollBar.setCallback(this);
12256            scrollCache.scrollBar.setState(getDrawableState());
12257        }
12258
12259        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
12260
12261            if (invalidate) {
12262                // Invalidate to show the scrollbars
12263                postInvalidateOnAnimation();
12264            }
12265
12266            if (scrollCache.state == ScrollabilityCache.OFF) {
12267                // FIXME: this is copied from WindowManagerService.
12268                // We should get this value from the system when it
12269                // is possible to do so.
12270                final int KEY_REPEAT_FIRST_DELAY = 750;
12271                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
12272            }
12273
12274            // Tell mScrollCache when we should start fading. This may
12275            // extend the fade start time if one was already scheduled
12276            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
12277            scrollCache.fadeStartTime = fadeStartTime;
12278            scrollCache.state = ScrollabilityCache.ON;
12279
12280            // Schedule our fader to run, unscheduling any old ones first
12281            if (mAttachInfo != null) {
12282                mAttachInfo.mHandler.removeCallbacks(scrollCache);
12283                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
12284            }
12285
12286            return true;
12287        }
12288
12289        return false;
12290    }
12291
12292    /**
12293     * Do not invalidate views which are not visible and which are not running an animation. They
12294     * will not get drawn and they should not set dirty flags as if they will be drawn
12295     */
12296    private boolean skipInvalidate() {
12297        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
12298                (!(mParent instanceof ViewGroup) ||
12299                        !((ViewGroup) mParent).isViewTransitioning(this));
12300    }
12301
12302    /**
12303     * Mark the area defined by dirty as needing to be drawn. If the view is
12304     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12305     * point in the future.
12306     * <p>
12307     * This must be called from a UI thread. To call from a non-UI thread, call
12308     * {@link #postInvalidate()}.
12309     * <p>
12310     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
12311     * {@code dirty}.
12312     *
12313     * @param dirty the rectangle representing the bounds of the dirty region
12314     */
12315    public void invalidate(Rect dirty) {
12316        final int scrollX = mScrollX;
12317        final int scrollY = mScrollY;
12318        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
12319                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
12320    }
12321
12322    /**
12323     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
12324     * coordinates of the dirty rect are relative to the view. If the view is
12325     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
12326     * point in the future.
12327     * <p>
12328     * This must be called from a UI thread. To call from a non-UI thread, call
12329     * {@link #postInvalidate()}.
12330     *
12331     * @param l the left position of the dirty region
12332     * @param t the top position of the dirty region
12333     * @param r the right position of the dirty region
12334     * @param b the bottom position of the dirty region
12335     */
12336    public void invalidate(int l, int t, int r, int b) {
12337        final int scrollX = mScrollX;
12338        final int scrollY = mScrollY;
12339        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
12340    }
12341
12342    /**
12343     * Invalidate the whole view. If the view is visible,
12344     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
12345     * the future.
12346     * <p>
12347     * This must be called from a UI thread. To call from a non-UI thread, call
12348     * {@link #postInvalidate()}.
12349     */
12350    public void invalidate() {
12351        invalidate(true);
12352    }
12353
12354    /**
12355     * This is where the invalidate() work actually happens. A full invalidate()
12356     * causes the drawing cache to be invalidated, but this function can be
12357     * called with invalidateCache set to false to skip that invalidation step
12358     * for cases that do not need it (for example, a component that remains at
12359     * the same dimensions with the same content).
12360     *
12361     * @param invalidateCache Whether the drawing cache for this view should be
12362     *            invalidated as well. This is usually true for a full
12363     *            invalidate, but may be set to false if the View's contents or
12364     *            dimensions have not changed.
12365     */
12366    void invalidate(boolean invalidateCache) {
12367        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
12368    }
12369
12370    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
12371            boolean fullInvalidate) {
12372        if (mGhostView != null) {
12373            mGhostView.invalidate(true);
12374            return;
12375        }
12376
12377        if (skipInvalidate()) {
12378            return;
12379        }
12380
12381        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
12382                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
12383                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
12384                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
12385            if (fullInvalidate) {
12386                mLastIsOpaque = isOpaque();
12387                mPrivateFlags &= ~PFLAG_DRAWN;
12388            }
12389
12390            mPrivateFlags |= PFLAG_DIRTY;
12391
12392            if (invalidateCache) {
12393                mPrivateFlags |= PFLAG_INVALIDATED;
12394                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12395            }
12396
12397            // Propagate the damage rectangle to the parent view.
12398            final AttachInfo ai = mAttachInfo;
12399            final ViewParent p = mParent;
12400            if (p != null && ai != null && l < r && t < b) {
12401                final Rect damage = ai.mTmpInvalRect;
12402                damage.set(l, t, r, b);
12403                p.invalidateChild(this, damage);
12404            }
12405
12406            // Damage the entire projection receiver, if necessary.
12407            if (mBackground != null && mBackground.isProjected()) {
12408                final View receiver = getProjectionReceiver();
12409                if (receiver != null) {
12410                    receiver.damageInParent();
12411                }
12412            }
12413
12414            // Damage the entire IsolatedZVolume receiving this view's shadow.
12415            if (isHardwareAccelerated() && getZ() != 0) {
12416                damageShadowReceiver();
12417            }
12418        }
12419    }
12420
12421    /**
12422     * @return this view's projection receiver, or {@code null} if none exists
12423     */
12424    private View getProjectionReceiver() {
12425        ViewParent p = getParent();
12426        while (p != null && p instanceof View) {
12427            final View v = (View) p;
12428            if (v.isProjectionReceiver()) {
12429                return v;
12430            }
12431            p = p.getParent();
12432        }
12433
12434        return null;
12435    }
12436
12437    /**
12438     * @return whether the view is a projection receiver
12439     */
12440    private boolean isProjectionReceiver() {
12441        return mBackground != null;
12442    }
12443
12444    /**
12445     * Damage area of the screen that can be covered by this View's shadow.
12446     *
12447     * This method will guarantee that any changes to shadows cast by a View
12448     * are damaged on the screen for future redraw.
12449     */
12450    private void damageShadowReceiver() {
12451        final AttachInfo ai = mAttachInfo;
12452        if (ai != null) {
12453            ViewParent p = getParent();
12454            if (p != null && p instanceof ViewGroup) {
12455                final ViewGroup vg = (ViewGroup) p;
12456                vg.damageInParent();
12457            }
12458        }
12459    }
12460
12461    /**
12462     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
12463     * set any flags or handle all of the cases handled by the default invalidation methods.
12464     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
12465     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
12466     * walk up the hierarchy, transforming the dirty rect as necessary.
12467     *
12468     * The method also handles normal invalidation logic if display list properties are not
12469     * being used in this view. The invalidateParent and forceRedraw flags are used by that
12470     * backup approach, to handle these cases used in the various property-setting methods.
12471     *
12472     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
12473     * are not being used in this view
12474     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
12475     * list properties are not being used in this view
12476     */
12477    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
12478        if (!isHardwareAccelerated()
12479                || !mRenderNode.isValid()
12480                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
12481            if (invalidateParent) {
12482                invalidateParentCaches();
12483            }
12484            if (forceRedraw) {
12485                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
12486            }
12487            invalidate(false);
12488        } else {
12489            damageInParent();
12490        }
12491        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
12492            damageShadowReceiver();
12493        }
12494    }
12495
12496    /**
12497     * Tells the parent view to damage this view's bounds.
12498     *
12499     * @hide
12500     */
12501    protected void damageInParent() {
12502        final AttachInfo ai = mAttachInfo;
12503        final ViewParent p = mParent;
12504        if (p != null && ai != null) {
12505            final Rect r = ai.mTmpInvalRect;
12506            r.set(0, 0, mRight - mLeft, mBottom - mTop);
12507            if (mParent instanceof ViewGroup) {
12508                ((ViewGroup) mParent).damageChild(this, r);
12509            } else {
12510                mParent.invalidateChild(this, r);
12511            }
12512        }
12513    }
12514
12515    /**
12516     * Utility method to transform a given Rect by the current matrix of this view.
12517     */
12518    void transformRect(final Rect rect) {
12519        if (!getMatrix().isIdentity()) {
12520            RectF boundingRect = mAttachInfo.mTmpTransformRect;
12521            boundingRect.set(rect);
12522            getMatrix().mapRect(boundingRect);
12523            rect.set((int) Math.floor(boundingRect.left),
12524                    (int) Math.floor(boundingRect.top),
12525                    (int) Math.ceil(boundingRect.right),
12526                    (int) Math.ceil(boundingRect.bottom));
12527        }
12528    }
12529
12530    /**
12531     * Used to indicate that the parent of this view should clear its caches. This functionality
12532     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12533     * which is necessary when various parent-managed properties of the view change, such as
12534     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
12535     * clears the parent caches and does not causes an invalidate event.
12536     *
12537     * @hide
12538     */
12539    protected void invalidateParentCaches() {
12540        if (mParent instanceof View) {
12541            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
12542        }
12543    }
12544
12545    /**
12546     * Used to indicate that the parent of this view should be invalidated. This functionality
12547     * is used to force the parent to rebuild its display list (when hardware-accelerated),
12548     * which is necessary when various parent-managed properties of the view change, such as
12549     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
12550     * an invalidation event to the parent.
12551     *
12552     * @hide
12553     */
12554    protected void invalidateParentIfNeeded() {
12555        if (isHardwareAccelerated() && mParent instanceof View) {
12556            ((View) mParent).invalidate(true);
12557        }
12558    }
12559
12560    /**
12561     * @hide
12562     */
12563    protected void invalidateParentIfNeededAndWasQuickRejected() {
12564        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
12565            // View was rejected last time it was drawn by its parent; this may have changed
12566            invalidateParentIfNeeded();
12567        }
12568    }
12569
12570    /**
12571     * Indicates whether this View is opaque. An opaque View guarantees that it will
12572     * draw all the pixels overlapping its bounds using a fully opaque color.
12573     *
12574     * Subclasses of View should override this method whenever possible to indicate
12575     * whether an instance is opaque. Opaque Views are treated in a special way by
12576     * the View hierarchy, possibly allowing it to perform optimizations during
12577     * invalidate/draw passes.
12578     *
12579     * @return True if this View is guaranteed to be fully opaque, false otherwise.
12580     */
12581    @ViewDebug.ExportedProperty(category = "drawing")
12582    public boolean isOpaque() {
12583        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
12584                getFinalAlpha() >= 1.0f;
12585    }
12586
12587    /**
12588     * @hide
12589     */
12590    protected void computeOpaqueFlags() {
12591        // Opaque if:
12592        //   - Has a background
12593        //   - Background is opaque
12594        //   - Doesn't have scrollbars or scrollbars overlay
12595
12596        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
12597            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
12598        } else {
12599            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
12600        }
12601
12602        final int flags = mViewFlags;
12603        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
12604                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
12605                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
12606            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
12607        } else {
12608            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
12609        }
12610    }
12611
12612    /**
12613     * @hide
12614     */
12615    protected boolean hasOpaqueScrollbars() {
12616        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
12617    }
12618
12619    /**
12620     * @return A handler associated with the thread running the View. This
12621     * handler can be used to pump events in the UI events queue.
12622     */
12623    public Handler getHandler() {
12624        final AttachInfo attachInfo = mAttachInfo;
12625        if (attachInfo != null) {
12626            return attachInfo.mHandler;
12627        }
12628        return null;
12629    }
12630
12631    /**
12632     * Gets the view root associated with the View.
12633     * @return The view root, or null if none.
12634     * @hide
12635     */
12636    public ViewRootImpl getViewRootImpl() {
12637        if (mAttachInfo != null) {
12638            return mAttachInfo.mViewRootImpl;
12639        }
12640        return null;
12641    }
12642
12643    /**
12644     * @hide
12645     */
12646    public HardwareRenderer getHardwareRenderer() {
12647        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
12648    }
12649
12650    /**
12651     * <p>Causes the Runnable to be added to the message queue.
12652     * The runnable will be run on the user interface thread.</p>
12653     *
12654     * @param action The Runnable that will be executed.
12655     *
12656     * @return Returns true if the Runnable was successfully placed in to the
12657     *         message queue.  Returns false on failure, usually because the
12658     *         looper processing the message queue is exiting.
12659     *
12660     * @see #postDelayed
12661     * @see #removeCallbacks
12662     */
12663    public boolean post(Runnable action) {
12664        final AttachInfo attachInfo = mAttachInfo;
12665        if (attachInfo != null) {
12666            return attachInfo.mHandler.post(action);
12667        }
12668        // Assume that post will succeed later
12669        ViewRootImpl.getRunQueue().post(action);
12670        return true;
12671    }
12672
12673    /**
12674     * <p>Causes the Runnable to be added to the message queue, to be run
12675     * after the specified amount of time elapses.
12676     * The runnable will be run on the user interface thread.</p>
12677     *
12678     * @param action The Runnable that will be executed.
12679     * @param delayMillis The delay (in milliseconds) until the Runnable
12680     *        will be executed.
12681     *
12682     * @return true if the Runnable was successfully placed in to the
12683     *         message queue.  Returns false on failure, usually because the
12684     *         looper processing the message queue is exiting.  Note that a
12685     *         result of true does not mean the Runnable will be processed --
12686     *         if the looper is quit before the delivery time of the message
12687     *         occurs then the message will be dropped.
12688     *
12689     * @see #post
12690     * @see #removeCallbacks
12691     */
12692    public boolean postDelayed(Runnable action, long delayMillis) {
12693        final AttachInfo attachInfo = mAttachInfo;
12694        if (attachInfo != null) {
12695            return attachInfo.mHandler.postDelayed(action, delayMillis);
12696        }
12697        // Assume that post will succeed later
12698        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12699        return true;
12700    }
12701
12702    /**
12703     * <p>Causes the Runnable to execute on the next animation time step.
12704     * The runnable will be run on the user interface thread.</p>
12705     *
12706     * @param action The Runnable that will be executed.
12707     *
12708     * @see #postOnAnimationDelayed
12709     * @see #removeCallbacks
12710     */
12711    public void postOnAnimation(Runnable action) {
12712        final AttachInfo attachInfo = mAttachInfo;
12713        if (attachInfo != null) {
12714            attachInfo.mViewRootImpl.mChoreographer.postCallback(
12715                    Choreographer.CALLBACK_ANIMATION, action, null);
12716        } else {
12717            // Assume that post will succeed later
12718            ViewRootImpl.getRunQueue().post(action);
12719        }
12720    }
12721
12722    /**
12723     * <p>Causes the Runnable to execute on the next animation time step,
12724     * after the specified amount of time elapses.
12725     * The runnable will be run on the user interface thread.</p>
12726     *
12727     * @param action The Runnable that will be executed.
12728     * @param delayMillis The delay (in milliseconds) until the Runnable
12729     *        will be executed.
12730     *
12731     * @see #postOnAnimation
12732     * @see #removeCallbacks
12733     */
12734    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
12735        final AttachInfo attachInfo = mAttachInfo;
12736        if (attachInfo != null) {
12737            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
12738                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
12739        } else {
12740            // Assume that post will succeed later
12741            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
12742        }
12743    }
12744
12745    /**
12746     * <p>Removes the specified Runnable from the message queue.</p>
12747     *
12748     * @param action The Runnable to remove from the message handling queue
12749     *
12750     * @return true if this view could ask the Handler to remove the Runnable,
12751     *         false otherwise. When the returned value is true, the Runnable
12752     *         may or may not have been actually removed from the message queue
12753     *         (for instance, if the Runnable was not in the queue already.)
12754     *
12755     * @see #post
12756     * @see #postDelayed
12757     * @see #postOnAnimation
12758     * @see #postOnAnimationDelayed
12759     */
12760    public boolean removeCallbacks(Runnable action) {
12761        if (action != null) {
12762            final AttachInfo attachInfo = mAttachInfo;
12763            if (attachInfo != null) {
12764                attachInfo.mHandler.removeCallbacks(action);
12765                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
12766                        Choreographer.CALLBACK_ANIMATION, action, null);
12767            }
12768            // Assume that post will succeed later
12769            ViewRootImpl.getRunQueue().removeCallbacks(action);
12770        }
12771        return true;
12772    }
12773
12774    /**
12775     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
12776     * Use this to invalidate the View from a non-UI thread.</p>
12777     *
12778     * <p>This method can be invoked from outside of the UI thread
12779     * only when this View is attached to a window.</p>
12780     *
12781     * @see #invalidate()
12782     * @see #postInvalidateDelayed(long)
12783     */
12784    public void postInvalidate() {
12785        postInvalidateDelayed(0);
12786    }
12787
12788    /**
12789     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12790     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
12791     *
12792     * <p>This method can be invoked from outside of the UI thread
12793     * only when this View is attached to a window.</p>
12794     *
12795     * @param left The left coordinate of the rectangle to invalidate.
12796     * @param top The top coordinate of the rectangle to invalidate.
12797     * @param right The right coordinate of the rectangle to invalidate.
12798     * @param bottom The bottom coordinate of the rectangle to invalidate.
12799     *
12800     * @see #invalidate(int, int, int, int)
12801     * @see #invalidate(Rect)
12802     * @see #postInvalidateDelayed(long, int, int, int, int)
12803     */
12804    public void postInvalidate(int left, int top, int right, int bottom) {
12805        postInvalidateDelayed(0, left, top, right, bottom);
12806    }
12807
12808    /**
12809     * <p>Cause an invalidate to happen on a subsequent cycle through the event
12810     * loop. Waits for the specified amount of time.</p>
12811     *
12812     * <p>This method can be invoked from outside of the UI thread
12813     * only when this View is attached to a window.</p>
12814     *
12815     * @param delayMilliseconds the duration in milliseconds to delay the
12816     *         invalidation by
12817     *
12818     * @see #invalidate()
12819     * @see #postInvalidate()
12820     */
12821    public void postInvalidateDelayed(long delayMilliseconds) {
12822        // We try only with the AttachInfo because there's no point in invalidating
12823        // if we are not attached to our window
12824        final AttachInfo attachInfo = mAttachInfo;
12825        if (attachInfo != null) {
12826            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
12827        }
12828    }
12829
12830    /**
12831     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
12832     * through the event loop. Waits for the specified amount of time.</p>
12833     *
12834     * <p>This method can be invoked from outside of the UI thread
12835     * only when this View is attached to a window.</p>
12836     *
12837     * @param delayMilliseconds the duration in milliseconds to delay the
12838     *         invalidation by
12839     * @param left The left coordinate of the rectangle to invalidate.
12840     * @param top The top coordinate of the rectangle to invalidate.
12841     * @param right The right coordinate of the rectangle to invalidate.
12842     * @param bottom The bottom coordinate of the rectangle to invalidate.
12843     *
12844     * @see #invalidate(int, int, int, int)
12845     * @see #invalidate(Rect)
12846     * @see #postInvalidate(int, int, int, int)
12847     */
12848    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
12849            int right, int bottom) {
12850
12851        // We try only with the AttachInfo because there's no point in invalidating
12852        // if we are not attached to our window
12853        final AttachInfo attachInfo = mAttachInfo;
12854        if (attachInfo != null) {
12855            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12856            info.target = this;
12857            info.left = left;
12858            info.top = top;
12859            info.right = right;
12860            info.bottom = bottom;
12861
12862            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
12863        }
12864    }
12865
12866    /**
12867     * <p>Cause an invalidate to happen on the next animation time step, typically the
12868     * next display frame.</p>
12869     *
12870     * <p>This method can be invoked from outside of the UI thread
12871     * only when this View is attached to a window.</p>
12872     *
12873     * @see #invalidate()
12874     */
12875    public void postInvalidateOnAnimation() {
12876        // We try only with the AttachInfo because there's no point in invalidating
12877        // if we are not attached to our window
12878        final AttachInfo attachInfo = mAttachInfo;
12879        if (attachInfo != null) {
12880            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
12881        }
12882    }
12883
12884    /**
12885     * <p>Cause an invalidate of the specified area to happen on the next animation
12886     * time step, typically the next display frame.</p>
12887     *
12888     * <p>This method can be invoked from outside of the UI thread
12889     * only when this View is attached to a window.</p>
12890     *
12891     * @param left The left coordinate of the rectangle to invalidate.
12892     * @param top The top coordinate of the rectangle to invalidate.
12893     * @param right The right coordinate of the rectangle to invalidate.
12894     * @param bottom The bottom coordinate of the rectangle to invalidate.
12895     *
12896     * @see #invalidate(int, int, int, int)
12897     * @see #invalidate(Rect)
12898     */
12899    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12900        // We try only with the AttachInfo because there's no point in invalidating
12901        // if we are not attached to our window
12902        final AttachInfo attachInfo = mAttachInfo;
12903        if (attachInfo != null) {
12904            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12905            info.target = this;
12906            info.left = left;
12907            info.top = top;
12908            info.right = right;
12909            info.bottom = bottom;
12910
12911            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12912        }
12913    }
12914
12915    /**
12916     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12917     * This event is sent at most once every
12918     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12919     */
12920    private void postSendViewScrolledAccessibilityEventCallback() {
12921        if (mSendViewScrolledAccessibilityEvent == null) {
12922            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12923        }
12924        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12925            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12926            postDelayed(mSendViewScrolledAccessibilityEvent,
12927                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12928        }
12929    }
12930
12931    /**
12932     * Called by a parent to request that a child update its values for mScrollX
12933     * and mScrollY if necessary. This will typically be done if the child is
12934     * animating a scroll using a {@link android.widget.Scroller Scroller}
12935     * object.
12936     */
12937    public void computeScroll() {
12938    }
12939
12940    /**
12941     * <p>Indicate whether the horizontal edges are faded when the view is
12942     * scrolled horizontally.</p>
12943     *
12944     * @return true if the horizontal edges should are faded on scroll, false
12945     *         otherwise
12946     *
12947     * @see #setHorizontalFadingEdgeEnabled(boolean)
12948     *
12949     * @attr ref android.R.styleable#View_requiresFadingEdge
12950     */
12951    public boolean isHorizontalFadingEdgeEnabled() {
12952        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12953    }
12954
12955    /**
12956     * <p>Define whether the horizontal edges should be faded when this view
12957     * is scrolled horizontally.</p>
12958     *
12959     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12960     *                                    be faded when the view is scrolled
12961     *                                    horizontally
12962     *
12963     * @see #isHorizontalFadingEdgeEnabled()
12964     *
12965     * @attr ref android.R.styleable#View_requiresFadingEdge
12966     */
12967    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12968        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12969            if (horizontalFadingEdgeEnabled) {
12970                initScrollCache();
12971            }
12972
12973            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12974        }
12975    }
12976
12977    /**
12978     * <p>Indicate whether the vertical edges are faded when the view is
12979     * scrolled horizontally.</p>
12980     *
12981     * @return true if the vertical edges should are faded on scroll, false
12982     *         otherwise
12983     *
12984     * @see #setVerticalFadingEdgeEnabled(boolean)
12985     *
12986     * @attr ref android.R.styleable#View_requiresFadingEdge
12987     */
12988    public boolean isVerticalFadingEdgeEnabled() {
12989        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12990    }
12991
12992    /**
12993     * <p>Define whether the vertical edges should be faded when this view
12994     * is scrolled vertically.</p>
12995     *
12996     * @param verticalFadingEdgeEnabled true if the vertical edges should
12997     *                                  be faded when the view is scrolled
12998     *                                  vertically
12999     *
13000     * @see #isVerticalFadingEdgeEnabled()
13001     *
13002     * @attr ref android.R.styleable#View_requiresFadingEdge
13003     */
13004    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
13005        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
13006            if (verticalFadingEdgeEnabled) {
13007                initScrollCache();
13008            }
13009
13010            mViewFlags ^= FADING_EDGE_VERTICAL;
13011        }
13012    }
13013
13014    /**
13015     * Returns the strength, or intensity, of the top faded edge. The strength is
13016     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13017     * returns 0.0 or 1.0 but no value in between.
13018     *
13019     * Subclasses should override this method to provide a smoother fade transition
13020     * when scrolling occurs.
13021     *
13022     * @return the intensity of the top fade as a float between 0.0f and 1.0f
13023     */
13024    protected float getTopFadingEdgeStrength() {
13025        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
13026    }
13027
13028    /**
13029     * Returns the strength, or intensity, of the bottom faded edge. The strength is
13030     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13031     * returns 0.0 or 1.0 but no value in between.
13032     *
13033     * Subclasses should override this method to provide a smoother fade transition
13034     * when scrolling occurs.
13035     *
13036     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
13037     */
13038    protected float getBottomFadingEdgeStrength() {
13039        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
13040                computeVerticalScrollRange() ? 1.0f : 0.0f;
13041    }
13042
13043    /**
13044     * Returns the strength, or intensity, of the left faded edge. The strength is
13045     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13046     * returns 0.0 or 1.0 but no value in between.
13047     *
13048     * Subclasses should override this method to provide a smoother fade transition
13049     * when scrolling occurs.
13050     *
13051     * @return the intensity of the left fade as a float between 0.0f and 1.0f
13052     */
13053    protected float getLeftFadingEdgeStrength() {
13054        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
13055    }
13056
13057    /**
13058     * Returns the strength, or intensity, of the right faded edge. The strength is
13059     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
13060     * returns 0.0 or 1.0 but no value in between.
13061     *
13062     * Subclasses should override this method to provide a smoother fade transition
13063     * when scrolling occurs.
13064     *
13065     * @return the intensity of the right fade as a float between 0.0f and 1.0f
13066     */
13067    protected float getRightFadingEdgeStrength() {
13068        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
13069                computeHorizontalScrollRange() ? 1.0f : 0.0f;
13070    }
13071
13072    /**
13073     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
13074     * scrollbar is not drawn by default.</p>
13075     *
13076     * @return true if the horizontal scrollbar should be painted, false
13077     *         otherwise
13078     *
13079     * @see #setHorizontalScrollBarEnabled(boolean)
13080     */
13081    public boolean isHorizontalScrollBarEnabled() {
13082        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13083    }
13084
13085    /**
13086     * <p>Define whether the horizontal scrollbar should be drawn or not. The
13087     * scrollbar is not drawn by default.</p>
13088     *
13089     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
13090     *                                   be painted
13091     *
13092     * @see #isHorizontalScrollBarEnabled()
13093     */
13094    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
13095        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
13096            mViewFlags ^= SCROLLBARS_HORIZONTAL;
13097            computeOpaqueFlags();
13098            resolvePadding();
13099        }
13100    }
13101
13102    /**
13103     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
13104     * scrollbar is not drawn by default.</p>
13105     *
13106     * @return true if the vertical scrollbar should be painted, false
13107     *         otherwise
13108     *
13109     * @see #setVerticalScrollBarEnabled(boolean)
13110     */
13111    public boolean isVerticalScrollBarEnabled() {
13112        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
13113    }
13114
13115    /**
13116     * <p>Define whether the vertical scrollbar should be drawn or not. The
13117     * scrollbar is not drawn by default.</p>
13118     *
13119     * @param verticalScrollBarEnabled true if the vertical scrollbar should
13120     *                                 be painted
13121     *
13122     * @see #isVerticalScrollBarEnabled()
13123     */
13124    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
13125        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
13126            mViewFlags ^= SCROLLBARS_VERTICAL;
13127            computeOpaqueFlags();
13128            resolvePadding();
13129        }
13130    }
13131
13132    /**
13133     * @hide
13134     */
13135    protected void recomputePadding() {
13136        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13137    }
13138
13139    /**
13140     * Define whether scrollbars will fade when the view is not scrolling.
13141     *
13142     * @param fadeScrollbars whether to enable fading
13143     *
13144     * @attr ref android.R.styleable#View_fadeScrollbars
13145     */
13146    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
13147        initScrollCache();
13148        final ScrollabilityCache scrollabilityCache = mScrollCache;
13149        scrollabilityCache.fadeScrollBars = fadeScrollbars;
13150        if (fadeScrollbars) {
13151            scrollabilityCache.state = ScrollabilityCache.OFF;
13152        } else {
13153            scrollabilityCache.state = ScrollabilityCache.ON;
13154        }
13155    }
13156
13157    /**
13158     *
13159     * Returns true if scrollbars will fade when this view is not scrolling
13160     *
13161     * @return true if scrollbar fading is enabled
13162     *
13163     * @attr ref android.R.styleable#View_fadeScrollbars
13164     */
13165    public boolean isScrollbarFadingEnabled() {
13166        return mScrollCache != null && mScrollCache.fadeScrollBars;
13167    }
13168
13169    /**
13170     *
13171     * Returns the delay before scrollbars fade.
13172     *
13173     * @return the delay before scrollbars fade
13174     *
13175     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13176     */
13177    public int getScrollBarDefaultDelayBeforeFade() {
13178        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
13179                mScrollCache.scrollBarDefaultDelayBeforeFade;
13180    }
13181
13182    /**
13183     * Define the delay before scrollbars fade.
13184     *
13185     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
13186     *
13187     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
13188     */
13189    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
13190        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
13191    }
13192
13193    /**
13194     *
13195     * Returns the scrollbar fade duration.
13196     *
13197     * @return the scrollbar fade duration
13198     *
13199     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13200     */
13201    public int getScrollBarFadeDuration() {
13202        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
13203                mScrollCache.scrollBarFadeDuration;
13204    }
13205
13206    /**
13207     * Define the scrollbar fade duration.
13208     *
13209     * @param scrollBarFadeDuration - the scrollbar fade duration
13210     *
13211     * @attr ref android.R.styleable#View_scrollbarFadeDuration
13212     */
13213    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
13214        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
13215    }
13216
13217    /**
13218     *
13219     * Returns the scrollbar size.
13220     *
13221     * @return the scrollbar size
13222     *
13223     * @attr ref android.R.styleable#View_scrollbarSize
13224     */
13225    public int getScrollBarSize() {
13226        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
13227                mScrollCache.scrollBarSize;
13228    }
13229
13230    /**
13231     * Define the scrollbar size.
13232     *
13233     * @param scrollBarSize - the scrollbar size
13234     *
13235     * @attr ref android.R.styleable#View_scrollbarSize
13236     */
13237    public void setScrollBarSize(int scrollBarSize) {
13238        getScrollCache().scrollBarSize = scrollBarSize;
13239    }
13240
13241    /**
13242     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
13243     * inset. When inset, they add to the padding of the view. And the scrollbars
13244     * can be drawn inside the padding area or on the edge of the view. For example,
13245     * if a view has a background drawable and you want to draw the scrollbars
13246     * inside the padding specified by the drawable, you can use
13247     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
13248     * appear at the edge of the view, ignoring the padding, then you can use
13249     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
13250     * @param style the style of the scrollbars. Should be one of
13251     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
13252     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
13253     * @see #SCROLLBARS_INSIDE_OVERLAY
13254     * @see #SCROLLBARS_INSIDE_INSET
13255     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13256     * @see #SCROLLBARS_OUTSIDE_INSET
13257     *
13258     * @attr ref android.R.styleable#View_scrollbarStyle
13259     */
13260    public void setScrollBarStyle(@ScrollBarStyle int style) {
13261        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
13262            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
13263            computeOpaqueFlags();
13264            resolvePadding();
13265        }
13266    }
13267
13268    /**
13269     * <p>Returns the current scrollbar style.</p>
13270     * @return the current scrollbar style
13271     * @see #SCROLLBARS_INSIDE_OVERLAY
13272     * @see #SCROLLBARS_INSIDE_INSET
13273     * @see #SCROLLBARS_OUTSIDE_OVERLAY
13274     * @see #SCROLLBARS_OUTSIDE_INSET
13275     *
13276     * @attr ref android.R.styleable#View_scrollbarStyle
13277     */
13278    @ViewDebug.ExportedProperty(mapping = {
13279            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
13280            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
13281            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
13282            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
13283    })
13284    @ScrollBarStyle
13285    public int getScrollBarStyle() {
13286        return mViewFlags & SCROLLBARS_STYLE_MASK;
13287    }
13288
13289    /**
13290     * <p>Compute the horizontal range that the horizontal scrollbar
13291     * represents.</p>
13292     *
13293     * <p>The range is expressed in arbitrary units that must be the same as the
13294     * units used by {@link #computeHorizontalScrollExtent()} and
13295     * {@link #computeHorizontalScrollOffset()}.</p>
13296     *
13297     * <p>The default range is the drawing width of this view.</p>
13298     *
13299     * @return the total horizontal range represented by the horizontal
13300     *         scrollbar
13301     *
13302     * @see #computeHorizontalScrollExtent()
13303     * @see #computeHorizontalScrollOffset()
13304     * @see android.widget.ScrollBarDrawable
13305     */
13306    protected int computeHorizontalScrollRange() {
13307        return getWidth();
13308    }
13309
13310    /**
13311     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
13312     * within the horizontal range. This value is used to compute the position
13313     * of the thumb within the scrollbar's track.</p>
13314     *
13315     * <p>The range is expressed in arbitrary units that must be the same as the
13316     * units used by {@link #computeHorizontalScrollRange()} and
13317     * {@link #computeHorizontalScrollExtent()}.</p>
13318     *
13319     * <p>The default offset is the scroll offset of this view.</p>
13320     *
13321     * @return the horizontal offset of the scrollbar's thumb
13322     *
13323     * @see #computeHorizontalScrollRange()
13324     * @see #computeHorizontalScrollExtent()
13325     * @see android.widget.ScrollBarDrawable
13326     */
13327    protected int computeHorizontalScrollOffset() {
13328        return mScrollX;
13329    }
13330
13331    /**
13332     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
13333     * within the horizontal range. This value is used to compute the length
13334     * of the thumb within the scrollbar's track.</p>
13335     *
13336     * <p>The range is expressed in arbitrary units that must be the same as the
13337     * units used by {@link #computeHorizontalScrollRange()} and
13338     * {@link #computeHorizontalScrollOffset()}.</p>
13339     *
13340     * <p>The default extent is the drawing width of this view.</p>
13341     *
13342     * @return the horizontal extent of the scrollbar's thumb
13343     *
13344     * @see #computeHorizontalScrollRange()
13345     * @see #computeHorizontalScrollOffset()
13346     * @see android.widget.ScrollBarDrawable
13347     */
13348    protected int computeHorizontalScrollExtent() {
13349        return getWidth();
13350    }
13351
13352    /**
13353     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
13354     *
13355     * <p>The range is expressed in arbitrary units that must be the same as the
13356     * units used by {@link #computeVerticalScrollExtent()} and
13357     * {@link #computeVerticalScrollOffset()}.</p>
13358     *
13359     * @return the total vertical range represented by the vertical scrollbar
13360     *
13361     * <p>The default range is the drawing height of this view.</p>
13362     *
13363     * @see #computeVerticalScrollExtent()
13364     * @see #computeVerticalScrollOffset()
13365     * @see android.widget.ScrollBarDrawable
13366     */
13367    protected int computeVerticalScrollRange() {
13368        return getHeight();
13369    }
13370
13371    /**
13372     * <p>Compute the vertical offset of the vertical scrollbar's thumb
13373     * within the horizontal range. This value is used to compute the position
13374     * of the thumb within the scrollbar's track.</p>
13375     *
13376     * <p>The range is expressed in arbitrary units that must be the same as the
13377     * units used by {@link #computeVerticalScrollRange()} and
13378     * {@link #computeVerticalScrollExtent()}.</p>
13379     *
13380     * <p>The default offset is the scroll offset of this view.</p>
13381     *
13382     * @return the vertical offset of the scrollbar's thumb
13383     *
13384     * @see #computeVerticalScrollRange()
13385     * @see #computeVerticalScrollExtent()
13386     * @see android.widget.ScrollBarDrawable
13387     */
13388    protected int computeVerticalScrollOffset() {
13389        return mScrollY;
13390    }
13391
13392    /**
13393     * <p>Compute the vertical extent of the vertical scrollbar's thumb
13394     * within the vertical range. This value is used to compute the length
13395     * of the thumb within the scrollbar's track.</p>
13396     *
13397     * <p>The range is expressed in arbitrary units that must be the same as the
13398     * units used by {@link #computeVerticalScrollRange()} and
13399     * {@link #computeVerticalScrollOffset()}.</p>
13400     *
13401     * <p>The default extent is the drawing height of this view.</p>
13402     *
13403     * @return the vertical extent of the scrollbar's thumb
13404     *
13405     * @see #computeVerticalScrollRange()
13406     * @see #computeVerticalScrollOffset()
13407     * @see android.widget.ScrollBarDrawable
13408     */
13409    protected int computeVerticalScrollExtent() {
13410        return getHeight();
13411    }
13412
13413    /**
13414     * Check if this view can be scrolled horizontally in a certain direction.
13415     *
13416     * @param direction Negative to check scrolling left, positive to check scrolling right.
13417     * @return true if this view can be scrolled in the specified direction, false otherwise.
13418     */
13419    public boolean canScrollHorizontally(int direction) {
13420        final int offset = computeHorizontalScrollOffset();
13421        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
13422        if (range == 0) return false;
13423        if (direction < 0) {
13424            return offset > 0;
13425        } else {
13426            return offset < range - 1;
13427        }
13428    }
13429
13430    /**
13431     * Check if this view can be scrolled vertically in a certain direction.
13432     *
13433     * @param direction Negative to check scrolling up, positive to check scrolling down.
13434     * @return true if this view can be scrolled in the specified direction, false otherwise.
13435     */
13436    public boolean canScrollVertically(int direction) {
13437        final int offset = computeVerticalScrollOffset();
13438        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
13439        if (range == 0) return false;
13440        if (direction < 0) {
13441            return offset > 0;
13442        } else {
13443            return offset < range - 1;
13444        }
13445    }
13446
13447    /**
13448     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
13449     * scrollbars are painted only if they have been awakened first.</p>
13450     *
13451     * @param canvas the canvas on which to draw the scrollbars
13452     *
13453     * @see #awakenScrollBars(int)
13454     */
13455    protected final void onDrawScrollBars(Canvas canvas) {
13456        // scrollbars are drawn only when the animation is running
13457        final ScrollabilityCache cache = mScrollCache;
13458        if (cache != null) {
13459
13460            int state = cache.state;
13461
13462            if (state == ScrollabilityCache.OFF) {
13463                return;
13464            }
13465
13466            boolean invalidate = false;
13467
13468            if (state == ScrollabilityCache.FADING) {
13469                // We're fading -- get our fade interpolation
13470                if (cache.interpolatorValues == null) {
13471                    cache.interpolatorValues = new float[1];
13472                }
13473
13474                float[] values = cache.interpolatorValues;
13475
13476                // Stops the animation if we're done
13477                if (cache.scrollBarInterpolator.timeToValues(values) ==
13478                        Interpolator.Result.FREEZE_END) {
13479                    cache.state = ScrollabilityCache.OFF;
13480                } else {
13481                    cache.scrollBar.mutate().setAlpha(Math.round(values[0]));
13482                }
13483
13484                // This will make the scroll bars inval themselves after
13485                // drawing. We only want this when we're fading so that
13486                // we prevent excessive redraws
13487                invalidate = true;
13488            } else {
13489                // We're just on -- but we may have been fading before so
13490                // reset alpha
13491                cache.scrollBar.mutate().setAlpha(255);
13492            }
13493
13494
13495            final int viewFlags = mViewFlags;
13496
13497            final boolean drawHorizontalScrollBar =
13498                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
13499            final boolean drawVerticalScrollBar =
13500                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
13501                && !isVerticalScrollBarHidden();
13502
13503            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
13504                final int width = mRight - mLeft;
13505                final int height = mBottom - mTop;
13506
13507                final ScrollBarDrawable scrollBar = cache.scrollBar;
13508
13509                final int scrollX = mScrollX;
13510                final int scrollY = mScrollY;
13511                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
13512
13513                int left;
13514                int top;
13515                int right;
13516                int bottom;
13517
13518                if (drawHorizontalScrollBar) {
13519                    int size = scrollBar.getSize(false);
13520                    if (size <= 0) {
13521                        size = cache.scrollBarSize;
13522                    }
13523
13524                    scrollBar.setParameters(computeHorizontalScrollRange(),
13525                                            computeHorizontalScrollOffset(),
13526                                            computeHorizontalScrollExtent(), false);
13527                    final int verticalScrollBarGap = drawVerticalScrollBar ?
13528                            getVerticalScrollbarWidth() : 0;
13529                    top = scrollY + height - size - (mUserPaddingBottom & inside);
13530                    left = scrollX + (mPaddingLeft & inside);
13531                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
13532                    bottom = top + size;
13533                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
13534                    if (invalidate) {
13535                        invalidate(left, top, right, bottom);
13536                    }
13537                }
13538
13539                if (drawVerticalScrollBar) {
13540                    int size = scrollBar.getSize(true);
13541                    if (size <= 0) {
13542                        size = cache.scrollBarSize;
13543                    }
13544
13545                    scrollBar.setParameters(computeVerticalScrollRange(),
13546                                            computeVerticalScrollOffset(),
13547                                            computeVerticalScrollExtent(), true);
13548                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
13549                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
13550                        verticalScrollbarPosition = isLayoutRtl() ?
13551                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
13552                    }
13553                    switch (verticalScrollbarPosition) {
13554                        default:
13555                        case SCROLLBAR_POSITION_RIGHT:
13556                            left = scrollX + width - size - (mUserPaddingRight & inside);
13557                            break;
13558                        case SCROLLBAR_POSITION_LEFT:
13559                            left = scrollX + (mUserPaddingLeft & inside);
13560                            break;
13561                    }
13562                    top = scrollY + (mPaddingTop & inside);
13563                    right = left + size;
13564                    bottom = scrollY + height - (mUserPaddingBottom & inside);
13565                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
13566                    if (invalidate) {
13567                        invalidate(left, top, right, bottom);
13568                    }
13569                }
13570            }
13571        }
13572    }
13573
13574    /**
13575     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
13576     * FastScroller is visible.
13577     * @return whether to temporarily hide the vertical scrollbar
13578     * @hide
13579     */
13580    protected boolean isVerticalScrollBarHidden() {
13581        return false;
13582    }
13583
13584    /**
13585     * <p>Draw the horizontal scrollbar if
13586     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
13587     *
13588     * @param canvas the canvas on which to draw the scrollbar
13589     * @param scrollBar the scrollbar's drawable
13590     *
13591     * @see #isHorizontalScrollBarEnabled()
13592     * @see #computeHorizontalScrollRange()
13593     * @see #computeHorizontalScrollExtent()
13594     * @see #computeHorizontalScrollOffset()
13595     * @see android.widget.ScrollBarDrawable
13596     * @hide
13597     */
13598    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
13599            int l, int t, int r, int b) {
13600        scrollBar.setBounds(l, t, r, b);
13601        scrollBar.draw(canvas);
13602    }
13603
13604    /**
13605     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
13606     * returns true.</p>
13607     *
13608     * @param canvas the canvas on which to draw the scrollbar
13609     * @param scrollBar the scrollbar's drawable
13610     *
13611     * @see #isVerticalScrollBarEnabled()
13612     * @see #computeVerticalScrollRange()
13613     * @see #computeVerticalScrollExtent()
13614     * @see #computeVerticalScrollOffset()
13615     * @see android.widget.ScrollBarDrawable
13616     * @hide
13617     */
13618    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
13619            int l, int t, int r, int b) {
13620        scrollBar.setBounds(l, t, r, b);
13621        scrollBar.draw(canvas);
13622    }
13623
13624    /**
13625     * Implement this to do your drawing.
13626     *
13627     * @param canvas the canvas on which the background will be drawn
13628     */
13629    protected void onDraw(Canvas canvas) {
13630    }
13631
13632    /*
13633     * Caller is responsible for calling requestLayout if necessary.
13634     * (This allows addViewInLayout to not request a new layout.)
13635     */
13636    void assignParent(ViewParent parent) {
13637        if (mParent == null) {
13638            mParent = parent;
13639        } else if (parent == null) {
13640            mParent = null;
13641        } else {
13642            throw new RuntimeException("view " + this + " being added, but"
13643                    + " it already has a parent");
13644        }
13645    }
13646
13647    /**
13648     * This is called when the view is attached to a window.  At this point it
13649     * has a Surface and will start drawing.  Note that this function is
13650     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
13651     * however it may be called any time before the first onDraw -- including
13652     * before or after {@link #onMeasure(int, int)}.
13653     *
13654     * @see #onDetachedFromWindow()
13655     */
13656    @CallSuper
13657    protected void onAttachedToWindow() {
13658        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
13659            mParent.requestTransparentRegion(this);
13660        }
13661
13662        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
13663            initialAwakenScrollBars();
13664            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
13665        }
13666
13667        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13668
13669        jumpDrawablesToCurrentState();
13670
13671        resetSubtreeAccessibilityStateChanged();
13672
13673        // rebuild, since Outline not maintained while View is detached
13674        rebuildOutline();
13675
13676        if (isFocused()) {
13677            InputMethodManager imm = InputMethodManager.peekInstance();
13678            if (imm != null) {
13679                imm.focusIn(this);
13680            }
13681        }
13682    }
13683
13684    /**
13685     * Resolve all RTL related properties.
13686     *
13687     * @return true if resolution of RTL properties has been done
13688     *
13689     * @hide
13690     */
13691    public boolean resolveRtlPropertiesIfNeeded() {
13692        if (!needRtlPropertiesResolution()) return false;
13693
13694        // Order is important here: LayoutDirection MUST be resolved first
13695        if (!isLayoutDirectionResolved()) {
13696            resolveLayoutDirection();
13697            resolveLayoutParams();
13698        }
13699        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
13700        if (!isTextDirectionResolved()) {
13701            resolveTextDirection();
13702        }
13703        if (!isTextAlignmentResolved()) {
13704            resolveTextAlignment();
13705        }
13706        // Should resolve Drawables before Padding because we need the layout direction of the
13707        // Drawable to correctly resolve Padding.
13708        if (!areDrawablesResolved()) {
13709            resolveDrawables();
13710        }
13711        if (!isPaddingResolved()) {
13712            resolvePadding();
13713        }
13714        onRtlPropertiesChanged(getLayoutDirection());
13715        return true;
13716    }
13717
13718    /**
13719     * Reset resolution of all RTL related properties.
13720     *
13721     * @hide
13722     */
13723    public void resetRtlProperties() {
13724        resetResolvedLayoutDirection();
13725        resetResolvedTextDirection();
13726        resetResolvedTextAlignment();
13727        resetResolvedPadding();
13728        resetResolvedDrawables();
13729    }
13730
13731    /**
13732     * @see #onScreenStateChanged(int)
13733     */
13734    void dispatchScreenStateChanged(int screenState) {
13735        onScreenStateChanged(screenState);
13736    }
13737
13738    /**
13739     * This method is called whenever the state of the screen this view is
13740     * attached to changes. A state change will usually occurs when the screen
13741     * turns on or off (whether it happens automatically or the user does it
13742     * manually.)
13743     *
13744     * @param screenState The new state of the screen. Can be either
13745     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
13746     */
13747    public void onScreenStateChanged(int screenState) {
13748    }
13749
13750    /**
13751     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
13752     */
13753    private boolean hasRtlSupport() {
13754        return mContext.getApplicationInfo().hasRtlSupport();
13755    }
13756
13757    /**
13758     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
13759     * RTL not supported)
13760     */
13761    private boolean isRtlCompatibilityMode() {
13762        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
13763        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
13764    }
13765
13766    /**
13767     * @return true if RTL properties need resolution.
13768     *
13769     */
13770    private boolean needRtlPropertiesResolution() {
13771        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
13772    }
13773
13774    /**
13775     * Called when any RTL property (layout direction or text direction or text alignment) has
13776     * been changed.
13777     *
13778     * Subclasses need to override this method to take care of cached information that depends on the
13779     * resolved layout direction, or to inform child views that inherit their layout direction.
13780     *
13781     * The default implementation does nothing.
13782     *
13783     * @param layoutDirection the direction of the layout
13784     *
13785     * @see #LAYOUT_DIRECTION_LTR
13786     * @see #LAYOUT_DIRECTION_RTL
13787     */
13788    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
13789    }
13790
13791    /**
13792     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
13793     * that the parent directionality can and will be resolved before its children.
13794     *
13795     * @return true if resolution has been done, false otherwise.
13796     *
13797     * @hide
13798     */
13799    public boolean resolveLayoutDirection() {
13800        // Clear any previous layout direction resolution
13801        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13802
13803        if (hasRtlSupport()) {
13804            // Set resolved depending on layout direction
13805            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
13806                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
13807                case LAYOUT_DIRECTION_INHERIT:
13808                    // We cannot resolve yet. LTR is by default and let the resolution happen again
13809                    // later to get the correct resolved value
13810                    if (!canResolveLayoutDirection()) return false;
13811
13812                    // Parent has not yet resolved, LTR is still the default
13813                    try {
13814                        if (!mParent.isLayoutDirectionResolved()) return false;
13815
13816                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13817                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13818                        }
13819                    } catch (AbstractMethodError e) {
13820                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13821                                " does not fully implement ViewParent", e);
13822                    }
13823                    break;
13824                case LAYOUT_DIRECTION_RTL:
13825                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13826                    break;
13827                case LAYOUT_DIRECTION_LOCALE:
13828                    if((LAYOUT_DIRECTION_RTL ==
13829                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
13830                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
13831                    }
13832                    break;
13833                default:
13834                    // Nothing to do, LTR by default
13835            }
13836        }
13837
13838        // Set to resolved
13839        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13840        return true;
13841    }
13842
13843    /**
13844     * Check if layout direction resolution can be done.
13845     *
13846     * @return true if layout direction resolution can be done otherwise return false.
13847     */
13848    public boolean canResolveLayoutDirection() {
13849        switch (getRawLayoutDirection()) {
13850            case LAYOUT_DIRECTION_INHERIT:
13851                if (mParent != null) {
13852                    try {
13853                        return mParent.canResolveLayoutDirection();
13854                    } catch (AbstractMethodError e) {
13855                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
13856                                " does not fully implement ViewParent", e);
13857                    }
13858                }
13859                return false;
13860
13861            default:
13862                return true;
13863        }
13864    }
13865
13866    /**
13867     * Reset the resolved layout direction. Layout direction will be resolved during a call to
13868     * {@link #onMeasure(int, int)}.
13869     *
13870     * @hide
13871     */
13872    public void resetResolvedLayoutDirection() {
13873        // Reset the current resolved bits
13874        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
13875    }
13876
13877    /**
13878     * @return true if the layout direction is inherited.
13879     *
13880     * @hide
13881     */
13882    public boolean isLayoutDirectionInherited() {
13883        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
13884    }
13885
13886    /**
13887     * @return true if layout direction has been resolved.
13888     */
13889    public boolean isLayoutDirectionResolved() {
13890        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
13891    }
13892
13893    /**
13894     * Return if padding has been resolved
13895     *
13896     * @hide
13897     */
13898    boolean isPaddingResolved() {
13899        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
13900    }
13901
13902    /**
13903     * Resolves padding depending on layout direction, if applicable, and
13904     * recomputes internal padding values to adjust for scroll bars.
13905     *
13906     * @hide
13907     */
13908    public void resolvePadding() {
13909        final int resolvedLayoutDirection = getLayoutDirection();
13910
13911        if (!isRtlCompatibilityMode()) {
13912            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13913            // If start / end padding are defined, they will be resolved (hence overriding) to
13914            // left / right or right / left depending on the resolved layout direction.
13915            // If start / end padding are not defined, use the left / right ones.
13916            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13917                Rect padding = sThreadLocal.get();
13918                if (padding == null) {
13919                    padding = new Rect();
13920                    sThreadLocal.set(padding);
13921                }
13922                mBackground.getPadding(padding);
13923                if (!mLeftPaddingDefined) {
13924                    mUserPaddingLeftInitial = padding.left;
13925                }
13926                if (!mRightPaddingDefined) {
13927                    mUserPaddingRightInitial = padding.right;
13928                }
13929            }
13930            switch (resolvedLayoutDirection) {
13931                case LAYOUT_DIRECTION_RTL:
13932                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13933                        mUserPaddingRight = mUserPaddingStart;
13934                    } else {
13935                        mUserPaddingRight = mUserPaddingRightInitial;
13936                    }
13937                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13938                        mUserPaddingLeft = mUserPaddingEnd;
13939                    } else {
13940                        mUserPaddingLeft = mUserPaddingLeftInitial;
13941                    }
13942                    break;
13943                case LAYOUT_DIRECTION_LTR:
13944                default:
13945                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13946                        mUserPaddingLeft = mUserPaddingStart;
13947                    } else {
13948                        mUserPaddingLeft = mUserPaddingLeftInitial;
13949                    }
13950                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13951                        mUserPaddingRight = mUserPaddingEnd;
13952                    } else {
13953                        mUserPaddingRight = mUserPaddingRightInitial;
13954                    }
13955            }
13956
13957            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13958        }
13959
13960        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13961        onRtlPropertiesChanged(resolvedLayoutDirection);
13962
13963        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13964    }
13965
13966    /**
13967     * Reset the resolved layout direction.
13968     *
13969     * @hide
13970     */
13971    public void resetResolvedPadding() {
13972        resetResolvedPaddingInternal();
13973    }
13974
13975    /**
13976     * Used when we only want to reset *this* view's padding and not trigger overrides
13977     * in ViewGroup that reset children too.
13978     */
13979    void resetResolvedPaddingInternal() {
13980        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13981    }
13982
13983    /**
13984     * This is called when the view is detached from a window.  At this point it
13985     * no longer has a surface for drawing.
13986     *
13987     * @see #onAttachedToWindow()
13988     */
13989    @CallSuper
13990    protected void onDetachedFromWindow() {
13991    }
13992
13993    /**
13994     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13995     * after onDetachedFromWindow().
13996     *
13997     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13998     * The super method should be called at the end of the overridden method to ensure
13999     * subclasses are destroyed first
14000     *
14001     * @hide
14002     */
14003    @CallSuper
14004    protected void onDetachedFromWindowInternal() {
14005        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
14006        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
14007
14008        removeUnsetPressCallback();
14009        removeLongPressCallback();
14010        removePerformClickCallback();
14011        removeSendViewScrolledAccessibilityEventCallback();
14012        stopNestedScroll();
14013
14014        // Anything that started animating right before detach should already
14015        // be in its final state when re-attached.
14016        jumpDrawablesToCurrentState();
14017
14018        destroyDrawingCache();
14019
14020        cleanupDraw();
14021        mCurrentAnimation = null;
14022    }
14023
14024    private void cleanupDraw() {
14025        resetDisplayList();
14026        if (mAttachInfo != null) {
14027            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
14028        }
14029    }
14030
14031    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
14032    }
14033
14034    /**
14035     * @return The number of times this view has been attached to a window
14036     */
14037    protected int getWindowAttachCount() {
14038        return mWindowAttachCount;
14039    }
14040
14041    /**
14042     * Retrieve a unique token identifying the window this view is attached to.
14043     * @return Return the window's token for use in
14044     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
14045     */
14046    public IBinder getWindowToken() {
14047        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
14048    }
14049
14050    /**
14051     * Retrieve the {@link WindowId} for the window this view is
14052     * currently attached to.
14053     */
14054    public WindowId getWindowId() {
14055        if (mAttachInfo == null) {
14056            return null;
14057        }
14058        if (mAttachInfo.mWindowId == null) {
14059            try {
14060                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
14061                        mAttachInfo.mWindowToken);
14062                mAttachInfo.mWindowId = new WindowId(
14063                        mAttachInfo.mIWindowId);
14064            } catch (RemoteException e) {
14065            }
14066        }
14067        return mAttachInfo.mWindowId;
14068    }
14069
14070    /**
14071     * Retrieve a unique token identifying the top-level "real" window of
14072     * the window that this view is attached to.  That is, this is like
14073     * {@link #getWindowToken}, except if the window this view in is a panel
14074     * window (attached to another containing window), then the token of
14075     * the containing window is returned instead.
14076     *
14077     * @return Returns the associated window token, either
14078     * {@link #getWindowToken()} or the containing window's token.
14079     */
14080    public IBinder getApplicationWindowToken() {
14081        AttachInfo ai = mAttachInfo;
14082        if (ai != null) {
14083            IBinder appWindowToken = ai.mPanelParentWindowToken;
14084            if (appWindowToken == null) {
14085                appWindowToken = ai.mWindowToken;
14086            }
14087            return appWindowToken;
14088        }
14089        return null;
14090    }
14091
14092    /**
14093     * Gets the logical display to which the view's window has been attached.
14094     *
14095     * @return The logical display, or null if the view is not currently attached to a window.
14096     */
14097    public Display getDisplay() {
14098        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
14099    }
14100
14101    /**
14102     * Retrieve private session object this view hierarchy is using to
14103     * communicate with the window manager.
14104     * @return the session object to communicate with the window manager
14105     */
14106    /*package*/ IWindowSession getWindowSession() {
14107        return mAttachInfo != null ? mAttachInfo.mSession : null;
14108    }
14109
14110    /**
14111     * @param info the {@link android.view.View.AttachInfo} to associated with
14112     *        this view
14113     */
14114    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
14115        //System.out.println("Attached! " + this);
14116        mAttachInfo = info;
14117        if (mOverlay != null) {
14118            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
14119        }
14120        mWindowAttachCount++;
14121        // We will need to evaluate the drawable state at least once.
14122        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14123        if (mFloatingTreeObserver != null) {
14124            info.mTreeObserver.merge(mFloatingTreeObserver);
14125            mFloatingTreeObserver = null;
14126        }
14127        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
14128            mAttachInfo.mScrollContainers.add(this);
14129            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
14130        }
14131        performCollectViewAttributes(mAttachInfo, visibility);
14132        onAttachedToWindow();
14133
14134        ListenerInfo li = mListenerInfo;
14135        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14136                li != null ? li.mOnAttachStateChangeListeners : null;
14137        if (listeners != null && listeners.size() > 0) {
14138            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14139            // perform the dispatching. The iterator is a safe guard against listeners that
14140            // could mutate the list by calling the various add/remove methods. This prevents
14141            // the array from being modified while we iterate it.
14142            for (OnAttachStateChangeListener listener : listeners) {
14143                listener.onViewAttachedToWindow(this);
14144            }
14145        }
14146
14147        int vis = info.mWindowVisibility;
14148        if (vis != GONE) {
14149            onWindowVisibilityChanged(vis);
14150        }
14151        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
14152            // If nobody has evaluated the drawable state yet, then do it now.
14153            refreshDrawableState();
14154        }
14155        needGlobalAttributesUpdate(false);
14156    }
14157
14158    void dispatchDetachedFromWindow() {
14159        AttachInfo info = mAttachInfo;
14160        if (info != null) {
14161            int vis = info.mWindowVisibility;
14162            if (vis != GONE) {
14163                onWindowVisibilityChanged(GONE);
14164            }
14165        }
14166
14167        onDetachedFromWindow();
14168        onDetachedFromWindowInternal();
14169
14170        ListenerInfo li = mListenerInfo;
14171        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
14172                li != null ? li.mOnAttachStateChangeListeners : null;
14173        if (listeners != null && listeners.size() > 0) {
14174            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
14175            // perform the dispatching. The iterator is a safe guard against listeners that
14176            // could mutate the list by calling the various add/remove methods. This prevents
14177            // the array from being modified while we iterate it.
14178            for (OnAttachStateChangeListener listener : listeners) {
14179                listener.onViewDetachedFromWindow(this);
14180            }
14181        }
14182
14183        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
14184            mAttachInfo.mScrollContainers.remove(this);
14185            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
14186        }
14187
14188        mAttachInfo = null;
14189        if (mOverlay != null) {
14190            mOverlay.getOverlayView().dispatchDetachedFromWindow();
14191        }
14192    }
14193
14194    /**
14195     * Cancel any deferred high-level input events that were previously posted to the event queue.
14196     *
14197     * <p>Many views post high-level events such as click handlers to the event queue
14198     * to run deferred in order to preserve a desired user experience - clearing visible
14199     * pressed states before executing, etc. This method will abort any events of this nature
14200     * that are currently in flight.</p>
14201     *
14202     * <p>Custom views that generate their own high-level deferred input events should override
14203     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
14204     *
14205     * <p>This will also cancel pending input events for any child views.</p>
14206     *
14207     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
14208     * This will not impact newer events posted after this call that may occur as a result of
14209     * lower-level input events still waiting in the queue. If you are trying to prevent
14210     * double-submitted  events for the duration of some sort of asynchronous transaction
14211     * you should also take other steps to protect against unexpected double inputs e.g. calling
14212     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
14213     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
14214     */
14215    public final void cancelPendingInputEvents() {
14216        dispatchCancelPendingInputEvents();
14217    }
14218
14219    /**
14220     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
14221     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
14222     */
14223    void dispatchCancelPendingInputEvents() {
14224        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
14225        onCancelPendingInputEvents();
14226        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
14227            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
14228                    " did not call through to super.onCancelPendingInputEvents()");
14229        }
14230    }
14231
14232    /**
14233     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
14234     * a parent view.
14235     *
14236     * <p>This method is responsible for removing any pending high-level input events that were
14237     * posted to the event queue to run later. Custom view classes that post their own deferred
14238     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
14239     * {@link android.os.Handler} should override this method, call
14240     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
14241     * </p>
14242     */
14243    public void onCancelPendingInputEvents() {
14244        removePerformClickCallback();
14245        cancelLongPress();
14246        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
14247    }
14248
14249    /**
14250     * Store this view hierarchy's frozen state into the given container.
14251     *
14252     * @param container The SparseArray in which to save the view's state.
14253     *
14254     * @see #restoreHierarchyState(android.util.SparseArray)
14255     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14256     * @see #onSaveInstanceState()
14257     */
14258    public void saveHierarchyState(SparseArray<Parcelable> container) {
14259        dispatchSaveInstanceState(container);
14260    }
14261
14262    /**
14263     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
14264     * this view and its children. May be overridden to modify how freezing happens to a
14265     * view's children; for example, some views may want to not store state for their children.
14266     *
14267     * @param container The SparseArray in which to save the view's state.
14268     *
14269     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14270     * @see #saveHierarchyState(android.util.SparseArray)
14271     * @see #onSaveInstanceState()
14272     */
14273    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
14274        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
14275            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14276            Parcelable state = onSaveInstanceState();
14277            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14278                throw new IllegalStateException(
14279                        "Derived class did not call super.onSaveInstanceState()");
14280            }
14281            if (state != null) {
14282                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
14283                // + ": " + state);
14284                container.put(mID, state);
14285            }
14286        }
14287    }
14288
14289    /**
14290     * Hook allowing a view to generate a representation of its internal state
14291     * that can later be used to create a new instance with that same state.
14292     * This state should only contain information that is not persistent or can
14293     * not be reconstructed later. For example, you will never store your
14294     * current position on screen because that will be computed again when a
14295     * new instance of the view is placed in its view hierarchy.
14296     * <p>
14297     * Some examples of things you may store here: the current cursor position
14298     * in a text view (but usually not the text itself since that is stored in a
14299     * content provider or other persistent storage), the currently selected
14300     * item in a list view.
14301     *
14302     * @return Returns a Parcelable object containing the view's current dynamic
14303     *         state, or null if there is nothing interesting to save. The
14304     *         default implementation returns null.
14305     * @see #onRestoreInstanceState(android.os.Parcelable)
14306     * @see #saveHierarchyState(android.util.SparseArray)
14307     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14308     * @see #setSaveEnabled(boolean)
14309     */
14310    @CallSuper
14311    protected Parcelable onSaveInstanceState() {
14312        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14313        if (mStartActivityRequestWho != null) {
14314            BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE);
14315            state.mStartActivityRequestWhoSaved = mStartActivityRequestWho;
14316            return state;
14317        }
14318        return BaseSavedState.EMPTY_STATE;
14319    }
14320
14321    /**
14322     * Restore this view hierarchy's frozen state from the given container.
14323     *
14324     * @param container The SparseArray which holds previously frozen states.
14325     *
14326     * @see #saveHierarchyState(android.util.SparseArray)
14327     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14328     * @see #onRestoreInstanceState(android.os.Parcelable)
14329     */
14330    public void restoreHierarchyState(SparseArray<Parcelable> container) {
14331        dispatchRestoreInstanceState(container);
14332    }
14333
14334    /**
14335     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
14336     * state for this view and its children. May be overridden to modify how restoring
14337     * happens to a view's children; for example, some views may want to not store state
14338     * for their children.
14339     *
14340     * @param container The SparseArray which holds previously saved state.
14341     *
14342     * @see #dispatchSaveInstanceState(android.util.SparseArray)
14343     * @see #restoreHierarchyState(android.util.SparseArray)
14344     * @see #onRestoreInstanceState(android.os.Parcelable)
14345     */
14346    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
14347        if (mID != NO_ID) {
14348            Parcelable state = container.get(mID);
14349            if (state != null) {
14350                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
14351                // + ": " + state);
14352                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
14353                onRestoreInstanceState(state);
14354                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
14355                    throw new IllegalStateException(
14356                            "Derived class did not call super.onRestoreInstanceState()");
14357                }
14358            }
14359        }
14360    }
14361
14362    /**
14363     * Hook allowing a view to re-apply a representation of its internal state that had previously
14364     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
14365     * null state.
14366     *
14367     * @param state The frozen state that had previously been returned by
14368     *        {@link #onSaveInstanceState}.
14369     *
14370     * @see #onSaveInstanceState()
14371     * @see #restoreHierarchyState(android.util.SparseArray)
14372     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
14373     */
14374    @CallSuper
14375    protected void onRestoreInstanceState(Parcelable state) {
14376        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
14377        if (state != null && !(state instanceof AbsSavedState)) {
14378            throw new IllegalArgumentException("Wrong state class, expecting View State but "
14379                    + "received " + state.getClass().toString() + " instead. This usually happens "
14380                    + "when two views of different type have the same id in the same hierarchy. "
14381                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
14382                    + "other views do not use the same id.");
14383        }
14384        if (state != null && state instanceof BaseSavedState) {
14385            mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved;
14386        }
14387    }
14388
14389    /**
14390     * <p>Return the time at which the drawing of the view hierarchy started.</p>
14391     *
14392     * @return the drawing start time in milliseconds
14393     */
14394    public long getDrawingTime() {
14395        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
14396    }
14397
14398    /**
14399     * <p>Enables or disables the duplication of the parent's state into this view. When
14400     * duplication is enabled, this view gets its drawable state from its parent rather
14401     * than from its own internal properties.</p>
14402     *
14403     * <p>Note: in the current implementation, setting this property to true after the
14404     * view was added to a ViewGroup might have no effect at all. This property should
14405     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
14406     *
14407     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
14408     * property is enabled, an exception will be thrown.</p>
14409     *
14410     * <p>Note: if the child view uses and updates additional states which are unknown to the
14411     * parent, these states should not be affected by this method.</p>
14412     *
14413     * @param enabled True to enable duplication of the parent's drawable state, false
14414     *                to disable it.
14415     *
14416     * @see #getDrawableState()
14417     * @see #isDuplicateParentStateEnabled()
14418     */
14419    public void setDuplicateParentStateEnabled(boolean enabled) {
14420        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
14421    }
14422
14423    /**
14424     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
14425     *
14426     * @return True if this view's drawable state is duplicated from the parent,
14427     *         false otherwise
14428     *
14429     * @see #getDrawableState()
14430     * @see #setDuplicateParentStateEnabled(boolean)
14431     */
14432    public boolean isDuplicateParentStateEnabled() {
14433        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
14434    }
14435
14436    /**
14437     * <p>Specifies the type of layer backing this view. The layer can be
14438     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14439     * {@link #LAYER_TYPE_HARDWARE}.</p>
14440     *
14441     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14442     * instance that controls how the layer is composed on screen. The following
14443     * properties of the paint are taken into account when composing the layer:</p>
14444     * <ul>
14445     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14446     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14447     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14448     * </ul>
14449     *
14450     * <p>If this view has an alpha value set to < 1.0 by calling
14451     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded
14452     * by this view's alpha value.</p>
14453     *
14454     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
14455     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
14456     * for more information on when and how to use layers.</p>
14457     *
14458     * @param layerType The type of layer to use with this view, must be one of
14459     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14460     *        {@link #LAYER_TYPE_HARDWARE}
14461     * @param paint The paint used to compose the layer. This argument is optional
14462     *        and can be null. It is ignored when the layer type is
14463     *        {@link #LAYER_TYPE_NONE}
14464     *
14465     * @see #getLayerType()
14466     * @see #LAYER_TYPE_NONE
14467     * @see #LAYER_TYPE_SOFTWARE
14468     * @see #LAYER_TYPE_HARDWARE
14469     * @see #setAlpha(float)
14470     *
14471     * @attr ref android.R.styleable#View_layerType
14472     */
14473    public void setLayerType(int layerType, Paint paint) {
14474        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
14475            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
14476                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
14477        }
14478
14479        boolean typeChanged = mRenderNode.setLayerType(layerType);
14480
14481        if (!typeChanged) {
14482            setLayerPaint(paint);
14483            return;
14484        }
14485
14486        // Destroy any previous software drawing cache if needed
14487        if (mLayerType == LAYER_TYPE_SOFTWARE) {
14488            destroyDrawingCache();
14489        }
14490
14491        mLayerType = layerType;
14492        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
14493        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
14494        mRenderNode.setLayerPaint(mLayerPaint);
14495
14496        // draw() behaves differently if we are on a layer, so we need to
14497        // invalidate() here
14498        invalidateParentCaches();
14499        invalidate(true);
14500    }
14501
14502    /**
14503     * Updates the {@link Paint} object used with the current layer (used only if the current
14504     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
14505     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
14506     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
14507     * ensure that the view gets redrawn immediately.
14508     *
14509     * <p>A layer is associated with an optional {@link android.graphics.Paint}
14510     * instance that controls how the layer is composed on screen. The following
14511     * properties of the paint are taken into account when composing the layer:</p>
14512     * <ul>
14513     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
14514     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
14515     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
14516     * </ul>
14517     *
14518     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
14519     * alpha value of the layer's paint is superseded by this view's alpha value.</p>
14520     *
14521     * @param paint The paint used to compose the layer. This argument is optional
14522     *        and can be null. It is ignored when the layer type is
14523     *        {@link #LAYER_TYPE_NONE}
14524     *
14525     * @see #setLayerType(int, android.graphics.Paint)
14526     */
14527    public void setLayerPaint(Paint paint) {
14528        int layerType = getLayerType();
14529        if (layerType != LAYER_TYPE_NONE) {
14530            mLayerPaint = paint == null ? new Paint() : paint;
14531            if (layerType == LAYER_TYPE_HARDWARE) {
14532                if (mRenderNode.setLayerPaint(mLayerPaint)) {
14533                    invalidateViewProperty(false, false);
14534                }
14535            } else {
14536                invalidate();
14537            }
14538        }
14539    }
14540
14541    /**
14542     * Indicates what type of layer is currently associated with this view. By default
14543     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
14544     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
14545     * for more information on the different types of layers.
14546     *
14547     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
14548     *         {@link #LAYER_TYPE_HARDWARE}
14549     *
14550     * @see #setLayerType(int, android.graphics.Paint)
14551     * @see #buildLayer()
14552     * @see #LAYER_TYPE_NONE
14553     * @see #LAYER_TYPE_SOFTWARE
14554     * @see #LAYER_TYPE_HARDWARE
14555     */
14556    public int getLayerType() {
14557        return mLayerType;
14558    }
14559
14560    /**
14561     * Forces this view's layer to be created and this view to be rendered
14562     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
14563     * invoking this method will have no effect.
14564     *
14565     * This method can for instance be used to render a view into its layer before
14566     * starting an animation. If this view is complex, rendering into the layer
14567     * before starting the animation will avoid skipping frames.
14568     *
14569     * @throws IllegalStateException If this view is not attached to a window
14570     *
14571     * @see #setLayerType(int, android.graphics.Paint)
14572     */
14573    public void buildLayer() {
14574        if (mLayerType == LAYER_TYPE_NONE) return;
14575
14576        final AttachInfo attachInfo = mAttachInfo;
14577        if (attachInfo == null) {
14578            throw new IllegalStateException("This view must be attached to a window first");
14579        }
14580
14581        if (getWidth() == 0 || getHeight() == 0) {
14582            return;
14583        }
14584
14585        switch (mLayerType) {
14586            case LAYER_TYPE_HARDWARE:
14587                updateDisplayListIfDirty();
14588                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
14589                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
14590                }
14591                break;
14592            case LAYER_TYPE_SOFTWARE:
14593                buildDrawingCache(true);
14594                break;
14595        }
14596    }
14597
14598    /**
14599     * If this View draws with a HardwareLayer, returns it.
14600     * Otherwise returns null
14601     *
14602     * TODO: Only TextureView uses this, can we eliminate it?
14603     */
14604    HardwareLayer getHardwareLayer() {
14605        return null;
14606    }
14607
14608    /**
14609     * Destroys all hardware rendering resources. This method is invoked
14610     * when the system needs to reclaim resources. Upon execution of this
14611     * method, you should free any OpenGL resources created by the view.
14612     *
14613     * Note: you <strong>must</strong> call
14614     * <code>super.destroyHardwareResources()</code> when overriding
14615     * this method.
14616     *
14617     * @hide
14618     */
14619    @CallSuper
14620    protected void destroyHardwareResources() {
14621        // Although the Layer will be destroyed by RenderNode, we want to release
14622        // the staging display list, which is also a signal to RenderNode that it's
14623        // safe to free its copy of the display list as it knows that we will
14624        // push an updated DisplayList if we try to draw again
14625        resetDisplayList();
14626    }
14627
14628    /**
14629     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
14630     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
14631     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
14632     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
14633     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
14634     * null.</p>
14635     *
14636     * <p>Enabling the drawing cache is similar to
14637     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
14638     * acceleration is turned off. When hardware acceleration is turned on, enabling the
14639     * drawing cache has no effect on rendering because the system uses a different mechanism
14640     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
14641     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
14642     * for information on how to enable software and hardware layers.</p>
14643     *
14644     * <p>This API can be used to manually generate
14645     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
14646     * {@link #getDrawingCache()}.</p>
14647     *
14648     * @param enabled true to enable the drawing cache, false otherwise
14649     *
14650     * @see #isDrawingCacheEnabled()
14651     * @see #getDrawingCache()
14652     * @see #buildDrawingCache()
14653     * @see #setLayerType(int, android.graphics.Paint)
14654     */
14655    public void setDrawingCacheEnabled(boolean enabled) {
14656        mCachingFailed = false;
14657        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
14658    }
14659
14660    /**
14661     * <p>Indicates whether the drawing cache is enabled for this view.</p>
14662     *
14663     * @return true if the drawing cache is enabled
14664     *
14665     * @see #setDrawingCacheEnabled(boolean)
14666     * @see #getDrawingCache()
14667     */
14668    @ViewDebug.ExportedProperty(category = "drawing")
14669    public boolean isDrawingCacheEnabled() {
14670        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
14671    }
14672
14673    /**
14674     * Debugging utility which recursively outputs the dirty state of a view and its
14675     * descendants.
14676     *
14677     * @hide
14678     */
14679    @SuppressWarnings({"UnusedDeclaration"})
14680    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
14681        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
14682                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
14683                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
14684                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
14685        if (clear) {
14686            mPrivateFlags &= clearMask;
14687        }
14688        if (this instanceof ViewGroup) {
14689            ViewGroup parent = (ViewGroup) this;
14690            final int count = parent.getChildCount();
14691            for (int i = 0; i < count; i++) {
14692                final View child = parent.getChildAt(i);
14693                child.outputDirtyFlags(indent + "  ", clear, clearMask);
14694            }
14695        }
14696    }
14697
14698    /**
14699     * This method is used by ViewGroup to cause its children to restore or recreate their
14700     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
14701     * to recreate its own display list, which would happen if it went through the normal
14702     * draw/dispatchDraw mechanisms.
14703     *
14704     * @hide
14705     */
14706    protected void dispatchGetDisplayList() {}
14707
14708    /**
14709     * A view that is not attached or hardware accelerated cannot create a display list.
14710     * This method checks these conditions and returns the appropriate result.
14711     *
14712     * @return true if view has the ability to create a display list, false otherwise.
14713     *
14714     * @hide
14715     */
14716    public boolean canHaveDisplayList() {
14717        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
14718    }
14719
14720    /**
14721     * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported)
14722     * @hide
14723     */
14724    @NonNull
14725    public RenderNode updateDisplayListIfDirty() {
14726        final RenderNode renderNode = mRenderNode;
14727        if (!canHaveDisplayList()) {
14728            // can't populate RenderNode, don't try
14729            return renderNode;
14730        }
14731
14732        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
14733                || !renderNode.isValid()
14734                || (mRecreateDisplayList)) {
14735            // Don't need to recreate the display list, just need to tell our
14736            // children to restore/recreate theirs
14737            if (renderNode.isValid()
14738                    && !mRecreateDisplayList) {
14739                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14740                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14741                dispatchGetDisplayList();
14742
14743                return renderNode; // no work needed
14744            }
14745
14746            // If we got here, we're recreating it. Mark it as such to ensure that
14747            // we copy in child display lists into ours in drawChild()
14748            mRecreateDisplayList = true;
14749
14750            int width = mRight - mLeft;
14751            int height = mBottom - mTop;
14752            int layerType = getLayerType();
14753
14754            final DisplayListCanvas canvas = renderNode.start(width, height);
14755            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
14756
14757            try {
14758                final HardwareLayer layer = getHardwareLayer();
14759                if (layer != null && layer.isValid()) {
14760                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
14761                } else if (layerType == LAYER_TYPE_SOFTWARE) {
14762                    buildDrawingCache(true);
14763                    Bitmap cache = getDrawingCache(true);
14764                    if (cache != null) {
14765                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
14766                    }
14767                } else {
14768                    computeScroll();
14769
14770                    canvas.translate(-mScrollX, -mScrollY);
14771                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14772                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14773
14774                    // Fast path for layouts with no backgrounds
14775                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14776                        dispatchDraw(canvas);
14777                        if (mOverlay != null && !mOverlay.isEmpty()) {
14778                            mOverlay.getOverlayView().draw(canvas);
14779                        }
14780                    } else {
14781                        draw(canvas);
14782                    }
14783                }
14784            } finally {
14785                renderNode.end(canvas);
14786                setDisplayListProperties(renderNode);
14787            }
14788        } else {
14789            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
14790            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14791        }
14792        return renderNode;
14793    }
14794
14795    private void resetDisplayList() {
14796        if (mRenderNode.isValid()) {
14797            mRenderNode.destroyDisplayListData();
14798        }
14799
14800        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
14801            mBackgroundRenderNode.destroyDisplayListData();
14802        }
14803    }
14804
14805    /**
14806     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
14807     *
14808     * @return A non-scaled bitmap representing this view or null if cache is disabled.
14809     *
14810     * @see #getDrawingCache(boolean)
14811     */
14812    public Bitmap getDrawingCache() {
14813        return getDrawingCache(false);
14814    }
14815
14816    /**
14817     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
14818     * is null when caching is disabled. If caching is enabled and the cache is not ready,
14819     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
14820     * draw from the cache when the cache is enabled. To benefit from the cache, you must
14821     * request the drawing cache by calling this method and draw it on screen if the
14822     * returned bitmap is not null.</p>
14823     *
14824     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14825     * this method will create a bitmap of the same size as this view. Because this bitmap
14826     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14827     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14828     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14829     * size than the view. This implies that your application must be able to handle this
14830     * size.</p>
14831     *
14832     * @param autoScale Indicates whether the generated bitmap should be scaled based on
14833     *        the current density of the screen when the application is in compatibility
14834     *        mode.
14835     *
14836     * @return A bitmap representing this view or null if cache is disabled.
14837     *
14838     * @see #setDrawingCacheEnabled(boolean)
14839     * @see #isDrawingCacheEnabled()
14840     * @see #buildDrawingCache(boolean)
14841     * @see #destroyDrawingCache()
14842     */
14843    public Bitmap getDrawingCache(boolean autoScale) {
14844        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
14845            return null;
14846        }
14847        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
14848            buildDrawingCache(autoScale);
14849        }
14850        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
14851    }
14852
14853    /**
14854     * <p>Frees the resources used by the drawing cache. If you call
14855     * {@link #buildDrawingCache()} manually without calling
14856     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14857     * should cleanup the cache with this method afterwards.</p>
14858     *
14859     * @see #setDrawingCacheEnabled(boolean)
14860     * @see #buildDrawingCache()
14861     * @see #getDrawingCache()
14862     */
14863    public void destroyDrawingCache() {
14864        if (mDrawingCache != null) {
14865            mDrawingCache.recycle();
14866            mDrawingCache = null;
14867        }
14868        if (mUnscaledDrawingCache != null) {
14869            mUnscaledDrawingCache.recycle();
14870            mUnscaledDrawingCache = null;
14871        }
14872    }
14873
14874    /**
14875     * Setting a solid background color for the drawing cache's bitmaps will improve
14876     * performance and memory usage. Note, though that this should only be used if this
14877     * view will always be drawn on top of a solid color.
14878     *
14879     * @param color The background color to use for the drawing cache's bitmap
14880     *
14881     * @see #setDrawingCacheEnabled(boolean)
14882     * @see #buildDrawingCache()
14883     * @see #getDrawingCache()
14884     */
14885    public void setDrawingCacheBackgroundColor(@ColorInt int color) {
14886        if (color != mDrawingCacheBackgroundColor) {
14887            mDrawingCacheBackgroundColor = color;
14888            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
14889        }
14890    }
14891
14892    /**
14893     * @see #setDrawingCacheBackgroundColor(int)
14894     *
14895     * @return The background color to used for the drawing cache's bitmap
14896     */
14897    @ColorInt
14898    public int getDrawingCacheBackgroundColor() {
14899        return mDrawingCacheBackgroundColor;
14900    }
14901
14902    /**
14903     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
14904     *
14905     * @see #buildDrawingCache(boolean)
14906     */
14907    public void buildDrawingCache() {
14908        buildDrawingCache(false);
14909    }
14910
14911    /**
14912     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14913     *
14914     * <p>If you call {@link #buildDrawingCache()} manually without calling
14915     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14916     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14917     *
14918     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14919     * this method will create a bitmap of the same size as this view. Because this bitmap
14920     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14921     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14922     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14923     * size than the view. This implies that your application must be able to handle this
14924     * size.</p>
14925     *
14926     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14927     * you do not need the drawing cache bitmap, calling this method will increase memory
14928     * usage and cause the view to be rendered in software once, thus negatively impacting
14929     * performance.</p>
14930     *
14931     * @see #getDrawingCache()
14932     * @see #destroyDrawingCache()
14933     */
14934    public void buildDrawingCache(boolean autoScale) {
14935        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14936                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14937            if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
14938                Trace.traceBegin(Trace.TRACE_TAG_VIEW,
14939                        "buildDrawingCache/SW Layer for " + getClass().getSimpleName());
14940            }
14941            try {
14942                buildDrawingCacheImpl(autoScale);
14943            } finally {
14944                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
14945            }
14946        }
14947    }
14948
14949    /**
14950     * private, internal implementation of buildDrawingCache, used to enable tracing
14951     */
14952    private void buildDrawingCacheImpl(boolean autoScale) {
14953        mCachingFailed = false;
14954
14955        int width = mRight - mLeft;
14956        int height = mBottom - mTop;
14957
14958        final AttachInfo attachInfo = mAttachInfo;
14959        final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14960
14961        if (autoScale && scalingRequired) {
14962            width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14963            height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14964        }
14965
14966        final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14967        final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14968        final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14969
14970        final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14971        final long drawingCacheSize =
14972                ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14973        if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14974            if (width > 0 && height > 0) {
14975                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14976                        + projectedBitmapSize + " bytes, only "
14977                        + drawingCacheSize + " available");
14978            }
14979            destroyDrawingCache();
14980            mCachingFailed = true;
14981            return;
14982        }
14983
14984        boolean clear = true;
14985        Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14986
14987        if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14988            Bitmap.Config quality;
14989            if (!opaque) {
14990                // Never pick ARGB_4444 because it looks awful
14991                // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14992                switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14993                    case DRAWING_CACHE_QUALITY_AUTO:
14994                    case DRAWING_CACHE_QUALITY_LOW:
14995                    case DRAWING_CACHE_QUALITY_HIGH:
14996                    default:
14997                        quality = Bitmap.Config.ARGB_8888;
14998                        break;
14999                }
15000            } else {
15001                // Optimization for translucent windows
15002                // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
15003                quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
15004            }
15005
15006            // Try to cleanup memory
15007            if (bitmap != null) bitmap.recycle();
15008
15009            try {
15010                bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15011                        width, height, quality);
15012                bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
15013                if (autoScale) {
15014                    mDrawingCache = bitmap;
15015                } else {
15016                    mUnscaledDrawingCache = bitmap;
15017                }
15018                if (opaque && use32BitCache) bitmap.setHasAlpha(false);
15019            } catch (OutOfMemoryError e) {
15020                // If there is not enough memory to create the bitmap cache, just
15021                // ignore the issue as bitmap caches are not required to draw the
15022                // view hierarchy
15023                if (autoScale) {
15024                    mDrawingCache = null;
15025                } else {
15026                    mUnscaledDrawingCache = null;
15027                }
15028                mCachingFailed = true;
15029                return;
15030            }
15031
15032            clear = drawingCacheBackgroundColor != 0;
15033        }
15034
15035        Canvas canvas;
15036        if (attachInfo != null) {
15037            canvas = attachInfo.mCanvas;
15038            if (canvas == null) {
15039                canvas = new Canvas();
15040            }
15041            canvas.setBitmap(bitmap);
15042            // Temporarily clobber the cached Canvas in case one of our children
15043            // is also using a drawing cache. Without this, the children would
15044            // steal the canvas by attaching their own bitmap to it and bad, bad
15045            // thing would happen (invisible views, corrupted drawings, etc.)
15046            attachInfo.mCanvas = null;
15047        } else {
15048            // This case should hopefully never or seldom happen
15049            canvas = new Canvas(bitmap);
15050        }
15051
15052        if (clear) {
15053            bitmap.eraseColor(drawingCacheBackgroundColor);
15054        }
15055
15056        computeScroll();
15057        final int restoreCount = canvas.save();
15058
15059        if (autoScale && scalingRequired) {
15060            final float scale = attachInfo.mApplicationScale;
15061            canvas.scale(scale, scale);
15062        }
15063
15064        canvas.translate(-mScrollX, -mScrollY);
15065
15066        mPrivateFlags |= PFLAG_DRAWN;
15067        if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
15068                mLayerType != LAYER_TYPE_NONE) {
15069            mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
15070        }
15071
15072        // Fast path for layouts with no backgrounds
15073        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15074            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15075            dispatchDraw(canvas);
15076            if (mOverlay != null && !mOverlay.isEmpty()) {
15077                mOverlay.getOverlayView().draw(canvas);
15078            }
15079        } else {
15080            draw(canvas);
15081        }
15082
15083        canvas.restoreToCount(restoreCount);
15084        canvas.setBitmap(null);
15085
15086        if (attachInfo != null) {
15087            // Restore the cached Canvas for our siblings
15088            attachInfo.mCanvas = canvas;
15089        }
15090    }
15091
15092    /**
15093     * Create a snapshot of the view into a bitmap.  We should probably make
15094     * some form of this public, but should think about the API.
15095     */
15096    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
15097        int width = mRight - mLeft;
15098        int height = mBottom - mTop;
15099
15100        final AttachInfo attachInfo = mAttachInfo;
15101        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
15102        width = (int) ((width * scale) + 0.5f);
15103        height = (int) ((height * scale) + 0.5f);
15104
15105        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
15106                width > 0 ? width : 1, height > 0 ? height : 1, quality);
15107        if (bitmap == null) {
15108            throw new OutOfMemoryError();
15109        }
15110
15111        Resources resources = getResources();
15112        if (resources != null) {
15113            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
15114        }
15115
15116        Canvas canvas;
15117        if (attachInfo != null) {
15118            canvas = attachInfo.mCanvas;
15119            if (canvas == null) {
15120                canvas = new Canvas();
15121            }
15122            canvas.setBitmap(bitmap);
15123            // Temporarily clobber the cached Canvas in case one of our children
15124            // is also using a drawing cache. Without this, the children would
15125            // steal the canvas by attaching their own bitmap to it and bad, bad
15126            // things would happen (invisible views, corrupted drawings, etc.)
15127            attachInfo.mCanvas = null;
15128        } else {
15129            // This case should hopefully never or seldom happen
15130            canvas = new Canvas(bitmap);
15131        }
15132
15133        if ((backgroundColor & 0xff000000) != 0) {
15134            bitmap.eraseColor(backgroundColor);
15135        }
15136
15137        computeScroll();
15138        final int restoreCount = canvas.save();
15139        canvas.scale(scale, scale);
15140        canvas.translate(-mScrollX, -mScrollY);
15141
15142        // Temporarily remove the dirty mask
15143        int flags = mPrivateFlags;
15144        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15145
15146        // Fast path for layouts with no backgrounds
15147        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15148            dispatchDraw(canvas);
15149            if (mOverlay != null && !mOverlay.isEmpty()) {
15150                mOverlay.getOverlayView().draw(canvas);
15151            }
15152        } else {
15153            draw(canvas);
15154        }
15155
15156        mPrivateFlags = flags;
15157
15158        canvas.restoreToCount(restoreCount);
15159        canvas.setBitmap(null);
15160
15161        if (attachInfo != null) {
15162            // Restore the cached Canvas for our siblings
15163            attachInfo.mCanvas = canvas;
15164        }
15165
15166        return bitmap;
15167    }
15168
15169    /**
15170     * Indicates whether this View is currently in edit mode. A View is usually
15171     * in edit mode when displayed within a developer tool. For instance, if
15172     * this View is being drawn by a visual user interface builder, this method
15173     * should return true.
15174     *
15175     * Subclasses should check the return value of this method to provide
15176     * different behaviors if their normal behavior might interfere with the
15177     * host environment. For instance: the class spawns a thread in its
15178     * constructor, the drawing code relies on device-specific features, etc.
15179     *
15180     * This method is usually checked in the drawing code of custom widgets.
15181     *
15182     * @return True if this View is in edit mode, false otherwise.
15183     */
15184    public boolean isInEditMode() {
15185        return false;
15186    }
15187
15188    /**
15189     * If the View draws content inside its padding and enables fading edges,
15190     * it needs to support padding offsets. Padding offsets are added to the
15191     * fading edges to extend the length of the fade so that it covers pixels
15192     * drawn inside the padding.
15193     *
15194     * Subclasses of this class should override this method if they need
15195     * to draw content inside the padding.
15196     *
15197     * @return True if padding offset must be applied, false otherwise.
15198     *
15199     * @see #getLeftPaddingOffset()
15200     * @see #getRightPaddingOffset()
15201     * @see #getTopPaddingOffset()
15202     * @see #getBottomPaddingOffset()
15203     *
15204     * @since CURRENT
15205     */
15206    protected boolean isPaddingOffsetRequired() {
15207        return false;
15208    }
15209
15210    /**
15211     * Amount by which to extend the left fading region. Called only when
15212     * {@link #isPaddingOffsetRequired()} returns true.
15213     *
15214     * @return The left padding offset in pixels.
15215     *
15216     * @see #isPaddingOffsetRequired()
15217     *
15218     * @since CURRENT
15219     */
15220    protected int getLeftPaddingOffset() {
15221        return 0;
15222    }
15223
15224    /**
15225     * Amount by which to extend the right fading region. Called only when
15226     * {@link #isPaddingOffsetRequired()} returns true.
15227     *
15228     * @return The right padding offset in pixels.
15229     *
15230     * @see #isPaddingOffsetRequired()
15231     *
15232     * @since CURRENT
15233     */
15234    protected int getRightPaddingOffset() {
15235        return 0;
15236    }
15237
15238    /**
15239     * Amount by which to extend the top fading region. Called only when
15240     * {@link #isPaddingOffsetRequired()} returns true.
15241     *
15242     * @return The top padding offset in pixels.
15243     *
15244     * @see #isPaddingOffsetRequired()
15245     *
15246     * @since CURRENT
15247     */
15248    protected int getTopPaddingOffset() {
15249        return 0;
15250    }
15251
15252    /**
15253     * Amount by which to extend the bottom fading region. Called only when
15254     * {@link #isPaddingOffsetRequired()} returns true.
15255     *
15256     * @return The bottom padding offset in pixels.
15257     *
15258     * @see #isPaddingOffsetRequired()
15259     *
15260     * @since CURRENT
15261     */
15262    protected int getBottomPaddingOffset() {
15263        return 0;
15264    }
15265
15266    /**
15267     * @hide
15268     * @param offsetRequired
15269     */
15270    protected int getFadeTop(boolean offsetRequired) {
15271        int top = mPaddingTop;
15272        if (offsetRequired) top += getTopPaddingOffset();
15273        return top;
15274    }
15275
15276    /**
15277     * @hide
15278     * @param offsetRequired
15279     */
15280    protected int getFadeHeight(boolean offsetRequired) {
15281        int padding = mPaddingTop;
15282        if (offsetRequired) padding += getTopPaddingOffset();
15283        return mBottom - mTop - mPaddingBottom - padding;
15284    }
15285
15286    /**
15287     * <p>Indicates whether this view is attached to a hardware accelerated
15288     * window or not.</p>
15289     *
15290     * <p>Even if this method returns true, it does not mean that every call
15291     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
15292     * accelerated {@link android.graphics.Canvas}. For instance, if this view
15293     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
15294     * window is hardware accelerated,
15295     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
15296     * return false, and this method will return true.</p>
15297     *
15298     * @return True if the view is attached to a window and the window is
15299     *         hardware accelerated; false in any other case.
15300     */
15301    @ViewDebug.ExportedProperty(category = "drawing")
15302    public boolean isHardwareAccelerated() {
15303        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
15304    }
15305
15306    /**
15307     * Sets a rectangular area on this view to which the view will be clipped
15308     * when it is drawn. Setting the value to null will remove the clip bounds
15309     * and the view will draw normally, using its full bounds.
15310     *
15311     * @param clipBounds The rectangular area, in the local coordinates of
15312     * this view, to which future drawing operations will be clipped.
15313     */
15314    public void setClipBounds(Rect clipBounds) {
15315        if (clipBounds == mClipBounds
15316                || (clipBounds != null && clipBounds.equals(mClipBounds))) {
15317            return;
15318        }
15319        if (clipBounds != null) {
15320            if (mClipBounds == null) {
15321                mClipBounds = new Rect(clipBounds);
15322            } else {
15323                mClipBounds.set(clipBounds);
15324            }
15325        } else {
15326            mClipBounds = null;
15327        }
15328        mRenderNode.setClipBounds(mClipBounds);
15329        invalidateViewProperty(false, false);
15330    }
15331
15332    /**
15333     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
15334     *
15335     * @return A copy of the current clip bounds if clip bounds are set,
15336     * otherwise null.
15337     */
15338    public Rect getClipBounds() {
15339        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
15340    }
15341
15342
15343    /**
15344     * Populates an output rectangle with the clip bounds of the view,
15345     * returning {@code true} if successful or {@code false} if the view's
15346     * clip bounds are {@code null}.
15347     *
15348     * @param outRect rectangle in which to place the clip bounds of the view
15349     * @return {@code true} if successful or {@code false} if the view's
15350     *         clip bounds are {@code null}
15351     */
15352    public boolean getClipBounds(Rect outRect) {
15353        if (mClipBounds != null) {
15354            outRect.set(mClipBounds);
15355            return true;
15356        }
15357        return false;
15358    }
15359
15360    /**
15361     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
15362     * case of an active Animation being run on the view.
15363     */
15364    private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime,
15365            Animation a, boolean scalingRequired) {
15366        Transformation invalidationTransform;
15367        final int flags = parent.mGroupFlags;
15368        final boolean initialized = a.isInitialized();
15369        if (!initialized) {
15370            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
15371            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
15372            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
15373            onAnimationStart();
15374        }
15375
15376        final Transformation t = parent.getChildTransformation();
15377        boolean more = a.getTransformation(drawingTime, t, 1f);
15378        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
15379            if (parent.mInvalidationTransformation == null) {
15380                parent.mInvalidationTransformation = new Transformation();
15381            }
15382            invalidationTransform = parent.mInvalidationTransformation;
15383            a.getTransformation(drawingTime, invalidationTransform, 1f);
15384        } else {
15385            invalidationTransform = t;
15386        }
15387
15388        if (more) {
15389            if (!a.willChangeBounds()) {
15390                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
15391                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
15392                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
15393                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
15394                    // The child need to draw an animation, potentially offscreen, so
15395                    // make sure we do not cancel invalidate requests
15396                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15397                    parent.invalidate(mLeft, mTop, mRight, mBottom);
15398                }
15399            } else {
15400                if (parent.mInvalidateRegion == null) {
15401                    parent.mInvalidateRegion = new RectF();
15402                }
15403                final RectF region = parent.mInvalidateRegion;
15404                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
15405                        invalidationTransform);
15406
15407                // The child need to draw an animation, potentially offscreen, so
15408                // make sure we do not cancel invalidate requests
15409                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
15410
15411                final int left = mLeft + (int) region.left;
15412                final int top = mTop + (int) region.top;
15413                parent.invalidate(left, top, left + (int) (region.width() + .5f),
15414                        top + (int) (region.height() + .5f));
15415            }
15416        }
15417        return more;
15418    }
15419
15420    /**
15421     * This method is called by getDisplayList() when a display list is recorded for a View.
15422     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
15423     */
15424    void setDisplayListProperties(RenderNode renderNode) {
15425        if (renderNode != null) {
15426            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
15427            renderNode.setClipToBounds(mParent instanceof ViewGroup
15428                    && ((ViewGroup) mParent).getClipChildren());
15429
15430            float alpha = 1;
15431            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
15432                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15433                ViewGroup parentVG = (ViewGroup) mParent;
15434                final Transformation t = parentVG.getChildTransformation();
15435                if (parentVG.getChildStaticTransformation(this, t)) {
15436                    final int transformType = t.getTransformationType();
15437                    if (transformType != Transformation.TYPE_IDENTITY) {
15438                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
15439                            alpha = t.getAlpha();
15440                        }
15441                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
15442                            renderNode.setStaticMatrix(t.getMatrix());
15443                        }
15444                    }
15445                }
15446            }
15447            if (mTransformationInfo != null) {
15448                alpha *= getFinalAlpha();
15449                if (alpha < 1) {
15450                    final int multipliedAlpha = (int) (255 * alpha);
15451                    if (onSetAlpha(multipliedAlpha)) {
15452                        alpha = 1;
15453                    }
15454                }
15455                renderNode.setAlpha(alpha);
15456            } else if (alpha < 1) {
15457                renderNode.setAlpha(alpha);
15458            }
15459        }
15460    }
15461
15462    /**
15463     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
15464     *
15465     * This is where the View specializes rendering behavior based on layer type,
15466     * and hardware acceleration.
15467     */
15468    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
15469        final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated();
15470        /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList.
15471         *
15472         * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't
15473         * HW accelerated, it can't handle drawing RenderNodes.
15474         */
15475        boolean drawingWithRenderNode = mAttachInfo != null
15476                && mAttachInfo.mHardwareAccelerated
15477                && hardwareAcceleratedCanvas;
15478
15479        boolean more = false;
15480        final boolean childHasIdentityMatrix = hasIdentityMatrix();
15481        final int parentFlags = parent.mGroupFlags;
15482
15483        if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) {
15484            parent.getChildTransformation().clear();
15485            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15486        }
15487
15488        Transformation transformToApply = null;
15489        boolean concatMatrix = false;
15490        final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired;
15491        final Animation a = getAnimation();
15492        if (a != null) {
15493            more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired);
15494            concatMatrix = a.willChangeTransformationMatrix();
15495            if (concatMatrix) {
15496                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15497            }
15498            transformToApply = parent.getChildTransformation();
15499        } else {
15500            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
15501                // No longer animating: clear out old animation matrix
15502                mRenderNode.setAnimationMatrix(null);
15503                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
15504            }
15505            if (!drawingWithRenderNode
15506                    && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
15507                final Transformation t = parent.getChildTransformation();
15508                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
15509                if (hasTransform) {
15510                    final int transformType = t.getTransformationType();
15511                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
15512                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
15513                }
15514            }
15515        }
15516
15517        concatMatrix |= !childHasIdentityMatrix;
15518
15519        // Sets the flag as early as possible to allow draw() implementations
15520        // to call invalidate() successfully when doing animations
15521        mPrivateFlags |= PFLAG_DRAWN;
15522
15523        if (!concatMatrix &&
15524                (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
15525                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
15526                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
15527                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
15528            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
15529            return more;
15530        }
15531        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
15532
15533        if (hardwareAcceleratedCanvas) {
15534            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
15535            // retain the flag's value temporarily in the mRecreateDisplayList flag
15536            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0;
15537            mPrivateFlags &= ~PFLAG_INVALIDATED;
15538        }
15539
15540        RenderNode renderNode = null;
15541        Bitmap cache = null;
15542        int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local
15543        if (layerType == LAYER_TYPE_SOFTWARE
15544                || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) {
15545            // If not drawing with RenderNode, treat HW layers as SW
15546            layerType = LAYER_TYPE_SOFTWARE;
15547            buildDrawingCache(true);
15548            cache = getDrawingCache(true);
15549        }
15550
15551        if (drawingWithRenderNode) {
15552            // Delay getting the display list until animation-driven alpha values are
15553            // set up and possibly passed on to the view
15554            renderNode = updateDisplayListIfDirty();
15555            if (!renderNode.isValid()) {
15556                // Uncommon, but possible. If a view is removed from the hierarchy during the call
15557                // to getDisplayList(), the display list will be marked invalid and we should not
15558                // try to use it again.
15559                renderNode = null;
15560                drawingWithRenderNode = false;
15561            }
15562        }
15563
15564        int sx = 0;
15565        int sy = 0;
15566        if (!drawingWithRenderNode) {
15567            computeScroll();
15568            sx = mScrollX;
15569            sy = mScrollY;
15570        }
15571
15572        final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode;
15573        final boolean offsetForScroll = cache == null && !drawingWithRenderNode;
15574
15575        int restoreTo = -1;
15576        if (!drawingWithRenderNode || transformToApply != null) {
15577            restoreTo = canvas.save();
15578        }
15579        if (offsetForScroll) {
15580            canvas.translate(mLeft - sx, mTop - sy);
15581        } else {
15582            if (!drawingWithRenderNode) {
15583                canvas.translate(mLeft, mTop);
15584            }
15585            if (scalingRequired) {
15586                if (drawingWithRenderNode) {
15587                    // TODO: Might not need this if we put everything inside the DL
15588                    restoreTo = canvas.save();
15589                }
15590                // mAttachInfo cannot be null, otherwise scalingRequired == false
15591                final float scale = 1.0f / mAttachInfo.mApplicationScale;
15592                canvas.scale(scale, scale);
15593            }
15594        }
15595
15596        float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha());
15597        if (transformToApply != null
15598                || alpha < 1
15599                || !hasIdentityMatrix()
15600                || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15601            if (transformToApply != null || !childHasIdentityMatrix) {
15602                int transX = 0;
15603                int transY = 0;
15604
15605                if (offsetForScroll) {
15606                    transX = -sx;
15607                    transY = -sy;
15608                }
15609
15610                if (transformToApply != null) {
15611                    if (concatMatrix) {
15612                        if (drawingWithRenderNode) {
15613                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
15614                        } else {
15615                            // Undo the scroll translation, apply the transformation matrix,
15616                            // then redo the scroll translate to get the correct result.
15617                            canvas.translate(-transX, -transY);
15618                            canvas.concat(transformToApply.getMatrix());
15619                            canvas.translate(transX, transY);
15620                        }
15621                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15622                    }
15623
15624                    float transformAlpha = transformToApply.getAlpha();
15625                    if (transformAlpha < 1) {
15626                        alpha *= transformAlpha;
15627                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15628                    }
15629                }
15630
15631                if (!childHasIdentityMatrix && !drawingWithRenderNode) {
15632                    canvas.translate(-transX, -transY);
15633                    canvas.concat(getMatrix());
15634                    canvas.translate(transX, transY);
15635                }
15636            }
15637
15638            // Deal with alpha if it is or used to be <1
15639            if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) {
15640                if (alpha < 1) {
15641                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15642                } else {
15643                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
15644                }
15645                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
15646                if (!drawingWithDrawingCache) {
15647                    final int multipliedAlpha = (int) (255 * alpha);
15648                    if (!onSetAlpha(multipliedAlpha)) {
15649                        if (drawingWithRenderNode) {
15650                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
15651                        } else if (layerType == LAYER_TYPE_NONE) {
15652                            canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
15653                                    multipliedAlpha);
15654                        }
15655                    } else {
15656                        // Alpha is handled by the child directly, clobber the layer's alpha
15657                        mPrivateFlags |= PFLAG_ALPHA_SET;
15658                    }
15659                }
15660            }
15661        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15662            onSetAlpha(255);
15663            mPrivateFlags &= ~PFLAG_ALPHA_SET;
15664        }
15665
15666        if (!drawingWithRenderNode) {
15667            // apply clips directly, since RenderNode won't do it for this draw
15668            if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) {
15669                if (offsetForScroll) {
15670                    canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight());
15671                } else {
15672                    if (!scalingRequired || cache == null) {
15673                        canvas.clipRect(0, 0, getWidth(), getHeight());
15674                    } else {
15675                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
15676                    }
15677                }
15678            }
15679
15680            if (mClipBounds != null) {
15681                // clip bounds ignore scroll
15682                canvas.clipRect(mClipBounds);
15683            }
15684        }
15685
15686        if (!drawingWithDrawingCache) {
15687            if (drawingWithRenderNode) {
15688                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15689                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15690            } else {
15691                // Fast path for layouts with no backgrounds
15692                if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
15693                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15694                    dispatchDraw(canvas);
15695                } else {
15696                    draw(canvas);
15697                }
15698            }
15699        } else if (cache != null) {
15700            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
15701            Paint cachePaint;
15702            int restoreAlpha = 0;
15703
15704            if (layerType == LAYER_TYPE_NONE) {
15705                cachePaint = parent.mCachePaint;
15706                if (cachePaint == null) {
15707                    cachePaint = new Paint();
15708                    cachePaint.setDither(false);
15709                    parent.mCachePaint = cachePaint;
15710                }
15711            } else {
15712                cachePaint = mLayerPaint;
15713                restoreAlpha = mLayerPaint.getAlpha();
15714            }
15715            cachePaint.setAlpha((int) (alpha * 255));
15716            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
15717            cachePaint.setAlpha(restoreAlpha);
15718        }
15719
15720        if (restoreTo >= 0) {
15721            canvas.restoreToCount(restoreTo);
15722        }
15723
15724        if (a != null && !more) {
15725            if (!hardwareAcceleratedCanvas && !a.getFillAfter()) {
15726                onSetAlpha(255);
15727            }
15728            parent.finishAnimatingView(this, a);
15729        }
15730
15731        if (more && hardwareAcceleratedCanvas) {
15732            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
15733                // alpha animations should cause the child to recreate its display list
15734                invalidate(true);
15735            }
15736        }
15737
15738        mRecreateDisplayList = false;
15739
15740        return more;
15741    }
15742
15743    /**
15744     * Manually render this view (and all of its children) to the given Canvas.
15745     * The view must have already done a full layout before this function is
15746     * called.  When implementing a view, implement
15747     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
15748     * If you do need to override this method, call the superclass version.
15749     *
15750     * @param canvas The Canvas to which the View is rendered.
15751     */
15752    @CallSuper
15753    public void draw(Canvas canvas) {
15754        final int privateFlags = mPrivateFlags;
15755        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
15756                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
15757        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
15758
15759        /*
15760         * Draw traversal performs several drawing steps which must be executed
15761         * in the appropriate order:
15762         *
15763         *      1. Draw the background
15764         *      2. If necessary, save the canvas' layers to prepare for fading
15765         *      3. Draw view's content
15766         *      4. Draw children
15767         *      5. If necessary, draw the fading edges and restore layers
15768         *      6. Draw decorations (scrollbars for instance)
15769         */
15770
15771        // Step 1, draw the background, if needed
15772        int saveCount;
15773
15774        if (!dirtyOpaque) {
15775            drawBackground(canvas);
15776        }
15777
15778        // skip step 2 & 5 if possible (common case)
15779        final int viewFlags = mViewFlags;
15780        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
15781        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
15782        if (!verticalEdges && !horizontalEdges) {
15783            // Step 3, draw the content
15784            if (!dirtyOpaque) onDraw(canvas);
15785
15786            // Step 4, draw the children
15787            dispatchDraw(canvas);
15788
15789            // Overlay is part of the content and draws beneath Foreground
15790            if (mOverlay != null && !mOverlay.isEmpty()) {
15791                mOverlay.getOverlayView().dispatchDraw(canvas);
15792            }
15793
15794            // Step 6, draw decorations (foreground, scrollbars)
15795            onDrawForeground(canvas);
15796
15797            // we're done...
15798            return;
15799        }
15800
15801        /*
15802         * Here we do the full fledged routine...
15803         * (this is an uncommon case where speed matters less,
15804         * this is why we repeat some of the tests that have been
15805         * done above)
15806         */
15807
15808        boolean drawTop = false;
15809        boolean drawBottom = false;
15810        boolean drawLeft = false;
15811        boolean drawRight = false;
15812
15813        float topFadeStrength = 0.0f;
15814        float bottomFadeStrength = 0.0f;
15815        float leftFadeStrength = 0.0f;
15816        float rightFadeStrength = 0.0f;
15817
15818        // Step 2, save the canvas' layers
15819        int paddingLeft = mPaddingLeft;
15820
15821        final boolean offsetRequired = isPaddingOffsetRequired();
15822        if (offsetRequired) {
15823            paddingLeft += getLeftPaddingOffset();
15824        }
15825
15826        int left = mScrollX + paddingLeft;
15827        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
15828        int top = mScrollY + getFadeTop(offsetRequired);
15829        int bottom = top + getFadeHeight(offsetRequired);
15830
15831        if (offsetRequired) {
15832            right += getRightPaddingOffset();
15833            bottom += getBottomPaddingOffset();
15834        }
15835
15836        final ScrollabilityCache scrollabilityCache = mScrollCache;
15837        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
15838        int length = (int) fadeHeight;
15839
15840        // clip the fade length if top and bottom fades overlap
15841        // overlapping fades produce odd-looking artifacts
15842        if (verticalEdges && (top + length > bottom - length)) {
15843            length = (bottom - top) / 2;
15844        }
15845
15846        // also clip horizontal fades if necessary
15847        if (horizontalEdges && (left + length > right - length)) {
15848            length = (right - left) / 2;
15849        }
15850
15851        if (verticalEdges) {
15852            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
15853            drawTop = topFadeStrength * fadeHeight > 1.0f;
15854            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
15855            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
15856        }
15857
15858        if (horizontalEdges) {
15859            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
15860            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15861            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15862            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15863        }
15864
15865        saveCount = canvas.getSaveCount();
15866
15867        int solidColor = getSolidColor();
15868        if (solidColor == 0) {
15869            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15870
15871            if (drawTop) {
15872                canvas.saveLayer(left, top, right, top + length, null, flags);
15873            }
15874
15875            if (drawBottom) {
15876                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15877            }
15878
15879            if (drawLeft) {
15880                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15881            }
15882
15883            if (drawRight) {
15884                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15885            }
15886        } else {
15887            scrollabilityCache.setFadeColor(solidColor);
15888        }
15889
15890        // Step 3, draw the content
15891        if (!dirtyOpaque) onDraw(canvas);
15892
15893        // Step 4, draw the children
15894        dispatchDraw(canvas);
15895
15896        // Step 5, draw the fade effect and restore layers
15897        final Paint p = scrollabilityCache.paint;
15898        final Matrix matrix = scrollabilityCache.matrix;
15899        final Shader fade = scrollabilityCache.shader;
15900
15901        if (drawTop) {
15902            matrix.setScale(1, fadeHeight * topFadeStrength);
15903            matrix.postTranslate(left, top);
15904            fade.setLocalMatrix(matrix);
15905            p.setShader(fade);
15906            canvas.drawRect(left, top, right, top + length, p);
15907        }
15908
15909        if (drawBottom) {
15910            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15911            matrix.postRotate(180);
15912            matrix.postTranslate(left, bottom);
15913            fade.setLocalMatrix(matrix);
15914            p.setShader(fade);
15915            canvas.drawRect(left, bottom - length, right, bottom, p);
15916        }
15917
15918        if (drawLeft) {
15919            matrix.setScale(1, fadeHeight * leftFadeStrength);
15920            matrix.postRotate(-90);
15921            matrix.postTranslate(left, top);
15922            fade.setLocalMatrix(matrix);
15923            p.setShader(fade);
15924            canvas.drawRect(left, top, left + length, bottom, p);
15925        }
15926
15927        if (drawRight) {
15928            matrix.setScale(1, fadeHeight * rightFadeStrength);
15929            matrix.postRotate(90);
15930            matrix.postTranslate(right, top);
15931            fade.setLocalMatrix(matrix);
15932            p.setShader(fade);
15933            canvas.drawRect(right - length, top, right, bottom, p);
15934        }
15935
15936        canvas.restoreToCount(saveCount);
15937
15938        // Overlay is part of the content and draws beneath Foreground
15939        if (mOverlay != null && !mOverlay.isEmpty()) {
15940            mOverlay.getOverlayView().dispatchDraw(canvas);
15941        }
15942
15943        // Step 6, draw decorations (foreground, scrollbars)
15944        onDrawForeground(canvas);
15945    }
15946
15947    /**
15948     * Draws the background onto the specified canvas.
15949     *
15950     * @param canvas Canvas on which to draw the background
15951     */
15952    private void drawBackground(Canvas canvas) {
15953        final Drawable background = mBackground;
15954        if (background == null) {
15955            return;
15956        }
15957
15958        setBackgroundBounds();
15959
15960        // Attempt to use a display list if requested.
15961        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15962                && mAttachInfo.mHardwareRenderer != null) {
15963            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15964
15965            final RenderNode renderNode = mBackgroundRenderNode;
15966            if (renderNode != null && renderNode.isValid()) {
15967                setBackgroundRenderNodeProperties(renderNode);
15968                ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
15969                return;
15970            }
15971        }
15972
15973        final int scrollX = mScrollX;
15974        final int scrollY = mScrollY;
15975        if ((scrollX | scrollY) == 0) {
15976            background.draw(canvas);
15977        } else {
15978            canvas.translate(scrollX, scrollY);
15979            background.draw(canvas);
15980            canvas.translate(-scrollX, -scrollY);
15981        }
15982    }
15983
15984    /**
15985     * Sets the correct background bounds and rebuilds the outline, if needed.
15986     * <p/>
15987     * This is called by LayoutLib.
15988     */
15989    void setBackgroundBounds() {
15990        if (mBackgroundSizeChanged && mBackground != null) {
15991            mBackground.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15992            mBackgroundSizeChanged = false;
15993            rebuildOutline();
15994        }
15995    }
15996
15997    private void setBackgroundRenderNodeProperties(RenderNode renderNode) {
15998        renderNode.setTranslationX(mScrollX);
15999        renderNode.setTranslationY(mScrollY);
16000    }
16001
16002    /**
16003     * Creates a new display list or updates the existing display list for the
16004     * specified Drawable.
16005     *
16006     * @param drawable Drawable for which to create a display list
16007     * @param renderNode Existing RenderNode, or {@code null}
16008     * @return A valid display list for the specified drawable
16009     */
16010    private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
16011        if (renderNode == null) {
16012            renderNode = RenderNode.create(drawable.getClass().getName(), this);
16013        }
16014
16015        final Rect bounds = drawable.getBounds();
16016        final int width = bounds.width();
16017        final int height = bounds.height();
16018        final DisplayListCanvas canvas = renderNode.start(width, height);
16019
16020        // Reverse left/top translation done by drawable canvas, which will
16021        // instead be applied by rendernode's LTRB bounds below. This way, the
16022        // drawable's bounds match with its rendernode bounds and its content
16023        // will lie within those bounds in the rendernode tree.
16024        canvas.translate(-bounds.left, -bounds.top);
16025
16026        try {
16027            drawable.draw(canvas);
16028        } finally {
16029            renderNode.end(canvas);
16030        }
16031
16032        // Set up drawable properties that are view-independent.
16033        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
16034        renderNode.setProjectBackwards(drawable.isProjected());
16035        renderNode.setProjectionReceiver(true);
16036        renderNode.setClipToBounds(false);
16037        return renderNode;
16038    }
16039
16040    /**
16041     * Returns the overlay for this view, creating it if it does not yet exist.
16042     * Adding drawables to the overlay will cause them to be displayed whenever
16043     * the view itself is redrawn. Objects in the overlay should be actively
16044     * managed: remove them when they should not be displayed anymore. The
16045     * overlay will always have the same size as its host view.
16046     *
16047     * <p>Note: Overlays do not currently work correctly with {@link
16048     * SurfaceView} or {@link TextureView}; contents in overlays for these
16049     * types of views may not display correctly.</p>
16050     *
16051     * @return The ViewOverlay object for this view.
16052     * @see ViewOverlay
16053     */
16054    public ViewOverlay getOverlay() {
16055        if (mOverlay == null) {
16056            mOverlay = new ViewOverlay(mContext, this);
16057        }
16058        return mOverlay;
16059    }
16060
16061    /**
16062     * Override this if your view is known to always be drawn on top of a solid color background,
16063     * and needs to draw fading edges. Returning a non-zero color enables the view system to
16064     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
16065     * should be set to 0xFF.
16066     *
16067     * @see #setVerticalFadingEdgeEnabled(boolean)
16068     * @see #setHorizontalFadingEdgeEnabled(boolean)
16069     *
16070     * @return The known solid color background for this view, or 0 if the color may vary
16071     */
16072    @ViewDebug.ExportedProperty(category = "drawing")
16073    @ColorInt
16074    public int getSolidColor() {
16075        return 0;
16076    }
16077
16078    /**
16079     * Build a human readable string representation of the specified view flags.
16080     *
16081     * @param flags the view flags to convert to a string
16082     * @return a String representing the supplied flags
16083     */
16084    private static String printFlags(int flags) {
16085        String output = "";
16086        int numFlags = 0;
16087        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
16088            output += "TAKES_FOCUS";
16089            numFlags++;
16090        }
16091
16092        switch (flags & VISIBILITY_MASK) {
16093        case INVISIBLE:
16094            if (numFlags > 0) {
16095                output += " ";
16096            }
16097            output += "INVISIBLE";
16098            // USELESS HERE numFlags++;
16099            break;
16100        case GONE:
16101            if (numFlags > 0) {
16102                output += " ";
16103            }
16104            output += "GONE";
16105            // USELESS HERE numFlags++;
16106            break;
16107        default:
16108            break;
16109        }
16110        return output;
16111    }
16112
16113    /**
16114     * Build a human readable string representation of the specified private
16115     * view flags.
16116     *
16117     * @param privateFlags the private view flags to convert to a string
16118     * @return a String representing the supplied flags
16119     */
16120    private static String printPrivateFlags(int privateFlags) {
16121        String output = "";
16122        int numFlags = 0;
16123
16124        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
16125            output += "WANTS_FOCUS";
16126            numFlags++;
16127        }
16128
16129        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
16130            if (numFlags > 0) {
16131                output += " ";
16132            }
16133            output += "FOCUSED";
16134            numFlags++;
16135        }
16136
16137        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
16138            if (numFlags > 0) {
16139                output += " ";
16140            }
16141            output += "SELECTED";
16142            numFlags++;
16143        }
16144
16145        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
16146            if (numFlags > 0) {
16147                output += " ";
16148            }
16149            output += "IS_ROOT_NAMESPACE";
16150            numFlags++;
16151        }
16152
16153        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
16154            if (numFlags > 0) {
16155                output += " ";
16156            }
16157            output += "HAS_BOUNDS";
16158            numFlags++;
16159        }
16160
16161        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
16162            if (numFlags > 0) {
16163                output += " ";
16164            }
16165            output += "DRAWN";
16166            // USELESS HERE numFlags++;
16167        }
16168        return output;
16169    }
16170
16171    /**
16172     * <p>Indicates whether or not this view's layout will be requested during
16173     * the next hierarchy layout pass.</p>
16174     *
16175     * @return true if the layout will be forced during next layout pass
16176     */
16177    public boolean isLayoutRequested() {
16178        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
16179    }
16180
16181    /**
16182     * Return true if o is a ViewGroup that is laying out using optical bounds.
16183     * @hide
16184     */
16185    public static boolean isLayoutModeOptical(Object o) {
16186        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
16187    }
16188
16189    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
16190        Insets parentInsets = mParent instanceof View ?
16191                ((View) mParent).getOpticalInsets() : Insets.NONE;
16192        Insets childInsets = getOpticalInsets();
16193        return setFrame(
16194                left   + parentInsets.left - childInsets.left,
16195                top    + parentInsets.top  - childInsets.top,
16196                right  + parentInsets.left + childInsets.right,
16197                bottom + parentInsets.top  + childInsets.bottom);
16198    }
16199
16200    /**
16201     * Assign a size and position to a view and all of its
16202     * descendants
16203     *
16204     * <p>This is the second phase of the layout mechanism.
16205     * (The first is measuring). In this phase, each parent calls
16206     * layout on all of its children to position them.
16207     * This is typically done using the child measurements
16208     * that were stored in the measure pass().</p>
16209     *
16210     * <p>Derived classes should not override this method.
16211     * Derived classes with children should override
16212     * onLayout. In that method, they should
16213     * call layout on each of their children.</p>
16214     *
16215     * @param l Left position, relative to parent
16216     * @param t Top position, relative to parent
16217     * @param r Right position, relative to parent
16218     * @param b Bottom position, relative to parent
16219     */
16220    @SuppressWarnings({"unchecked"})
16221    public void layout(int l, int t, int r, int b) {
16222        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
16223            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
16224            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
16225        }
16226
16227        int oldL = mLeft;
16228        int oldT = mTop;
16229        int oldB = mBottom;
16230        int oldR = mRight;
16231
16232        boolean changed = isLayoutModeOptical(mParent) ?
16233                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
16234
16235        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
16236            onLayout(changed, l, t, r, b);
16237            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
16238
16239            ListenerInfo li = mListenerInfo;
16240            if (li != null && li.mOnLayoutChangeListeners != null) {
16241                ArrayList<OnLayoutChangeListener> listenersCopy =
16242                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
16243                int numListeners = listenersCopy.size();
16244                for (int i = 0; i < numListeners; ++i) {
16245                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
16246                }
16247            }
16248        }
16249
16250        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
16251        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
16252    }
16253
16254    /**
16255     * Called from layout when this view should
16256     * assign a size and position to each of its children.
16257     *
16258     * Derived classes with children should override
16259     * this method and call layout on each of
16260     * their children.
16261     * @param changed This is a new size or position for this view
16262     * @param left Left position, relative to parent
16263     * @param top Top position, relative to parent
16264     * @param right Right position, relative to parent
16265     * @param bottom Bottom position, relative to parent
16266     */
16267    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16268    }
16269
16270    /**
16271     * Assign a size and position to this view.
16272     *
16273     * This is called from layout.
16274     *
16275     * @param left Left position, relative to parent
16276     * @param top Top position, relative to parent
16277     * @param right Right position, relative to parent
16278     * @param bottom Bottom position, relative to parent
16279     * @return true if the new size and position are different than the
16280     *         previous ones
16281     * {@hide}
16282     */
16283    protected boolean setFrame(int left, int top, int right, int bottom) {
16284        boolean changed = false;
16285
16286        if (DBG) {
16287            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
16288                    + right + "," + bottom + ")");
16289        }
16290
16291        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
16292            changed = true;
16293
16294            // Remember our drawn bit
16295            int drawn = mPrivateFlags & PFLAG_DRAWN;
16296
16297            int oldWidth = mRight - mLeft;
16298            int oldHeight = mBottom - mTop;
16299            int newWidth = right - left;
16300            int newHeight = bottom - top;
16301            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
16302
16303            // Invalidate our old position
16304            invalidate(sizeChanged);
16305
16306            mLeft = left;
16307            mTop = top;
16308            mRight = right;
16309            mBottom = bottom;
16310            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
16311
16312            mPrivateFlags |= PFLAG_HAS_BOUNDS;
16313
16314
16315            if (sizeChanged) {
16316                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
16317            }
16318
16319            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
16320                // If we are visible, force the DRAWN bit to on so that
16321                // this invalidate will go through (at least to our parent).
16322                // This is because someone may have invalidated this view
16323                // before this call to setFrame came in, thereby clearing
16324                // the DRAWN bit.
16325                mPrivateFlags |= PFLAG_DRAWN;
16326                invalidate(sizeChanged);
16327                // parent display list may need to be recreated based on a change in the bounds
16328                // of any child
16329                invalidateParentCaches();
16330            }
16331
16332            // Reset drawn bit to original value (invalidate turns it off)
16333            mPrivateFlags |= drawn;
16334
16335            mBackgroundSizeChanged = true;
16336            if (mForegroundInfo != null) {
16337                mForegroundInfo.mBoundsChanged = true;
16338            }
16339
16340            notifySubtreeAccessibilityStateChangedIfNeeded();
16341        }
16342        return changed;
16343    }
16344
16345    /**
16346     * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}.
16347     * @hide
16348     */
16349    public void setLeftTopRightBottom(int left, int top, int right, int bottom) {
16350        setFrame(left, top, right, bottom);
16351    }
16352
16353    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
16354        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
16355        if (mOverlay != null) {
16356            mOverlay.getOverlayView().setRight(newWidth);
16357            mOverlay.getOverlayView().setBottom(newHeight);
16358        }
16359        rebuildOutline();
16360    }
16361
16362    /**
16363     * Finalize inflating a view from XML.  This is called as the last phase
16364     * of inflation, after all child views have been added.
16365     *
16366     * <p>Even if the subclass overrides onFinishInflate, they should always be
16367     * sure to call the super method, so that we get called.
16368     */
16369    @CallSuper
16370    protected void onFinishInflate() {
16371    }
16372
16373    /**
16374     * Returns the resources associated with this view.
16375     *
16376     * @return Resources object.
16377     */
16378    public Resources getResources() {
16379        return mResources;
16380    }
16381
16382    /**
16383     * Invalidates the specified Drawable.
16384     *
16385     * @param drawable the drawable to invalidate
16386     */
16387    @Override
16388    public void invalidateDrawable(@NonNull Drawable drawable) {
16389        if (verifyDrawable(drawable)) {
16390            final Rect dirty = drawable.getDirtyBounds();
16391            final int scrollX = mScrollX;
16392            final int scrollY = mScrollY;
16393
16394            invalidate(dirty.left + scrollX, dirty.top + scrollY,
16395                    dirty.right + scrollX, dirty.bottom + scrollY);
16396            rebuildOutline();
16397        }
16398    }
16399
16400    /**
16401     * Schedules an action on a drawable to occur at a specified time.
16402     *
16403     * @param who the recipient of the action
16404     * @param what the action to run on the drawable
16405     * @param when the time at which the action must occur. Uses the
16406     *        {@link SystemClock#uptimeMillis} timebase.
16407     */
16408    @Override
16409    public void scheduleDrawable(Drawable who, Runnable what, long when) {
16410        if (verifyDrawable(who) && what != null) {
16411            final long delay = when - SystemClock.uptimeMillis();
16412            if (mAttachInfo != null) {
16413                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
16414                        Choreographer.CALLBACK_ANIMATION, what, who,
16415                        Choreographer.subtractFrameDelay(delay));
16416            } else {
16417                ViewRootImpl.getRunQueue().postDelayed(what, delay);
16418            }
16419        }
16420    }
16421
16422    /**
16423     * Cancels a scheduled action on a drawable.
16424     *
16425     * @param who the recipient of the action
16426     * @param what the action to cancel
16427     */
16428    @Override
16429    public void unscheduleDrawable(Drawable who, Runnable what) {
16430        if (verifyDrawable(who) && what != null) {
16431            if (mAttachInfo != null) {
16432                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16433                        Choreographer.CALLBACK_ANIMATION, what, who);
16434            }
16435            ViewRootImpl.getRunQueue().removeCallbacks(what);
16436        }
16437    }
16438
16439    /**
16440     * Unschedule any events associated with the given Drawable.  This can be
16441     * used when selecting a new Drawable into a view, so that the previous
16442     * one is completely unscheduled.
16443     *
16444     * @param who The Drawable to unschedule.
16445     *
16446     * @see #drawableStateChanged
16447     */
16448    public void unscheduleDrawable(Drawable who) {
16449        if (mAttachInfo != null && who != null) {
16450            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
16451                    Choreographer.CALLBACK_ANIMATION, null, who);
16452        }
16453    }
16454
16455    /**
16456     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
16457     * that the View directionality can and will be resolved before its Drawables.
16458     *
16459     * Will call {@link View#onResolveDrawables} when resolution is done.
16460     *
16461     * @hide
16462     */
16463    protected void resolveDrawables() {
16464        // Drawables resolution may need to happen before resolving the layout direction (which is
16465        // done only during the measure() call).
16466        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
16467        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
16468        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
16469        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
16470        // direction to be resolved as its resolved value will be the same as its raw value.
16471        if (!isLayoutDirectionResolved() &&
16472                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
16473            return;
16474        }
16475
16476        final int layoutDirection = isLayoutDirectionResolved() ?
16477                getLayoutDirection() : getRawLayoutDirection();
16478
16479        if (mBackground != null) {
16480            mBackground.setLayoutDirection(layoutDirection);
16481        }
16482        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16483            mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection);
16484        }
16485        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
16486        onResolveDrawables(layoutDirection);
16487    }
16488
16489    boolean areDrawablesResolved() {
16490        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
16491    }
16492
16493    /**
16494     * Called when layout direction has been resolved.
16495     *
16496     * The default implementation does nothing.
16497     *
16498     * @param layoutDirection The resolved layout direction.
16499     *
16500     * @see #LAYOUT_DIRECTION_LTR
16501     * @see #LAYOUT_DIRECTION_RTL
16502     *
16503     * @hide
16504     */
16505    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
16506    }
16507
16508    /**
16509     * @hide
16510     */
16511    protected void resetResolvedDrawables() {
16512        resetResolvedDrawablesInternal();
16513    }
16514
16515    void resetResolvedDrawablesInternal() {
16516        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
16517    }
16518
16519    /**
16520     * If your view subclass is displaying its own Drawable objects, it should
16521     * override this function and return true for any Drawable it is
16522     * displaying.  This allows animations for those drawables to be
16523     * scheduled.
16524     *
16525     * <p>Be sure to call through to the super class when overriding this
16526     * function.
16527     *
16528     * @param who The Drawable to verify.  Return true if it is one you are
16529     *            displaying, else return the result of calling through to the
16530     *            super class.
16531     *
16532     * @return boolean If true than the Drawable is being displayed in the
16533     *         view; else false and it is not allowed to animate.
16534     *
16535     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
16536     * @see #drawableStateChanged()
16537     */
16538    @CallSuper
16539    protected boolean verifyDrawable(Drawable who) {
16540        return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who)
16541                || (mForegroundInfo != null && mForegroundInfo.mDrawable == who);
16542    }
16543
16544    /**
16545     * This function is called whenever the state of the view changes in such
16546     * a way that it impacts the state of drawables being shown.
16547     * <p>
16548     * If the View has a StateListAnimator, it will also be called to run necessary state
16549     * change animations.
16550     * <p>
16551     * Be sure to call through to the superclass when overriding this function.
16552     *
16553     * @see Drawable#setState(int[])
16554     */
16555    @CallSuper
16556    protected void drawableStateChanged() {
16557        final int[] state = getDrawableState();
16558
16559        final Drawable bg = mBackground;
16560        if (bg != null && bg.isStateful()) {
16561            bg.setState(state);
16562        }
16563
16564        final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
16565        if (fg != null && fg.isStateful()) {
16566            fg.setState(state);
16567        }
16568
16569        if (mScrollCache != null) {
16570            final Drawable scrollBar = mScrollCache.scrollBar;
16571            if (scrollBar != null && scrollBar.isStateful()) {
16572                scrollBar.setState(state);
16573            }
16574        }
16575
16576        if (mStateListAnimator != null) {
16577            mStateListAnimator.setState(state);
16578        }
16579    }
16580
16581    /**
16582     * This function is called whenever the view hotspot changes and needs to
16583     * be propagated to drawables or child views managed by the view.
16584     * <p>
16585     * Dispatching to child views is handled by
16586     * {@link #dispatchDrawableHotspotChanged(float, float)}.
16587     * <p>
16588     * Be sure to call through to the superclass when overriding this function.
16589     *
16590     * @param x hotspot x coordinate
16591     * @param y hotspot y coordinate
16592     */
16593    @CallSuper
16594    public void drawableHotspotChanged(float x, float y) {
16595        if (mBackground != null) {
16596            mBackground.setHotspot(x, y);
16597        }
16598        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16599            mForegroundInfo.mDrawable.setHotspot(x, y);
16600        }
16601
16602        dispatchDrawableHotspotChanged(x, y);
16603    }
16604
16605    /**
16606     * Dispatches drawableHotspotChanged to all of this View's children.
16607     *
16608     * @param x hotspot x coordinate
16609     * @param y hotspot y coordinate
16610     * @see #drawableHotspotChanged(float, float)
16611     */
16612    public void dispatchDrawableHotspotChanged(float x, float y) {
16613    }
16614
16615    /**
16616     * Call this to force a view to update its drawable state. This will cause
16617     * drawableStateChanged to be called on this view. Views that are interested
16618     * in the new state should call getDrawableState.
16619     *
16620     * @see #drawableStateChanged
16621     * @see #getDrawableState
16622     */
16623    public void refreshDrawableState() {
16624        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
16625        drawableStateChanged();
16626
16627        ViewParent parent = mParent;
16628        if (parent != null) {
16629            parent.childDrawableStateChanged(this);
16630        }
16631    }
16632
16633    /**
16634     * Return an array of resource IDs of the drawable states representing the
16635     * current state of the view.
16636     *
16637     * @return The current drawable state
16638     *
16639     * @see Drawable#setState(int[])
16640     * @see #drawableStateChanged()
16641     * @see #onCreateDrawableState(int)
16642     */
16643    public final int[] getDrawableState() {
16644        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
16645            return mDrawableState;
16646        } else {
16647            mDrawableState = onCreateDrawableState(0);
16648            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
16649            return mDrawableState;
16650        }
16651    }
16652
16653    /**
16654     * Generate the new {@link android.graphics.drawable.Drawable} state for
16655     * this view. This is called by the view
16656     * system when the cached Drawable state is determined to be invalid.  To
16657     * retrieve the current state, you should use {@link #getDrawableState}.
16658     *
16659     * @param extraSpace if non-zero, this is the number of extra entries you
16660     * would like in the returned array in which you can place your own
16661     * states.
16662     *
16663     * @return Returns an array holding the current {@link Drawable} state of
16664     * the view.
16665     *
16666     * @see #mergeDrawableStates(int[], int[])
16667     */
16668    protected int[] onCreateDrawableState(int extraSpace) {
16669        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
16670                mParent instanceof View) {
16671            return ((View) mParent).onCreateDrawableState(extraSpace);
16672        }
16673
16674        int[] drawableState;
16675
16676        int privateFlags = mPrivateFlags;
16677
16678        int viewStateIndex = 0;
16679        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED;
16680        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED;
16681        if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED;
16682        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED;
16683        if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED;
16684        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED;
16685        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
16686                HardwareRenderer.isAvailable()) {
16687            // This is set if HW acceleration is requested, even if the current
16688            // process doesn't allow it.  This is just to allow app preview
16689            // windows to better match their app.
16690            viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED;
16691        }
16692        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED;
16693
16694        final int privateFlags2 = mPrivateFlags2;
16695        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) {
16696            viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT;
16697        }
16698        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) {
16699            viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED;
16700        }
16701
16702        drawableState = StateSet.get(viewStateIndex);
16703
16704        //noinspection ConstantIfStatement
16705        if (false) {
16706            Log.i("View", "drawableStateIndex=" + viewStateIndex);
16707            Log.i("View", toString()
16708                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
16709                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
16710                    + " fo=" + hasFocus()
16711                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
16712                    + " wf=" + hasWindowFocus()
16713                    + ": " + Arrays.toString(drawableState));
16714        }
16715
16716        if (extraSpace == 0) {
16717            return drawableState;
16718        }
16719
16720        final int[] fullState;
16721        if (drawableState != null) {
16722            fullState = new int[drawableState.length + extraSpace];
16723            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
16724        } else {
16725            fullState = new int[extraSpace];
16726        }
16727
16728        return fullState;
16729    }
16730
16731    /**
16732     * Merge your own state values in <var>additionalState</var> into the base
16733     * state values <var>baseState</var> that were returned by
16734     * {@link #onCreateDrawableState(int)}.
16735     *
16736     * @param baseState The base state values returned by
16737     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
16738     * own additional state values.
16739     *
16740     * @param additionalState The additional state values you would like
16741     * added to <var>baseState</var>; this array is not modified.
16742     *
16743     * @return As a convenience, the <var>baseState</var> array you originally
16744     * passed into the function is returned.
16745     *
16746     * @see #onCreateDrawableState(int)
16747     */
16748    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
16749        final int N = baseState.length;
16750        int i = N - 1;
16751        while (i >= 0 && baseState[i] == 0) {
16752            i--;
16753        }
16754        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
16755        return baseState;
16756    }
16757
16758    /**
16759     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
16760     * on all Drawable objects associated with this view.
16761     * <p>
16762     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
16763     * attached to this view.
16764     */
16765    public void jumpDrawablesToCurrentState() {
16766        if (mBackground != null) {
16767            mBackground.jumpToCurrentState();
16768        }
16769        if (mStateListAnimator != null) {
16770            mStateListAnimator.jumpToCurrentState();
16771        }
16772        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) {
16773            mForegroundInfo.mDrawable.jumpToCurrentState();
16774        }
16775    }
16776
16777    /**
16778     * Sets the background color for this view.
16779     * @param color the color of the background
16780     */
16781    @RemotableViewMethod
16782    public void setBackgroundColor(@ColorInt int color) {
16783        if (mBackground instanceof ColorDrawable) {
16784            ((ColorDrawable) mBackground.mutate()).setColor(color);
16785            computeOpaqueFlags();
16786            mBackgroundResource = 0;
16787        } else {
16788            setBackground(new ColorDrawable(color));
16789        }
16790    }
16791
16792    /**
16793     * If the view has a ColorDrawable background, returns the color of that
16794     * drawable.
16795     *
16796     * @return The color of the ColorDrawable background, if set, otherwise 0.
16797     */
16798    @ColorInt
16799    public int getBackgroundColor() {
16800        if (mBackground instanceof ColorDrawable) {
16801            return ((ColorDrawable) mBackground).getColor();
16802        }
16803        return 0;
16804    }
16805
16806    /**
16807     * Set the background to a given resource. The resource should refer to
16808     * a Drawable object or 0 to remove the background.
16809     * @param resid The identifier of the resource.
16810     *
16811     * @attr ref android.R.styleable#View_background
16812     */
16813    @RemotableViewMethod
16814    public void setBackgroundResource(@DrawableRes int resid) {
16815        if (resid != 0 && resid == mBackgroundResource) {
16816            return;
16817        }
16818
16819        Drawable d = null;
16820        if (resid != 0) {
16821            d = mContext.getDrawable(resid);
16822        }
16823        setBackground(d);
16824
16825        mBackgroundResource = resid;
16826    }
16827
16828    /**
16829     * Set the background to a given Drawable, or remove the background. If the
16830     * background has padding, this View's padding is set to the background's
16831     * padding. However, when a background is removed, this View's padding isn't
16832     * touched. If setting the padding is desired, please use
16833     * {@link #setPadding(int, int, int, int)}.
16834     *
16835     * @param background The Drawable to use as the background, or null to remove the
16836     *        background
16837     */
16838    public void setBackground(Drawable background) {
16839        //noinspection deprecation
16840        setBackgroundDrawable(background);
16841    }
16842
16843    /**
16844     * @deprecated use {@link #setBackground(Drawable)} instead
16845     */
16846    @Deprecated
16847    public void setBackgroundDrawable(Drawable background) {
16848        computeOpaqueFlags();
16849
16850        if (background == mBackground) {
16851            return;
16852        }
16853
16854        boolean requestLayout = false;
16855
16856        mBackgroundResource = 0;
16857
16858        /*
16859         * Regardless of whether we're setting a new background or not, we want
16860         * to clear the previous drawable.
16861         */
16862        if (mBackground != null) {
16863            mBackground.setCallback(null);
16864            unscheduleDrawable(mBackground);
16865        }
16866
16867        if (background != null) {
16868            Rect padding = sThreadLocal.get();
16869            if (padding == null) {
16870                padding = new Rect();
16871                sThreadLocal.set(padding);
16872            }
16873            resetResolvedDrawablesInternal();
16874            background.setLayoutDirection(getLayoutDirection());
16875            if (background.getPadding(padding)) {
16876                resetResolvedPaddingInternal();
16877                switch (background.getLayoutDirection()) {
16878                    case LAYOUT_DIRECTION_RTL:
16879                        mUserPaddingLeftInitial = padding.right;
16880                        mUserPaddingRightInitial = padding.left;
16881                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
16882                        break;
16883                    case LAYOUT_DIRECTION_LTR:
16884                    default:
16885                        mUserPaddingLeftInitial = padding.left;
16886                        mUserPaddingRightInitial = padding.right;
16887                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
16888                }
16889                mLeftPaddingDefined = false;
16890                mRightPaddingDefined = false;
16891            }
16892
16893            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
16894            // if it has a different minimum size, we should layout again
16895            if (mBackground == null
16896                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
16897                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
16898                requestLayout = true;
16899            }
16900
16901            background.setCallback(this);
16902            if (background.isStateful()) {
16903                background.setState(getDrawableState());
16904            }
16905            background.setVisible(getVisibility() == VISIBLE, false);
16906            mBackground = background;
16907
16908            applyBackgroundTint();
16909
16910            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16911                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16912                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16913                requestLayout = true;
16914            }
16915        } else {
16916            /* Remove the background */
16917            mBackground = null;
16918
16919            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16920                /*
16921                 * This view ONLY drew the background before and we're removing
16922                 * the background, so now it won't draw anything
16923                 * (hence we SKIP_DRAW)
16924                 */
16925                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16926                mPrivateFlags |= PFLAG_SKIP_DRAW;
16927            }
16928
16929            /*
16930             * When the background is set, we try to apply its padding to this
16931             * View. When the background is removed, we don't touch this View's
16932             * padding. This is noted in the Javadocs. Hence, we don't need to
16933             * requestLayout(), the invalidate() below is sufficient.
16934             */
16935
16936            // The old background's minimum size could have affected this
16937            // View's layout, so let's requestLayout
16938            requestLayout = true;
16939        }
16940
16941        computeOpaqueFlags();
16942
16943        if (requestLayout) {
16944            requestLayout();
16945        }
16946
16947        mBackgroundSizeChanged = true;
16948        invalidate(true);
16949    }
16950
16951    /**
16952     * Gets the background drawable
16953     *
16954     * @return The drawable used as the background for this view, if any.
16955     *
16956     * @see #setBackground(Drawable)
16957     *
16958     * @attr ref android.R.styleable#View_background
16959     */
16960    public Drawable getBackground() {
16961        return mBackground;
16962    }
16963
16964    /**
16965     * Applies a tint to the background drawable. Does not modify the current tint
16966     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
16967     * <p>
16968     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16969     * mutate the drawable and apply the specified tint and tint mode using
16970     * {@link Drawable#setTintList(ColorStateList)}.
16971     *
16972     * @param tint the tint to apply, may be {@code null} to clear tint
16973     *
16974     * @attr ref android.R.styleable#View_backgroundTint
16975     * @see #getBackgroundTintList()
16976     * @see Drawable#setTintList(ColorStateList)
16977     */
16978    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16979        if (mBackgroundTint == null) {
16980            mBackgroundTint = new TintInfo();
16981        }
16982        mBackgroundTint.mTintList = tint;
16983        mBackgroundTint.mHasTintList = true;
16984
16985        applyBackgroundTint();
16986    }
16987
16988    /**
16989     * Return the tint applied to the background drawable, if specified.
16990     *
16991     * @return the tint applied to the background drawable
16992     * @attr ref android.R.styleable#View_backgroundTint
16993     * @see #setBackgroundTintList(ColorStateList)
16994     */
16995    @Nullable
16996    public ColorStateList getBackgroundTintList() {
16997        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
16998    }
16999
17000    /**
17001     * Specifies the blending mode used to apply the tint specified by
17002     * {@link #setBackgroundTintList(ColorStateList)}} to the background
17003     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17004     *
17005     * @param tintMode the blending mode used to apply the tint, may be
17006     *                 {@code null} to clear tint
17007     * @attr ref android.R.styleable#View_backgroundTintMode
17008     * @see #getBackgroundTintMode()
17009     * @see Drawable#setTintMode(PorterDuff.Mode)
17010     */
17011    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17012        if (mBackgroundTint == null) {
17013            mBackgroundTint = new TintInfo();
17014        }
17015        mBackgroundTint.mTintMode = tintMode;
17016        mBackgroundTint.mHasTintMode = true;
17017
17018        applyBackgroundTint();
17019    }
17020
17021    /**
17022     * Return the blending mode used to apply the tint to the background
17023     * drawable, if specified.
17024     *
17025     * @return the blending mode used to apply the tint to the background
17026     *         drawable
17027     * @attr ref android.R.styleable#View_backgroundTintMode
17028     * @see #setBackgroundTintMode(PorterDuff.Mode)
17029     */
17030    @Nullable
17031    public PorterDuff.Mode getBackgroundTintMode() {
17032        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
17033    }
17034
17035    private void applyBackgroundTint() {
17036        if (mBackground != null && mBackgroundTint != null) {
17037            final TintInfo tintInfo = mBackgroundTint;
17038            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17039                mBackground = mBackground.mutate();
17040
17041                if (tintInfo.mHasTintList) {
17042                    mBackground.setTintList(tintInfo.mTintList);
17043                }
17044
17045                if (tintInfo.mHasTintMode) {
17046                    mBackground.setTintMode(tintInfo.mTintMode);
17047                }
17048
17049                // The drawable (or one of its children) may not have been
17050                // stateful before applying the tint, so let's try again.
17051                if (mBackground.isStateful()) {
17052                    mBackground.setState(getDrawableState());
17053                }
17054            }
17055        }
17056    }
17057
17058    /**
17059     * Returns the drawable used as the foreground of this View. The
17060     * foreground drawable, if non-null, is always drawn on top of the view's content.
17061     *
17062     * @return a Drawable or null if no foreground was set
17063     *
17064     * @see #onDrawForeground(Canvas)
17065     */
17066    public Drawable getForeground() {
17067        return mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17068    }
17069
17070    /**
17071     * Supply a Drawable that is to be rendered on top of all of the content in the view.
17072     *
17073     * @param foreground the Drawable to be drawn on top of the children
17074     *
17075     * @attr ref android.R.styleable#View_foreground
17076     */
17077    public void setForeground(Drawable foreground) {
17078        if (mForegroundInfo == null) {
17079            if (foreground == null) {
17080                // Nothing to do.
17081                return;
17082            }
17083            mForegroundInfo = new ForegroundInfo();
17084        }
17085
17086        if (foreground == mForegroundInfo.mDrawable) {
17087            // Nothing to do
17088            return;
17089        }
17090
17091        if (mForegroundInfo.mDrawable != null) {
17092            mForegroundInfo.mDrawable.setCallback(null);
17093            unscheduleDrawable(mForegroundInfo.mDrawable);
17094        }
17095
17096        mForegroundInfo.mDrawable = foreground;
17097        mForegroundInfo.mBoundsChanged = true;
17098        if (foreground != null) {
17099            setWillNotDraw(false);
17100            foreground.setCallback(this);
17101            foreground.setLayoutDirection(getLayoutDirection());
17102            if (foreground.isStateful()) {
17103                foreground.setState(getDrawableState());
17104            }
17105            applyForegroundTint();
17106        }
17107        requestLayout();
17108        invalidate();
17109    }
17110
17111    /**
17112     * Magic bit used to support features of framework-internal window decor implementation details.
17113     * This used to live exclusively in FrameLayout.
17114     *
17115     * @return true if the foreground should draw inside the padding region or false
17116     *         if it should draw inset by the view's padding
17117     * @hide internal use only; only used by FrameLayout and internal screen layouts.
17118     */
17119    public boolean isForegroundInsidePadding() {
17120        return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true;
17121    }
17122
17123    /**
17124     * Describes how the foreground is positioned.
17125     *
17126     * @return foreground gravity.
17127     *
17128     * @see #setForegroundGravity(int)
17129     *
17130     * @attr ref android.R.styleable#View_foregroundGravity
17131     */
17132    public int getForegroundGravity() {
17133        return mForegroundInfo != null ? mForegroundInfo.mGravity
17134                : Gravity.START | Gravity.TOP;
17135    }
17136
17137    /**
17138     * Describes how the foreground is positioned. Defaults to START and TOP.
17139     *
17140     * @param gravity see {@link android.view.Gravity}
17141     *
17142     * @see #getForegroundGravity()
17143     *
17144     * @attr ref android.R.styleable#View_foregroundGravity
17145     */
17146    public void setForegroundGravity(int gravity) {
17147        if (mForegroundInfo == null) {
17148            mForegroundInfo = new ForegroundInfo();
17149        }
17150
17151        if (mForegroundInfo.mGravity != gravity) {
17152            if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
17153                gravity |= Gravity.START;
17154            }
17155
17156            if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
17157                gravity |= Gravity.TOP;
17158            }
17159
17160            mForegroundInfo.mGravity = gravity;
17161            requestLayout();
17162        }
17163    }
17164
17165    /**
17166     * Applies a tint to the foreground drawable. Does not modify the current tint
17167     * mode, which is {@link PorterDuff.Mode#SRC_IN} by default.
17168     * <p>
17169     * Subsequent calls to {@link #setForeground(Drawable)} will automatically
17170     * mutate the drawable and apply the specified tint and tint mode using
17171     * {@link Drawable#setTintList(ColorStateList)}.
17172     *
17173     * @param tint the tint to apply, may be {@code null} to clear tint
17174     *
17175     * @attr ref android.R.styleable#View_foregroundTint
17176     * @see #getForegroundTintList()
17177     * @see Drawable#setTintList(ColorStateList)
17178     */
17179    public void setForegroundTintList(@Nullable ColorStateList tint) {
17180        if (mForegroundInfo == null) {
17181            mForegroundInfo = new ForegroundInfo();
17182        }
17183        if (mForegroundInfo.mTintInfo == null) {
17184            mForegroundInfo.mTintInfo = new TintInfo();
17185        }
17186        mForegroundInfo.mTintInfo.mTintList = tint;
17187        mForegroundInfo.mTintInfo.mHasTintList = true;
17188
17189        applyForegroundTint();
17190    }
17191
17192    /**
17193     * Return the tint applied to the foreground drawable, if specified.
17194     *
17195     * @return the tint applied to the foreground drawable
17196     * @attr ref android.R.styleable#View_foregroundTint
17197     * @see #setForegroundTintList(ColorStateList)
17198     */
17199    @Nullable
17200    public ColorStateList getForegroundTintList() {
17201        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17202                ? mForegroundInfo.mTintInfo.mTintList : null;
17203    }
17204
17205    /**
17206     * Specifies the blending mode used to apply the tint specified by
17207     * {@link #setForegroundTintList(ColorStateList)}} to the background
17208     * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}.
17209     *
17210     * @param tintMode the blending mode used to apply the tint, may be
17211     *                 {@code null} to clear tint
17212     * @attr ref android.R.styleable#View_foregroundTintMode
17213     * @see #getForegroundTintMode()
17214     * @see Drawable#setTintMode(PorterDuff.Mode)
17215     */
17216    public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) {
17217        if (mBackgroundTint == null) {
17218            mBackgroundTint = new TintInfo();
17219        }
17220        mBackgroundTint.mTintMode = tintMode;
17221        mBackgroundTint.mHasTintMode = true;
17222
17223        applyBackgroundTint();
17224    }
17225
17226    /**
17227     * Return the blending mode used to apply the tint to the foreground
17228     * drawable, if specified.
17229     *
17230     * @return the blending mode used to apply the tint to the foreground
17231     *         drawable
17232     * @attr ref android.R.styleable#View_foregroundTintMode
17233     * @see #setBackgroundTintMode(PorterDuff.Mode)
17234     */
17235    @Nullable
17236    public PorterDuff.Mode getForegroundTintMode() {
17237        return mForegroundInfo != null && mForegroundInfo.mTintInfo != null
17238                ? mForegroundInfo.mTintInfo.mTintMode : null;
17239    }
17240
17241    private void applyForegroundTint() {
17242        if (mForegroundInfo != null && mForegroundInfo.mDrawable != null
17243                && mForegroundInfo.mTintInfo != null) {
17244            final TintInfo tintInfo = mForegroundInfo.mTintInfo;
17245            if (tintInfo.mHasTintList || tintInfo.mHasTintMode) {
17246                mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate();
17247
17248                if (tintInfo.mHasTintList) {
17249                    mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList);
17250                }
17251
17252                if (tintInfo.mHasTintMode) {
17253                    mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode);
17254                }
17255
17256                // The drawable (or one of its children) may not have been
17257                // stateful before applying the tint, so let's try again.
17258                if (mForegroundInfo.mDrawable.isStateful()) {
17259                    mForegroundInfo.mDrawable.setState(getDrawableState());
17260                }
17261            }
17262        }
17263    }
17264
17265    /**
17266     * Draw any foreground content for this view.
17267     *
17268     * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground}
17269     * drawable or other view-specific decorations. The foreground is drawn on top of the
17270     * primary view content.</p>
17271     *
17272     * @param canvas canvas to draw into
17273     */
17274    public void onDrawForeground(Canvas canvas) {
17275        onDrawScrollBars(canvas);
17276
17277        final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
17278        if (foreground != null) {
17279            if (mForegroundInfo.mBoundsChanged) {
17280                mForegroundInfo.mBoundsChanged = false;
17281                final Rect selfBounds = mForegroundInfo.mSelfBounds;
17282                final Rect overlayBounds = mForegroundInfo.mOverlayBounds;
17283
17284                if (mForegroundInfo.mInsidePadding) {
17285                    selfBounds.set(0, 0, getWidth(), getHeight());
17286                } else {
17287                    selfBounds.set(getPaddingLeft(), getPaddingTop(),
17288                            getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
17289                }
17290
17291                final int ld = getLayoutDirection();
17292                Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(),
17293                        foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld);
17294                foreground.setBounds(overlayBounds);
17295            }
17296
17297            foreground.draw(canvas);
17298        }
17299    }
17300
17301    /**
17302     * Sets the padding. The view may add on the space required to display
17303     * the scrollbars, depending on the style and visibility of the scrollbars.
17304     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
17305     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
17306     * from the values set in this call.
17307     *
17308     * @attr ref android.R.styleable#View_padding
17309     * @attr ref android.R.styleable#View_paddingBottom
17310     * @attr ref android.R.styleable#View_paddingLeft
17311     * @attr ref android.R.styleable#View_paddingRight
17312     * @attr ref android.R.styleable#View_paddingTop
17313     * @param left the left padding in pixels
17314     * @param top the top padding in pixels
17315     * @param right the right padding in pixels
17316     * @param bottom the bottom padding in pixels
17317     */
17318    public void setPadding(int left, int top, int right, int bottom) {
17319        resetResolvedPaddingInternal();
17320
17321        mUserPaddingStart = UNDEFINED_PADDING;
17322        mUserPaddingEnd = UNDEFINED_PADDING;
17323
17324        mUserPaddingLeftInitial = left;
17325        mUserPaddingRightInitial = right;
17326
17327        mLeftPaddingDefined = true;
17328        mRightPaddingDefined = true;
17329
17330        internalSetPadding(left, top, right, bottom);
17331    }
17332
17333    /**
17334     * @hide
17335     */
17336    protected void internalSetPadding(int left, int top, int right, int bottom) {
17337        mUserPaddingLeft = left;
17338        mUserPaddingRight = right;
17339        mUserPaddingBottom = bottom;
17340
17341        final int viewFlags = mViewFlags;
17342        boolean changed = false;
17343
17344        // Common case is there are no scroll bars.
17345        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
17346            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
17347                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
17348                        ? 0 : getVerticalScrollbarWidth();
17349                switch (mVerticalScrollbarPosition) {
17350                    case SCROLLBAR_POSITION_DEFAULT:
17351                        if (isLayoutRtl()) {
17352                            left += offset;
17353                        } else {
17354                            right += offset;
17355                        }
17356                        break;
17357                    case SCROLLBAR_POSITION_RIGHT:
17358                        right += offset;
17359                        break;
17360                    case SCROLLBAR_POSITION_LEFT:
17361                        left += offset;
17362                        break;
17363                }
17364            }
17365            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
17366                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
17367                        ? 0 : getHorizontalScrollbarHeight();
17368            }
17369        }
17370
17371        if (mPaddingLeft != left) {
17372            changed = true;
17373            mPaddingLeft = left;
17374        }
17375        if (mPaddingTop != top) {
17376            changed = true;
17377            mPaddingTop = top;
17378        }
17379        if (mPaddingRight != right) {
17380            changed = true;
17381            mPaddingRight = right;
17382        }
17383        if (mPaddingBottom != bottom) {
17384            changed = true;
17385            mPaddingBottom = bottom;
17386        }
17387
17388        if (changed) {
17389            requestLayout();
17390            invalidateOutline();
17391        }
17392    }
17393
17394    /**
17395     * Sets the relative padding. The view may add on the space required to display
17396     * the scrollbars, depending on the style and visibility of the scrollbars.
17397     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
17398     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
17399     * from the values set in this call.
17400     *
17401     * @attr ref android.R.styleable#View_padding
17402     * @attr ref android.R.styleable#View_paddingBottom
17403     * @attr ref android.R.styleable#View_paddingStart
17404     * @attr ref android.R.styleable#View_paddingEnd
17405     * @attr ref android.R.styleable#View_paddingTop
17406     * @param start the start padding in pixels
17407     * @param top the top padding in pixels
17408     * @param end the end padding in pixels
17409     * @param bottom the bottom padding in pixels
17410     */
17411    public void setPaddingRelative(int start, int top, int end, int bottom) {
17412        resetResolvedPaddingInternal();
17413
17414        mUserPaddingStart = start;
17415        mUserPaddingEnd = end;
17416        mLeftPaddingDefined = true;
17417        mRightPaddingDefined = true;
17418
17419        switch(getLayoutDirection()) {
17420            case LAYOUT_DIRECTION_RTL:
17421                mUserPaddingLeftInitial = end;
17422                mUserPaddingRightInitial = start;
17423                internalSetPadding(end, top, start, bottom);
17424                break;
17425            case LAYOUT_DIRECTION_LTR:
17426            default:
17427                mUserPaddingLeftInitial = start;
17428                mUserPaddingRightInitial = end;
17429                internalSetPadding(start, top, end, bottom);
17430        }
17431    }
17432
17433    /**
17434     * Returns the top padding of this view.
17435     *
17436     * @return the top padding in pixels
17437     */
17438    public int getPaddingTop() {
17439        return mPaddingTop;
17440    }
17441
17442    /**
17443     * Returns the bottom padding of this view. If there are inset and enabled
17444     * scrollbars, this value may include the space required to display the
17445     * scrollbars as well.
17446     *
17447     * @return the bottom padding in pixels
17448     */
17449    public int getPaddingBottom() {
17450        return mPaddingBottom;
17451    }
17452
17453    /**
17454     * Returns the left padding of this view. If there are inset and enabled
17455     * scrollbars, this value may include the space required to display the
17456     * scrollbars as well.
17457     *
17458     * @return the left padding in pixels
17459     */
17460    public int getPaddingLeft() {
17461        if (!isPaddingResolved()) {
17462            resolvePadding();
17463        }
17464        return mPaddingLeft;
17465    }
17466
17467    /**
17468     * Returns the start padding of this view depending on its resolved layout direction.
17469     * If there are inset and enabled scrollbars, this value may include the space
17470     * required to display the scrollbars as well.
17471     *
17472     * @return the start padding in pixels
17473     */
17474    public int getPaddingStart() {
17475        if (!isPaddingResolved()) {
17476            resolvePadding();
17477        }
17478        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17479                mPaddingRight : mPaddingLeft;
17480    }
17481
17482    /**
17483     * Returns the right padding of this view. If there are inset and enabled
17484     * scrollbars, this value may include the space required to display the
17485     * scrollbars as well.
17486     *
17487     * @return the right padding in pixels
17488     */
17489    public int getPaddingRight() {
17490        if (!isPaddingResolved()) {
17491            resolvePadding();
17492        }
17493        return mPaddingRight;
17494    }
17495
17496    /**
17497     * Returns the end padding of this view depending on its resolved layout direction.
17498     * If there are inset and enabled scrollbars, this value may include the space
17499     * required to display the scrollbars as well.
17500     *
17501     * @return the end padding in pixels
17502     */
17503    public int getPaddingEnd() {
17504        if (!isPaddingResolved()) {
17505            resolvePadding();
17506        }
17507        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
17508                mPaddingLeft : mPaddingRight;
17509    }
17510
17511    /**
17512     * Return if the padding has been set through relative values
17513     * {@link #setPaddingRelative(int, int, int, int)} or through
17514     * @attr ref android.R.styleable#View_paddingStart or
17515     * @attr ref android.R.styleable#View_paddingEnd
17516     *
17517     * @return true if the padding is relative or false if it is not.
17518     */
17519    public boolean isPaddingRelative() {
17520        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
17521    }
17522
17523    Insets computeOpticalInsets() {
17524        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
17525    }
17526
17527    /**
17528     * @hide
17529     */
17530    public void resetPaddingToInitialValues() {
17531        if (isRtlCompatibilityMode()) {
17532            mPaddingLeft = mUserPaddingLeftInitial;
17533            mPaddingRight = mUserPaddingRightInitial;
17534            return;
17535        }
17536        if (isLayoutRtl()) {
17537            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
17538            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
17539        } else {
17540            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
17541            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
17542        }
17543    }
17544
17545    /**
17546     * @hide
17547     */
17548    public Insets getOpticalInsets() {
17549        if (mLayoutInsets == null) {
17550            mLayoutInsets = computeOpticalInsets();
17551        }
17552        return mLayoutInsets;
17553    }
17554
17555    /**
17556     * Set this view's optical insets.
17557     *
17558     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
17559     * property. Views that compute their own optical insets should call it as part of measurement.
17560     * This method does not request layout. If you are setting optical insets outside of
17561     * measure/layout itself you will want to call requestLayout() yourself.
17562     * </p>
17563     * @hide
17564     */
17565    public void setOpticalInsets(Insets insets) {
17566        mLayoutInsets = insets;
17567    }
17568
17569    /**
17570     * Changes the selection state of this view. A view can be selected or not.
17571     * Note that selection is not the same as focus. Views are typically
17572     * selected in the context of an AdapterView like ListView or GridView;
17573     * the selected view is the view that is highlighted.
17574     *
17575     * @param selected true if the view must be selected, false otherwise
17576     */
17577    public void setSelected(boolean selected) {
17578        //noinspection DoubleNegation
17579        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
17580            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
17581            if (!selected) resetPressedState();
17582            invalidate(true);
17583            refreshDrawableState();
17584            dispatchSetSelected(selected);
17585            if (selected) {
17586                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
17587            } else {
17588                notifyViewAccessibilityStateChangedIfNeeded(
17589                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
17590            }
17591        }
17592    }
17593
17594    /**
17595     * Dispatch setSelected to all of this View's children.
17596     *
17597     * @see #setSelected(boolean)
17598     *
17599     * @param selected The new selected state
17600     */
17601    protected void dispatchSetSelected(boolean selected) {
17602    }
17603
17604    /**
17605     * Indicates the selection state of this view.
17606     *
17607     * @return true if the view is selected, false otherwise
17608     */
17609    @ViewDebug.ExportedProperty
17610    public boolean isSelected() {
17611        return (mPrivateFlags & PFLAG_SELECTED) != 0;
17612    }
17613
17614    /**
17615     * Changes the activated state of this view. A view can be activated or not.
17616     * Note that activation is not the same as selection.  Selection is
17617     * a transient property, representing the view (hierarchy) the user is
17618     * currently interacting with.  Activation is a longer-term state that the
17619     * user can move views in and out of.  For example, in a list view with
17620     * single or multiple selection enabled, the views in the current selection
17621     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
17622     * here.)  The activated state is propagated down to children of the view it
17623     * is set on.
17624     *
17625     * @param activated true if the view must be activated, false otherwise
17626     */
17627    public void setActivated(boolean activated) {
17628        //noinspection DoubleNegation
17629        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
17630            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
17631            invalidate(true);
17632            refreshDrawableState();
17633            dispatchSetActivated(activated);
17634        }
17635    }
17636
17637    /**
17638     * Dispatch setActivated to all of this View's children.
17639     *
17640     * @see #setActivated(boolean)
17641     *
17642     * @param activated The new activated state
17643     */
17644    protected void dispatchSetActivated(boolean activated) {
17645    }
17646
17647    /**
17648     * Indicates the activation state of this view.
17649     *
17650     * @return true if the view is activated, false otherwise
17651     */
17652    @ViewDebug.ExportedProperty
17653    public boolean isActivated() {
17654        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
17655    }
17656
17657    /**
17658     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
17659     * observer can be used to get notifications when global events, like
17660     * layout, happen.
17661     *
17662     * The returned ViewTreeObserver observer is not guaranteed to remain
17663     * valid for the lifetime of this View. If the caller of this method keeps
17664     * a long-lived reference to ViewTreeObserver, it should always check for
17665     * the return value of {@link ViewTreeObserver#isAlive()}.
17666     *
17667     * @return The ViewTreeObserver for this view's hierarchy.
17668     */
17669    public ViewTreeObserver getViewTreeObserver() {
17670        if (mAttachInfo != null) {
17671            return mAttachInfo.mTreeObserver;
17672        }
17673        if (mFloatingTreeObserver == null) {
17674            mFloatingTreeObserver = new ViewTreeObserver();
17675        }
17676        return mFloatingTreeObserver;
17677    }
17678
17679    /**
17680     * <p>Finds the topmost view in the current view hierarchy.</p>
17681     *
17682     * @return the topmost view containing this view
17683     */
17684    public View getRootView() {
17685        if (mAttachInfo != null) {
17686            final View v = mAttachInfo.mRootView;
17687            if (v != null) {
17688                return v;
17689            }
17690        }
17691
17692        View parent = this;
17693
17694        while (parent.mParent != null && parent.mParent instanceof View) {
17695            parent = (View) parent.mParent;
17696        }
17697
17698        return parent;
17699    }
17700
17701    /**
17702     * Transforms a motion event from view-local coordinates to on-screen
17703     * coordinates.
17704     *
17705     * @param ev the view-local motion event
17706     * @return false if the transformation could not be applied
17707     * @hide
17708     */
17709    public boolean toGlobalMotionEvent(MotionEvent ev) {
17710        final AttachInfo info = mAttachInfo;
17711        if (info == null) {
17712            return false;
17713        }
17714
17715        final Matrix m = info.mTmpMatrix;
17716        m.set(Matrix.IDENTITY_MATRIX);
17717        transformMatrixToGlobal(m);
17718        ev.transform(m);
17719        return true;
17720    }
17721
17722    /**
17723     * Transforms a motion event from on-screen coordinates to view-local
17724     * coordinates.
17725     *
17726     * @param ev the on-screen motion event
17727     * @return false if the transformation could not be applied
17728     * @hide
17729     */
17730    public boolean toLocalMotionEvent(MotionEvent ev) {
17731        final AttachInfo info = mAttachInfo;
17732        if (info == null) {
17733            return false;
17734        }
17735
17736        final Matrix m = info.mTmpMatrix;
17737        m.set(Matrix.IDENTITY_MATRIX);
17738        transformMatrixToLocal(m);
17739        ev.transform(m);
17740        return true;
17741    }
17742
17743    /**
17744     * Modifies the input matrix such that it maps view-local coordinates to
17745     * on-screen coordinates.
17746     *
17747     * @param m input matrix to modify
17748     * @hide
17749     */
17750    public void transformMatrixToGlobal(Matrix m) {
17751        final ViewParent parent = mParent;
17752        if (parent instanceof View) {
17753            final View vp = (View) parent;
17754            vp.transformMatrixToGlobal(m);
17755            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
17756        } else if (parent instanceof ViewRootImpl) {
17757            final ViewRootImpl vr = (ViewRootImpl) parent;
17758            vr.transformMatrixToGlobal(m);
17759            m.preTranslate(0, -vr.mCurScrollY);
17760        }
17761
17762        m.preTranslate(mLeft, mTop);
17763
17764        if (!hasIdentityMatrix()) {
17765            m.preConcat(getMatrix());
17766        }
17767    }
17768
17769    /**
17770     * Modifies the input matrix such that it maps on-screen coordinates to
17771     * view-local coordinates.
17772     *
17773     * @param m input matrix to modify
17774     * @hide
17775     */
17776    public void transformMatrixToLocal(Matrix m) {
17777        final ViewParent parent = mParent;
17778        if (parent instanceof View) {
17779            final View vp = (View) parent;
17780            vp.transformMatrixToLocal(m);
17781            m.postTranslate(vp.mScrollX, vp.mScrollY);
17782        } else if (parent instanceof ViewRootImpl) {
17783            final ViewRootImpl vr = (ViewRootImpl) parent;
17784            vr.transformMatrixToLocal(m);
17785            m.postTranslate(0, vr.mCurScrollY);
17786        }
17787
17788        m.postTranslate(-mLeft, -mTop);
17789
17790        if (!hasIdentityMatrix()) {
17791            m.postConcat(getInverseMatrix());
17792        }
17793    }
17794
17795    /**
17796     * @hide
17797     */
17798    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
17799            @ViewDebug.IntToString(from = 0, to = "x"),
17800            @ViewDebug.IntToString(from = 1, to = "y")
17801    })
17802    public int[] getLocationOnScreen() {
17803        int[] location = new int[2];
17804        getLocationOnScreen(location);
17805        return location;
17806    }
17807
17808    /**
17809     * <p>Computes the coordinates of this view on the screen. The argument
17810     * must be an array of two integers. After the method returns, the array
17811     * contains the x and y location in that order.</p>
17812     *
17813     * @param location an array of two integers in which to hold the coordinates
17814     */
17815    public void getLocationOnScreen(@Size(2) int[] location) {
17816        getLocationInWindow(location);
17817
17818        final AttachInfo info = mAttachInfo;
17819        if (info != null) {
17820            location[0] += info.mWindowLeft;
17821            location[1] += info.mWindowTop;
17822        }
17823    }
17824
17825    /**
17826     * <p>Computes the coordinates of this view in its window. The argument
17827     * must be an array of two integers. After the method returns, the array
17828     * contains the x and y location in that order.</p>
17829     *
17830     * @param location an array of two integers in which to hold the coordinates
17831     */
17832    public void getLocationInWindow(@Size(2) int[] location) {
17833        if (location == null || location.length < 2) {
17834            throw new IllegalArgumentException("location must be an array of two integers");
17835        }
17836
17837        if (mAttachInfo == null) {
17838            // When the view is not attached to a window, this method does not make sense
17839            location[0] = location[1] = 0;
17840            return;
17841        }
17842
17843        float[] position = mAttachInfo.mTmpTransformLocation;
17844        position[0] = position[1] = 0.0f;
17845
17846        if (!hasIdentityMatrix()) {
17847            getMatrix().mapPoints(position);
17848        }
17849
17850        position[0] += mLeft;
17851        position[1] += mTop;
17852
17853        ViewParent viewParent = mParent;
17854        while (viewParent instanceof View) {
17855            final View view = (View) viewParent;
17856
17857            position[0] -= view.mScrollX;
17858            position[1] -= view.mScrollY;
17859
17860            if (!view.hasIdentityMatrix()) {
17861                view.getMatrix().mapPoints(position);
17862            }
17863
17864            position[0] += view.mLeft;
17865            position[1] += view.mTop;
17866
17867            viewParent = view.mParent;
17868         }
17869
17870        if (viewParent instanceof ViewRootImpl) {
17871            // *cough*
17872            final ViewRootImpl vr = (ViewRootImpl) viewParent;
17873            position[1] -= vr.mCurScrollY;
17874        }
17875
17876        location[0] = (int) (position[0] + 0.5f);
17877        location[1] = (int) (position[1] + 0.5f);
17878    }
17879
17880    /**
17881     * {@hide}
17882     * @param id the id of the view to be found
17883     * @return the view of the specified id, null if cannot be found
17884     */
17885    protected View findViewTraversal(@IdRes int id) {
17886        if (id == mID) {
17887            return this;
17888        }
17889        return null;
17890    }
17891
17892    /**
17893     * {@hide}
17894     * @param tag the tag of the view to be found
17895     * @return the view of specified tag, null if cannot be found
17896     */
17897    protected View findViewWithTagTraversal(Object tag) {
17898        if (tag != null && tag.equals(mTag)) {
17899            return this;
17900        }
17901        return null;
17902    }
17903
17904    /**
17905     * {@hide}
17906     * @param predicate The predicate to evaluate.
17907     * @param childToSkip If not null, ignores this child during the recursive traversal.
17908     * @return The first view that matches the predicate or null.
17909     */
17910    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
17911        if (predicate.apply(this)) {
17912            return this;
17913        }
17914        return null;
17915    }
17916
17917    /**
17918     * Look for a child view with the given id.  If this view has the given
17919     * id, return this view.
17920     *
17921     * @param id The id to search for.
17922     * @return The view that has the given id in the hierarchy or null
17923     */
17924    @Nullable
17925    public final View findViewById(@IdRes int id) {
17926        if (id < 0) {
17927            return null;
17928        }
17929        return findViewTraversal(id);
17930    }
17931
17932    /**
17933     * Finds a view by its unuque and stable accessibility id.
17934     *
17935     * @param accessibilityId The searched accessibility id.
17936     * @return The found view.
17937     */
17938    final View findViewByAccessibilityId(int accessibilityId) {
17939        if (accessibilityId < 0) {
17940            return null;
17941        }
17942        return findViewByAccessibilityIdTraversal(accessibilityId);
17943    }
17944
17945    /**
17946     * Performs the traversal to find a view by its unuque and stable accessibility id.
17947     *
17948     * <strong>Note:</strong>This method does not stop at the root namespace
17949     * boundary since the user can touch the screen at an arbitrary location
17950     * potentially crossing the root namespace bounday which will send an
17951     * accessibility event to accessibility services and they should be able
17952     * to obtain the event source. Also accessibility ids are guaranteed to be
17953     * unique in the window.
17954     *
17955     * @param accessibilityId The accessibility id.
17956     * @return The found view.
17957     *
17958     * @hide
17959     */
17960    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
17961        if (getAccessibilityViewId() == accessibilityId) {
17962            return this;
17963        }
17964        return null;
17965    }
17966
17967    /**
17968     * Look for a child view with the given tag.  If this view has the given
17969     * tag, return this view.
17970     *
17971     * @param tag The tag to search for, using "tag.equals(getTag())".
17972     * @return The View that has the given tag in the hierarchy or null
17973     */
17974    public final View findViewWithTag(Object tag) {
17975        if (tag == null) {
17976            return null;
17977        }
17978        return findViewWithTagTraversal(tag);
17979    }
17980
17981    /**
17982     * {@hide}
17983     * Look for a child view that matches the specified predicate.
17984     * If this view matches the predicate, return this view.
17985     *
17986     * @param predicate The predicate to evaluate.
17987     * @return The first view that matches the predicate or null.
17988     */
17989    public final View findViewByPredicate(Predicate<View> predicate) {
17990        return findViewByPredicateTraversal(predicate, null);
17991    }
17992
17993    /**
17994     * {@hide}
17995     * Look for a child view that matches the specified predicate,
17996     * starting with the specified view and its descendents and then
17997     * recusively searching the ancestors and siblings of that view
17998     * until this view is reached.
17999     *
18000     * This method is useful in cases where the predicate does not match
18001     * a single unique view (perhaps multiple views use the same id)
18002     * and we are trying to find the view that is "closest" in scope to the
18003     * starting view.
18004     *
18005     * @param start The view to start from.
18006     * @param predicate The predicate to evaluate.
18007     * @return The first view that matches the predicate or null.
18008     */
18009    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
18010        View childToSkip = null;
18011        for (;;) {
18012            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
18013            if (view != null || start == this) {
18014                return view;
18015            }
18016
18017            ViewParent parent = start.getParent();
18018            if (parent == null || !(parent instanceof View)) {
18019                return null;
18020            }
18021
18022            childToSkip = start;
18023            start = (View) parent;
18024        }
18025    }
18026
18027    /**
18028     * Sets the identifier for this view. The identifier does not have to be
18029     * unique in this view's hierarchy. The identifier should be a positive
18030     * number.
18031     *
18032     * @see #NO_ID
18033     * @see #getId()
18034     * @see #findViewById(int)
18035     *
18036     * @param id a number used to identify the view
18037     *
18038     * @attr ref android.R.styleable#View_id
18039     */
18040    public void setId(@IdRes int id) {
18041        mID = id;
18042        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
18043            mID = generateViewId();
18044        }
18045    }
18046
18047    /**
18048     * {@hide}
18049     *
18050     * @param isRoot true if the view belongs to the root namespace, false
18051     *        otherwise
18052     */
18053    public void setIsRootNamespace(boolean isRoot) {
18054        if (isRoot) {
18055            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
18056        } else {
18057            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
18058        }
18059    }
18060
18061    /**
18062     * {@hide}
18063     *
18064     * @return true if the view belongs to the root namespace, false otherwise
18065     */
18066    public boolean isRootNamespace() {
18067        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
18068    }
18069
18070    /**
18071     * Returns this view's identifier.
18072     *
18073     * @return a positive integer used to identify the view or {@link #NO_ID}
18074     *         if the view has no ID
18075     *
18076     * @see #setId(int)
18077     * @see #findViewById(int)
18078     * @attr ref android.R.styleable#View_id
18079     */
18080    @IdRes
18081    @ViewDebug.CapturedViewProperty
18082    public int getId() {
18083        return mID;
18084    }
18085
18086    /**
18087     * Returns this view's tag.
18088     *
18089     * @return the Object stored in this view as a tag, or {@code null} if not
18090     *         set
18091     *
18092     * @see #setTag(Object)
18093     * @see #getTag(int)
18094     */
18095    @ViewDebug.ExportedProperty
18096    public Object getTag() {
18097        return mTag;
18098    }
18099
18100    /**
18101     * Sets the tag associated with this view. A tag can be used to mark
18102     * a view in its hierarchy and does not have to be unique within the
18103     * hierarchy. Tags can also be used to store data within a view without
18104     * resorting to another data structure.
18105     *
18106     * @param tag an Object to tag the view with
18107     *
18108     * @see #getTag()
18109     * @see #setTag(int, Object)
18110     */
18111    public void setTag(final Object tag) {
18112        mTag = tag;
18113    }
18114
18115    /**
18116     * Returns the tag associated with this view and the specified key.
18117     *
18118     * @param key The key identifying the tag
18119     *
18120     * @return the Object stored in this view as a tag, or {@code null} if not
18121     *         set
18122     *
18123     * @see #setTag(int, Object)
18124     * @see #getTag()
18125     */
18126    public Object getTag(int key) {
18127        if (mKeyedTags != null) return mKeyedTags.get(key);
18128        return null;
18129    }
18130
18131    /**
18132     * Sets a tag associated with this view and a key. A tag can be used
18133     * to mark a view in its hierarchy and does not have to be unique within
18134     * the hierarchy. Tags can also be used to store data within a view
18135     * without resorting to another data structure.
18136     *
18137     * The specified key should be an id declared in the resources of the
18138     * application to ensure it is unique (see the <a
18139     * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
18140     * Keys identified as belonging to
18141     * the Android framework or not associated with any package will cause
18142     * an {@link IllegalArgumentException} to be thrown.
18143     *
18144     * @param key The key identifying the tag
18145     * @param tag An Object to tag the view with
18146     *
18147     * @throws IllegalArgumentException If they specified key is not valid
18148     *
18149     * @see #setTag(Object)
18150     * @see #getTag(int)
18151     */
18152    public void setTag(int key, final Object tag) {
18153        // If the package id is 0x00 or 0x01, it's either an undefined package
18154        // or a framework id
18155        if ((key >>> 24) < 2) {
18156            throw new IllegalArgumentException("The key must be an application-specific "
18157                    + "resource id.");
18158        }
18159
18160        setKeyedTag(key, tag);
18161    }
18162
18163    /**
18164     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
18165     * framework id.
18166     *
18167     * @hide
18168     */
18169    public void setTagInternal(int key, Object tag) {
18170        if ((key >>> 24) != 0x1) {
18171            throw new IllegalArgumentException("The key must be a framework-specific "
18172                    + "resource id.");
18173        }
18174
18175        setKeyedTag(key, tag);
18176    }
18177
18178    private void setKeyedTag(int key, Object tag) {
18179        if (mKeyedTags == null) {
18180            mKeyedTags = new SparseArray<Object>(2);
18181        }
18182
18183        mKeyedTags.put(key, tag);
18184    }
18185
18186    /**
18187     * Prints information about this view in the log output, with the tag
18188     * {@link #VIEW_LOG_TAG}.
18189     *
18190     * @hide
18191     */
18192    public void debug() {
18193        debug(0);
18194    }
18195
18196    /**
18197     * Prints information about this view in the log output, with the tag
18198     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
18199     * indentation defined by the <code>depth</code>.
18200     *
18201     * @param depth the indentation level
18202     *
18203     * @hide
18204     */
18205    protected void debug(int depth) {
18206        String output = debugIndent(depth - 1);
18207
18208        output += "+ " + this;
18209        int id = getId();
18210        if (id != -1) {
18211            output += " (id=" + id + ")";
18212        }
18213        Object tag = getTag();
18214        if (tag != null) {
18215            output += " (tag=" + tag + ")";
18216        }
18217        Log.d(VIEW_LOG_TAG, output);
18218
18219        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
18220            output = debugIndent(depth) + " FOCUSED";
18221            Log.d(VIEW_LOG_TAG, output);
18222        }
18223
18224        output = debugIndent(depth);
18225        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
18226                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
18227                + "} ";
18228        Log.d(VIEW_LOG_TAG, output);
18229
18230        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
18231                || mPaddingBottom != 0) {
18232            output = debugIndent(depth);
18233            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
18234                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
18235            Log.d(VIEW_LOG_TAG, output);
18236        }
18237
18238        output = debugIndent(depth);
18239        output += "mMeasureWidth=" + mMeasuredWidth +
18240                " mMeasureHeight=" + mMeasuredHeight;
18241        Log.d(VIEW_LOG_TAG, output);
18242
18243        output = debugIndent(depth);
18244        if (mLayoutParams == null) {
18245            output += "BAD! no layout params";
18246        } else {
18247            output = mLayoutParams.debug(output);
18248        }
18249        Log.d(VIEW_LOG_TAG, output);
18250
18251        output = debugIndent(depth);
18252        output += "flags={";
18253        output += View.printFlags(mViewFlags);
18254        output += "}";
18255        Log.d(VIEW_LOG_TAG, output);
18256
18257        output = debugIndent(depth);
18258        output += "privateFlags={";
18259        output += View.printPrivateFlags(mPrivateFlags);
18260        output += "}";
18261        Log.d(VIEW_LOG_TAG, output);
18262    }
18263
18264    /**
18265     * Creates a string of whitespaces used for indentation.
18266     *
18267     * @param depth the indentation level
18268     * @return a String containing (depth * 2 + 3) * 2 white spaces
18269     *
18270     * @hide
18271     */
18272    protected static String debugIndent(int depth) {
18273        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
18274        for (int i = 0; i < (depth * 2) + 3; i++) {
18275            spaces.append(' ').append(' ');
18276        }
18277        return spaces.toString();
18278    }
18279
18280    /**
18281     * <p>Return the offset of the widget's text baseline from the widget's top
18282     * boundary. If this widget does not support baseline alignment, this
18283     * method returns -1. </p>
18284     *
18285     * @return the offset of the baseline within the widget's bounds or -1
18286     *         if baseline alignment is not supported
18287     */
18288    @ViewDebug.ExportedProperty(category = "layout")
18289    public int getBaseline() {
18290        return -1;
18291    }
18292
18293    /**
18294     * Returns whether the view hierarchy is currently undergoing a layout pass. This
18295     * information is useful to avoid situations such as calling {@link #requestLayout()} during
18296     * a layout pass.
18297     *
18298     * @return whether the view hierarchy is currently undergoing a layout pass
18299     */
18300    public boolean isInLayout() {
18301        ViewRootImpl viewRoot = getViewRootImpl();
18302        return (viewRoot != null && viewRoot.isInLayout());
18303    }
18304
18305    /**
18306     * Call this when something has changed which has invalidated the
18307     * layout of this view. This will schedule a layout pass of the view
18308     * tree. This should not be called while the view hierarchy is currently in a layout
18309     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
18310     * end of the current layout pass (and then layout will run again) or after the current
18311     * frame is drawn and the next layout occurs.
18312     *
18313     * <p>Subclasses which override this method should call the superclass method to
18314     * handle possible request-during-layout errors correctly.</p>
18315     */
18316    @CallSuper
18317    public void requestLayout() {
18318        if (mMeasureCache != null) mMeasureCache.clear();
18319
18320        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
18321            // Only trigger request-during-layout logic if this is the view requesting it,
18322            // not the views in its parent hierarchy
18323            ViewRootImpl viewRoot = getViewRootImpl();
18324            if (viewRoot != null && viewRoot.isInLayout()) {
18325                if (!viewRoot.requestLayoutDuringLayout(this)) {
18326                    return;
18327                }
18328            }
18329            mAttachInfo.mViewRequestingLayout = this;
18330        }
18331
18332        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18333        mPrivateFlags |= PFLAG_INVALIDATED;
18334
18335        if (mParent != null && !mParent.isLayoutRequested()) {
18336            mParent.requestLayout();
18337        }
18338        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
18339            mAttachInfo.mViewRequestingLayout = null;
18340        }
18341    }
18342
18343    /**
18344     * Forces this view to be laid out during the next layout pass.
18345     * This method does not call requestLayout() or forceLayout()
18346     * on the parent.
18347     */
18348    public void forceLayout() {
18349        if (mMeasureCache != null) mMeasureCache.clear();
18350
18351        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
18352        mPrivateFlags |= PFLAG_INVALIDATED;
18353    }
18354
18355    /**
18356     * <p>
18357     * This is called to find out how big a view should be. The parent
18358     * supplies constraint information in the width and height parameters.
18359     * </p>
18360     *
18361     * <p>
18362     * The actual measurement work of a view is performed in
18363     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
18364     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
18365     * </p>
18366     *
18367     *
18368     * @param widthMeasureSpec Horizontal space requirements as imposed by the
18369     *        parent
18370     * @param heightMeasureSpec Vertical space requirements as imposed by the
18371     *        parent
18372     *
18373     * @see #onMeasure(int, int)
18374     */
18375    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
18376        boolean optical = isLayoutModeOptical(this);
18377        if (optical != isLayoutModeOptical(mParent)) {
18378            Insets insets = getOpticalInsets();
18379            int oWidth  = insets.left + insets.right;
18380            int oHeight = insets.top  + insets.bottom;
18381            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
18382            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
18383        }
18384
18385        // Suppress sign extension for the low bytes
18386        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
18387        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
18388
18389        final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
18390        final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
18391                MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
18392        final boolean matchingSize = isExactly &&
18393                getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
18394                getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
18395        if (forceLayout || !matchingSize &&
18396                (widthMeasureSpec != mOldWidthMeasureSpec ||
18397                        heightMeasureSpec != mOldHeightMeasureSpec)) {
18398
18399            // first clears the measured dimension flag
18400            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
18401
18402            resolveRtlPropertiesIfNeeded();
18403
18404            int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
18405            if (cacheIndex < 0 || sIgnoreMeasureCache) {
18406                // measure ourselves, this should set the measured dimension flag back
18407                onMeasure(widthMeasureSpec, heightMeasureSpec);
18408                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18409            } else {
18410                long value = mMeasureCache.valueAt(cacheIndex);
18411                // Casting a long to int drops the high 32 bits, no mask needed
18412                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
18413                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
18414            }
18415
18416            // flag not set, setMeasuredDimension() was not invoked, we raise
18417            // an exception to warn the developer
18418            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
18419                throw new IllegalStateException("View with id " + getId() + ": "
18420                        + getClass().getName() + "#onMeasure() did not set the"
18421                        + " measured dimension by calling"
18422                        + " setMeasuredDimension()");
18423            }
18424
18425            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
18426        }
18427
18428        mOldWidthMeasureSpec = widthMeasureSpec;
18429        mOldHeightMeasureSpec = heightMeasureSpec;
18430
18431        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
18432                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
18433    }
18434
18435    /**
18436     * <p>
18437     * Measure the view and its content to determine the measured width and the
18438     * measured height. This method is invoked by {@link #measure(int, int)} and
18439     * should be overridden by subclasses to provide accurate and efficient
18440     * measurement of their contents.
18441     * </p>
18442     *
18443     * <p>
18444     * <strong>CONTRACT:</strong> When overriding this method, you
18445     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
18446     * measured width and height of this view. Failure to do so will trigger an
18447     * <code>IllegalStateException</code>, thrown by
18448     * {@link #measure(int, int)}. Calling the superclass'
18449     * {@link #onMeasure(int, int)} is a valid use.
18450     * </p>
18451     *
18452     * <p>
18453     * The base class implementation of measure defaults to the background size,
18454     * unless a larger size is allowed by the MeasureSpec. Subclasses should
18455     * override {@link #onMeasure(int, int)} to provide better measurements of
18456     * their content.
18457     * </p>
18458     *
18459     * <p>
18460     * If this method is overridden, it is the subclass's responsibility to make
18461     * sure the measured height and width are at least the view's minimum height
18462     * and width ({@link #getSuggestedMinimumHeight()} and
18463     * {@link #getSuggestedMinimumWidth()}).
18464     * </p>
18465     *
18466     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
18467     *                         The requirements are encoded with
18468     *                         {@link android.view.View.MeasureSpec}.
18469     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
18470     *                         The requirements are encoded with
18471     *                         {@link android.view.View.MeasureSpec}.
18472     *
18473     * @see #getMeasuredWidth()
18474     * @see #getMeasuredHeight()
18475     * @see #setMeasuredDimension(int, int)
18476     * @see #getSuggestedMinimumHeight()
18477     * @see #getSuggestedMinimumWidth()
18478     * @see android.view.View.MeasureSpec#getMode(int)
18479     * @see android.view.View.MeasureSpec#getSize(int)
18480     */
18481    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
18482        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
18483                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
18484    }
18485
18486    /**
18487     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
18488     * measured width and measured height. Failing to do so will trigger an
18489     * exception at measurement time.</p>
18490     *
18491     * @param measuredWidth The measured width of this view.  May be a complex
18492     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18493     * {@link #MEASURED_STATE_TOO_SMALL}.
18494     * @param measuredHeight The measured height of this view.  May be a complex
18495     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18496     * {@link #MEASURED_STATE_TOO_SMALL}.
18497     */
18498    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
18499        boolean optical = isLayoutModeOptical(this);
18500        if (optical != isLayoutModeOptical(mParent)) {
18501            Insets insets = getOpticalInsets();
18502            int opticalWidth  = insets.left + insets.right;
18503            int opticalHeight = insets.top  + insets.bottom;
18504
18505            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
18506            measuredHeight += optical ? opticalHeight : -opticalHeight;
18507        }
18508        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
18509    }
18510
18511    /**
18512     * Sets the measured dimension without extra processing for things like optical bounds.
18513     * Useful for reapplying consistent values that have already been cooked with adjustments
18514     * for optical bounds, etc. such as those from the measurement cache.
18515     *
18516     * @param measuredWidth The measured width of this view.  May be a complex
18517     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18518     * {@link #MEASURED_STATE_TOO_SMALL}.
18519     * @param measuredHeight The measured height of this view.  May be a complex
18520     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
18521     * {@link #MEASURED_STATE_TOO_SMALL}.
18522     */
18523    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
18524        mMeasuredWidth = measuredWidth;
18525        mMeasuredHeight = measuredHeight;
18526
18527        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
18528    }
18529
18530    /**
18531     * Merge two states as returned by {@link #getMeasuredState()}.
18532     * @param curState The current state as returned from a view or the result
18533     * of combining multiple views.
18534     * @param newState The new view state to combine.
18535     * @return Returns a new integer reflecting the combination of the two
18536     * states.
18537     */
18538    public static int combineMeasuredStates(int curState, int newState) {
18539        return curState | newState;
18540    }
18541
18542    /**
18543     * Version of {@link #resolveSizeAndState(int, int, int)}
18544     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
18545     */
18546    public static int resolveSize(int size, int measureSpec) {
18547        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
18548    }
18549
18550    /**
18551     * Utility to reconcile a desired size and state, with constraints imposed
18552     * by a MeasureSpec. Will take the desired size, unless a different size
18553     * is imposed by the constraints. The returned value is a compound integer,
18554     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
18555     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
18556     * resulting size is smaller than the size the view wants to be.
18557     *
18558     * @param size How big the view wants to be.
18559     * @param measureSpec Constraints imposed by the parent.
18560     * @param childMeasuredState Size information bit mask for the view's
18561     *                           children.
18562     * @return Size information bit mask as defined by
18563     *         {@link #MEASURED_SIZE_MASK} and
18564     *         {@link #MEASURED_STATE_TOO_SMALL}.
18565     */
18566    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
18567        final int specMode = MeasureSpec.getMode(measureSpec);
18568        final int specSize = MeasureSpec.getSize(measureSpec);
18569        final int result;
18570        switch (specMode) {
18571            case MeasureSpec.AT_MOST:
18572                if (specSize < size) {
18573                    result = specSize | MEASURED_STATE_TOO_SMALL;
18574                } else {
18575                    result = size;
18576                }
18577                break;
18578            case MeasureSpec.EXACTLY:
18579                result = specSize;
18580                break;
18581            case MeasureSpec.UNSPECIFIED:
18582            default:
18583                result = size;
18584        }
18585        return result | (childMeasuredState & MEASURED_STATE_MASK);
18586    }
18587
18588    /**
18589     * Utility to return a default size. Uses the supplied size if the
18590     * MeasureSpec imposed no constraints. Will get larger if allowed
18591     * by the MeasureSpec.
18592     *
18593     * @param size Default size for this view
18594     * @param measureSpec Constraints imposed by the parent
18595     * @return The size this view should be.
18596     */
18597    public static int getDefaultSize(int size, int measureSpec) {
18598        int result = size;
18599        int specMode = MeasureSpec.getMode(measureSpec);
18600        int specSize = MeasureSpec.getSize(measureSpec);
18601
18602        switch (specMode) {
18603        case MeasureSpec.UNSPECIFIED:
18604            result = size;
18605            break;
18606        case MeasureSpec.AT_MOST:
18607        case MeasureSpec.EXACTLY:
18608            result = specSize;
18609            break;
18610        }
18611        return result;
18612    }
18613
18614    /**
18615     * Returns the suggested minimum height that the view should use. This
18616     * returns the maximum of the view's minimum height
18617     * and the background's minimum height
18618     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
18619     * <p>
18620     * When being used in {@link #onMeasure(int, int)}, the caller should still
18621     * ensure the returned height is within the requirements of the parent.
18622     *
18623     * @return The suggested minimum height of the view.
18624     */
18625    protected int getSuggestedMinimumHeight() {
18626        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
18627
18628    }
18629
18630    /**
18631     * Returns the suggested minimum width that the view should use. This
18632     * returns the maximum of the view's minimum width)
18633     * and the background's minimum width
18634     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
18635     * <p>
18636     * When being used in {@link #onMeasure(int, int)}, the caller should still
18637     * ensure the returned width is within the requirements of the parent.
18638     *
18639     * @return The suggested minimum width of the view.
18640     */
18641    protected int getSuggestedMinimumWidth() {
18642        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
18643    }
18644
18645    /**
18646     * Returns the minimum height of the view.
18647     *
18648     * @return the minimum height the view will try to be.
18649     *
18650     * @see #setMinimumHeight(int)
18651     *
18652     * @attr ref android.R.styleable#View_minHeight
18653     */
18654    public int getMinimumHeight() {
18655        return mMinHeight;
18656    }
18657
18658    /**
18659     * Sets the minimum height of the view. It is not guaranteed the view will
18660     * be able to achieve this minimum height (for example, if its parent layout
18661     * constrains it with less available height).
18662     *
18663     * @param minHeight The minimum height the view will try to be.
18664     *
18665     * @see #getMinimumHeight()
18666     *
18667     * @attr ref android.R.styleable#View_minHeight
18668     */
18669    public void setMinimumHeight(int minHeight) {
18670        mMinHeight = minHeight;
18671        requestLayout();
18672    }
18673
18674    /**
18675     * Returns the minimum width of the view.
18676     *
18677     * @return the minimum width the view will try to be.
18678     *
18679     * @see #setMinimumWidth(int)
18680     *
18681     * @attr ref android.R.styleable#View_minWidth
18682     */
18683    public int getMinimumWidth() {
18684        return mMinWidth;
18685    }
18686
18687    /**
18688     * Sets the minimum width of the view. It is not guaranteed the view will
18689     * be able to achieve this minimum width (for example, if its parent layout
18690     * constrains it with less available width).
18691     *
18692     * @param minWidth The minimum width the view will try to be.
18693     *
18694     * @see #getMinimumWidth()
18695     *
18696     * @attr ref android.R.styleable#View_minWidth
18697     */
18698    public void setMinimumWidth(int minWidth) {
18699        mMinWidth = minWidth;
18700        requestLayout();
18701
18702    }
18703
18704    /**
18705     * Get the animation currently associated with this view.
18706     *
18707     * @return The animation that is currently playing or
18708     *         scheduled to play for this view.
18709     */
18710    public Animation getAnimation() {
18711        return mCurrentAnimation;
18712    }
18713
18714    /**
18715     * Start the specified animation now.
18716     *
18717     * @param animation the animation to start now
18718     */
18719    public void startAnimation(Animation animation) {
18720        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
18721        setAnimation(animation);
18722        invalidateParentCaches();
18723        invalidate(true);
18724    }
18725
18726    /**
18727     * Cancels any animations for this view.
18728     */
18729    public void clearAnimation() {
18730        if (mCurrentAnimation != null) {
18731            mCurrentAnimation.detach();
18732        }
18733        mCurrentAnimation = null;
18734        invalidateParentIfNeeded();
18735    }
18736
18737    /**
18738     * Sets the next animation to play for this view.
18739     * If you want the animation to play immediately, use
18740     * {@link #startAnimation(android.view.animation.Animation)} instead.
18741     * This method provides allows fine-grained
18742     * control over the start time and invalidation, but you
18743     * must make sure that 1) the animation has a start time set, and
18744     * 2) the view's parent (which controls animations on its children)
18745     * will be invalidated when the animation is supposed to
18746     * start.
18747     *
18748     * @param animation The next animation, or null.
18749     */
18750    public void setAnimation(Animation animation) {
18751        mCurrentAnimation = animation;
18752
18753        if (animation != null) {
18754            // If the screen is off assume the animation start time is now instead of
18755            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
18756            // would cause the animation to start when the screen turns back on
18757            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
18758                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
18759                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
18760            }
18761            animation.reset();
18762        }
18763    }
18764
18765    /**
18766     * Invoked by a parent ViewGroup to notify the start of the animation
18767     * currently associated with this view. If you override this method,
18768     * always call super.onAnimationStart();
18769     *
18770     * @see #setAnimation(android.view.animation.Animation)
18771     * @see #getAnimation()
18772     */
18773    @CallSuper
18774    protected void onAnimationStart() {
18775        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
18776    }
18777
18778    /**
18779     * Invoked by a parent ViewGroup to notify the end of the animation
18780     * currently associated with this view. If you override this method,
18781     * always call super.onAnimationEnd();
18782     *
18783     * @see #setAnimation(android.view.animation.Animation)
18784     * @see #getAnimation()
18785     */
18786    @CallSuper
18787    protected void onAnimationEnd() {
18788        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
18789    }
18790
18791    /**
18792     * Invoked if there is a Transform that involves alpha. Subclass that can
18793     * draw themselves with the specified alpha should return true, and then
18794     * respect that alpha when their onDraw() is called. If this returns false
18795     * then the view may be redirected to draw into an offscreen buffer to
18796     * fulfill the request, which will look fine, but may be slower than if the
18797     * subclass handles it internally. The default implementation returns false.
18798     *
18799     * @param alpha The alpha (0..255) to apply to the view's drawing
18800     * @return true if the view can draw with the specified alpha.
18801     */
18802    protected boolean onSetAlpha(int alpha) {
18803        return false;
18804    }
18805
18806    /**
18807     * This is used by the RootView to perform an optimization when
18808     * the view hierarchy contains one or several SurfaceView.
18809     * SurfaceView is always considered transparent, but its children are not,
18810     * therefore all View objects remove themselves from the global transparent
18811     * region (passed as a parameter to this function).
18812     *
18813     * @param region The transparent region for this ViewAncestor (window).
18814     *
18815     * @return Returns true if the effective visibility of the view at this
18816     * point is opaque, regardless of the transparent region; returns false
18817     * if it is possible for underlying windows to be seen behind the view.
18818     *
18819     * {@hide}
18820     */
18821    public boolean gatherTransparentRegion(Region region) {
18822        final AttachInfo attachInfo = mAttachInfo;
18823        if (region != null && attachInfo != null) {
18824            final int pflags = mPrivateFlags;
18825            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
18826                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
18827                // remove it from the transparent region.
18828                final int[] location = attachInfo.mTransparentLocation;
18829                getLocationInWindow(location);
18830                region.op(location[0], location[1], location[0] + mRight - mLeft,
18831                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
18832            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
18833                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
18834                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
18835                // exists, so we remove the background drawable's non-transparent
18836                // parts from this transparent region.
18837                applyDrawableToTransparentRegion(mBackground, region);
18838            }
18839            final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null;
18840            if (foreground != null) {
18841                applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region);
18842            }
18843        }
18844        return true;
18845    }
18846
18847    /**
18848     * Play a sound effect for this view.
18849     *
18850     * <p>The framework will play sound effects for some built in actions, such as
18851     * clicking, but you may wish to play these effects in your widget,
18852     * for instance, for internal navigation.
18853     *
18854     * <p>The sound effect will only be played if sound effects are enabled by the user, and
18855     * {@link #isSoundEffectsEnabled()} is true.
18856     *
18857     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
18858     */
18859    public void playSoundEffect(int soundConstant) {
18860        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
18861            return;
18862        }
18863        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
18864    }
18865
18866    /**
18867     * BZZZTT!!1!
18868     *
18869     * <p>Provide haptic feedback to the user for this view.
18870     *
18871     * <p>The framework will provide haptic feedback for some built in actions,
18872     * such as long presses, but you may wish to provide feedback for your
18873     * own widget.
18874     *
18875     * <p>The feedback will only be performed if
18876     * {@link #isHapticFeedbackEnabled()} is true.
18877     *
18878     * @param feedbackConstant One of the constants defined in
18879     * {@link HapticFeedbackConstants}
18880     */
18881    public boolean performHapticFeedback(int feedbackConstant) {
18882        return performHapticFeedback(feedbackConstant, 0);
18883    }
18884
18885    /**
18886     * BZZZTT!!1!
18887     *
18888     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
18889     *
18890     * @param feedbackConstant One of the constants defined in
18891     * {@link HapticFeedbackConstants}
18892     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
18893     */
18894    public boolean performHapticFeedback(int feedbackConstant, int flags) {
18895        if (mAttachInfo == null) {
18896            return false;
18897        }
18898        //noinspection SimplifiableIfStatement
18899        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
18900                && !isHapticFeedbackEnabled()) {
18901            return false;
18902        }
18903        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
18904                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
18905    }
18906
18907    /**
18908     * Request that the visibility of the status bar or other screen/window
18909     * decorations be changed.
18910     *
18911     * <p>This method is used to put the over device UI into temporary modes
18912     * where the user's attention is focused more on the application content,
18913     * by dimming or hiding surrounding system affordances.  This is typically
18914     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
18915     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
18916     * to be placed behind the action bar (and with these flags other system
18917     * affordances) so that smooth transitions between hiding and showing them
18918     * can be done.
18919     *
18920     * <p>Two representative examples of the use of system UI visibility is
18921     * implementing a content browsing application (like a magazine reader)
18922     * and a video playing application.
18923     *
18924     * <p>The first code shows a typical implementation of a View in a content
18925     * browsing application.  In this implementation, the application goes
18926     * into a content-oriented mode by hiding the status bar and action bar,
18927     * and putting the navigation elements into lights out mode.  The user can
18928     * then interact with content while in this mode.  Such an application should
18929     * provide an easy way for the user to toggle out of the mode (such as to
18930     * check information in the status bar or access notifications).  In the
18931     * implementation here, this is done simply by tapping on the content.
18932     *
18933     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
18934     *      content}
18935     *
18936     * <p>This second code sample shows a typical implementation of a View
18937     * in a video playing application.  In this situation, while the video is
18938     * playing the application would like to go into a complete full-screen mode,
18939     * to use as much of the display as possible for the video.  When in this state
18940     * the user can not interact with the application; the system intercepts
18941     * touching on the screen to pop the UI out of full screen mode.  See
18942     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
18943     *
18944     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
18945     *      content}
18946     *
18947     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18948     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18949     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18950     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18951     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18952     */
18953    public void setSystemUiVisibility(int visibility) {
18954        if (visibility != mSystemUiVisibility) {
18955            mSystemUiVisibility = visibility;
18956            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
18957                mParent.recomputeViewAttributes(this);
18958            }
18959        }
18960    }
18961
18962    /**
18963     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
18964     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
18965     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
18966     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
18967     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
18968     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
18969     */
18970    public int getSystemUiVisibility() {
18971        return mSystemUiVisibility;
18972    }
18973
18974    /**
18975     * Returns the current system UI visibility that is currently set for
18976     * the entire window.  This is the combination of the
18977     * {@link #setSystemUiVisibility(int)} values supplied by all of the
18978     * views in the window.
18979     */
18980    public int getWindowSystemUiVisibility() {
18981        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
18982    }
18983
18984    /**
18985     * Override to find out when the window's requested system UI visibility
18986     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
18987     * This is different from the callbacks received through
18988     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
18989     * in that this is only telling you about the local request of the window,
18990     * not the actual values applied by the system.
18991     */
18992    public void onWindowSystemUiVisibilityChanged(int visible) {
18993    }
18994
18995    /**
18996     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
18997     * the view hierarchy.
18998     */
18999    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
19000        onWindowSystemUiVisibilityChanged(visible);
19001    }
19002
19003    /**
19004     * Set a listener to receive callbacks when the visibility of the system bar changes.
19005     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
19006     */
19007    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
19008        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
19009        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
19010            mParent.recomputeViewAttributes(this);
19011        }
19012    }
19013
19014    /**
19015     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
19016     * the view hierarchy.
19017     */
19018    public void dispatchSystemUiVisibilityChanged(int visibility) {
19019        ListenerInfo li = mListenerInfo;
19020        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
19021            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
19022                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
19023        }
19024    }
19025
19026    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
19027        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
19028        if (val != mSystemUiVisibility) {
19029            setSystemUiVisibility(val);
19030            return true;
19031        }
19032        return false;
19033    }
19034
19035    /** @hide */
19036    public void setDisabledSystemUiVisibility(int flags) {
19037        if (mAttachInfo != null) {
19038            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
19039                mAttachInfo.mDisabledSystemUiVisibility = flags;
19040                if (mParent != null) {
19041                    mParent.recomputeViewAttributes(this);
19042                }
19043            }
19044        }
19045    }
19046
19047    /**
19048     * Creates an image that the system displays during the drag and drop
19049     * operation. This is called a &quot;drag shadow&quot;. The default implementation
19050     * for a DragShadowBuilder based on a View returns an image that has exactly the same
19051     * appearance as the given View. The default also positions the center of the drag shadow
19052     * directly under the touch point. If no View is provided (the constructor with no parameters
19053     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
19054     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the
19055     * default is an invisible drag shadow.
19056     * <p>
19057     * You are not required to use the View you provide to the constructor as the basis of the
19058     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
19059     * anything you want as the drag shadow.
19060     * </p>
19061     * <p>
19062     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
19063     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
19064     *  size and position of the drag shadow. It uses this data to construct a
19065     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
19066     *  so that your application can draw the shadow image in the Canvas.
19067     * </p>
19068     *
19069     * <div class="special reference">
19070     * <h3>Developer Guides</h3>
19071     * <p>For a guide to implementing drag and drop features, read the
19072     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19073     * </div>
19074     */
19075    public static class DragShadowBuilder {
19076        private final WeakReference<View> mView;
19077
19078        /**
19079         * Constructs a shadow image builder based on a View. By default, the resulting drag
19080         * shadow will have the same appearance and dimensions as the View, with the touch point
19081         * over the center of the View.
19082         * @param view A View. Any View in scope can be used.
19083         */
19084        public DragShadowBuilder(View view) {
19085            mView = new WeakReference<View>(view);
19086        }
19087
19088        /**
19089         * Construct a shadow builder object with no associated View.  This
19090         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
19091         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
19092         * to supply the drag shadow's dimensions and appearance without
19093         * reference to any View object. If they are not overridden, then the result is an
19094         * invisible drag shadow.
19095         */
19096        public DragShadowBuilder() {
19097            mView = new WeakReference<View>(null);
19098        }
19099
19100        /**
19101         * Returns the View object that had been passed to the
19102         * {@link #View.DragShadowBuilder(View)}
19103         * constructor.  If that View parameter was {@code null} or if the
19104         * {@link #View.DragShadowBuilder()}
19105         * constructor was used to instantiate the builder object, this method will return
19106         * null.
19107         *
19108         * @return The View object associate with this builder object.
19109         */
19110        @SuppressWarnings({"JavadocReference"})
19111        final public View getView() {
19112            return mView.get();
19113        }
19114
19115        /**
19116         * Provides the metrics for the shadow image. These include the dimensions of
19117         * the shadow image, and the point within that shadow that should
19118         * be centered under the touch location while dragging.
19119         * <p>
19120         * The default implementation sets the dimensions of the shadow to be the
19121         * same as the dimensions of the View itself and centers the shadow under
19122         * the touch point.
19123         * </p>
19124         *
19125         * @param shadowSize A {@link android.graphics.Point} containing the width and height
19126         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
19127         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
19128         * image.
19129         *
19130         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
19131         * shadow image that should be underneath the touch point during the drag and drop
19132         * operation. Your application must set {@link android.graphics.Point#x} to the
19133         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
19134         */
19135        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
19136            final View view = mView.get();
19137            if (view != null) {
19138                shadowSize.set(view.getWidth(), view.getHeight());
19139                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
19140            } else {
19141                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
19142            }
19143        }
19144
19145        /**
19146         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
19147         * based on the dimensions it received from the
19148         * {@link #onProvideShadowMetrics(Point, Point)} callback.
19149         *
19150         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
19151         */
19152        public void onDrawShadow(Canvas canvas) {
19153            final View view = mView.get();
19154            if (view != null) {
19155                view.draw(canvas);
19156            } else {
19157                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
19158            }
19159        }
19160    }
19161
19162    /**
19163     * Starts a drag and drop operation. When your application calls this method, it passes a
19164     * {@link android.view.View.DragShadowBuilder} object to the system. The
19165     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
19166     * to get metrics for the drag shadow, and then calls the object's
19167     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
19168     * <p>
19169     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
19170     *  drag events to all the View objects in your application that are currently visible. It does
19171     *  this either by calling the View object's drag listener (an implementation of
19172     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
19173     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
19174     *  Both are passed a {@link android.view.DragEvent} object that has a
19175     *  {@link android.view.DragEvent#getAction()} value of
19176     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
19177     * </p>
19178     * <p>
19179     * Your application can invoke startDrag() on any attached View object. The View object does not
19180     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
19181     * be related to the View the user selected for dragging.
19182     * </p>
19183     * @param data A {@link android.content.ClipData} object pointing to the data to be
19184     * transferred by the drag and drop operation.
19185     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
19186     * drag shadow.
19187     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
19188     * drop operation. This Object is put into every DragEvent object sent by the system during the
19189     * current drag.
19190     * <p>
19191     * myLocalState is a lightweight mechanism for the sending information from the dragged View
19192     * to the target Views. For example, it can contain flags that differentiate between a
19193     * a copy operation and a move operation.
19194     * </p>
19195     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
19196     * so the parameter should be set to 0.
19197     * @return {@code true} if the method completes successfully, or
19198     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
19199     * do a drag, and so no drag operation is in progress.
19200     */
19201    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
19202            Object myLocalState, int flags) {
19203        if (ViewDebug.DEBUG_DRAG) {
19204            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
19205        }
19206        boolean okay = false;
19207
19208        Point shadowSize = new Point();
19209        Point shadowTouchPoint = new Point();
19210        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
19211
19212        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
19213                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
19214            throw new IllegalStateException("Drag shadow dimensions must not be negative");
19215        }
19216
19217        if (ViewDebug.DEBUG_DRAG) {
19218            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
19219                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
19220        }
19221        Surface surface = new Surface();
19222        try {
19223            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
19224                    flags, shadowSize.x, shadowSize.y, surface);
19225            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
19226                    + " surface=" + surface);
19227            if (token != null) {
19228                Canvas canvas = surface.lockCanvas(null);
19229                try {
19230                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
19231                    shadowBuilder.onDrawShadow(canvas);
19232                } finally {
19233                    surface.unlockCanvasAndPost(canvas);
19234                }
19235
19236                final ViewRootImpl root = getViewRootImpl();
19237
19238                // Cache the local state object for delivery with DragEvents
19239                root.setLocalDragState(myLocalState);
19240
19241                // repurpose 'shadowSize' for the last touch point
19242                root.getLastTouchPoint(shadowSize);
19243
19244                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
19245                        shadowSize.x, shadowSize.y,
19246                        shadowTouchPoint.x, shadowTouchPoint.y, data);
19247                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
19248
19249                // Off and running!  Release our local surface instance; the drag
19250                // shadow surface is now managed by the system process.
19251                surface.release();
19252            }
19253        } catch (Exception e) {
19254            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
19255            surface.destroy();
19256        }
19257
19258        return okay;
19259    }
19260
19261    /**
19262     * Handles drag events sent by the system following a call to
19263     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
19264     *<p>
19265     * When the system calls this method, it passes a
19266     * {@link android.view.DragEvent} object. A call to
19267     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
19268     * in DragEvent. The method uses these to determine what is happening in the drag and drop
19269     * operation.
19270     * @param event The {@link android.view.DragEvent} sent by the system.
19271     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
19272     * in DragEvent, indicating the type of drag event represented by this object.
19273     * @return {@code true} if the method was successful, otherwise {@code false}.
19274     * <p>
19275     *  The method should return {@code true} in response to an action type of
19276     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
19277     *  operation.
19278     * </p>
19279     * <p>
19280     *  The method should also return {@code true} in response to an action type of
19281     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
19282     *  {@code false} if it didn't.
19283     * </p>
19284     */
19285    public boolean onDragEvent(DragEvent event) {
19286        return false;
19287    }
19288
19289    /**
19290     * Detects if this View is enabled and has a drag event listener.
19291     * If both are true, then it calls the drag event listener with the
19292     * {@link android.view.DragEvent} it received. If the drag event listener returns
19293     * {@code true}, then dispatchDragEvent() returns {@code true}.
19294     * <p>
19295     * For all other cases, the method calls the
19296     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
19297     * method and returns its result.
19298     * </p>
19299     * <p>
19300     * This ensures that a drag event is always consumed, even if the View does not have a drag
19301     * event listener. However, if the View has a listener and the listener returns true, then
19302     * onDragEvent() is not called.
19303     * </p>
19304     */
19305    public boolean dispatchDragEvent(DragEvent event) {
19306        ListenerInfo li = mListenerInfo;
19307        //noinspection SimplifiableIfStatement
19308        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
19309                && li.mOnDragListener.onDrag(this, event)) {
19310            return true;
19311        }
19312        return onDragEvent(event);
19313    }
19314
19315    boolean canAcceptDrag() {
19316        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
19317    }
19318
19319    /**
19320     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
19321     * it is ever exposed at all.
19322     * @hide
19323     */
19324    public void onCloseSystemDialogs(String reason) {
19325    }
19326
19327    /**
19328     * Given a Drawable whose bounds have been set to draw into this view,
19329     * update a Region being computed for
19330     * {@link #gatherTransparentRegion(android.graphics.Region)} so
19331     * that any non-transparent parts of the Drawable are removed from the
19332     * given transparent region.
19333     *
19334     * @param dr The Drawable whose transparency is to be applied to the region.
19335     * @param region A Region holding the current transparency information,
19336     * where any parts of the region that are set are considered to be
19337     * transparent.  On return, this region will be modified to have the
19338     * transparency information reduced by the corresponding parts of the
19339     * Drawable that are not transparent.
19340     * {@hide}
19341     */
19342    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
19343        if (DBG) {
19344            Log.i("View", "Getting transparent region for: " + this);
19345        }
19346        final Region r = dr.getTransparentRegion();
19347        final Rect db = dr.getBounds();
19348        final AttachInfo attachInfo = mAttachInfo;
19349        if (r != null && attachInfo != null) {
19350            final int w = getRight()-getLeft();
19351            final int h = getBottom()-getTop();
19352            if (db.left > 0) {
19353                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
19354                r.op(0, 0, db.left, h, Region.Op.UNION);
19355            }
19356            if (db.right < w) {
19357                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
19358                r.op(db.right, 0, w, h, Region.Op.UNION);
19359            }
19360            if (db.top > 0) {
19361                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
19362                r.op(0, 0, w, db.top, Region.Op.UNION);
19363            }
19364            if (db.bottom < h) {
19365                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
19366                r.op(0, db.bottom, w, h, Region.Op.UNION);
19367            }
19368            final int[] location = attachInfo.mTransparentLocation;
19369            getLocationInWindow(location);
19370            r.translate(location[0], location[1]);
19371            region.op(r, Region.Op.INTERSECT);
19372        } else {
19373            region.op(db, Region.Op.DIFFERENCE);
19374        }
19375    }
19376
19377    private void checkForLongClick(int delayOffset) {
19378        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
19379            mHasPerformedLongPress = false;
19380
19381            if (mPendingCheckForLongPress == null) {
19382                mPendingCheckForLongPress = new CheckForLongPress();
19383            }
19384            mPendingCheckForLongPress.rememberWindowAttachCount();
19385            postDelayed(mPendingCheckForLongPress,
19386                    ViewConfiguration.getLongPressTimeout() - delayOffset);
19387        }
19388    }
19389
19390    /**
19391     * Inflate a view from an XML resource.  This convenience method wraps the {@link
19392     * LayoutInflater} class, which provides a full range of options for view inflation.
19393     *
19394     * @param context The Context object for your activity or application.
19395     * @param resource The resource ID to inflate
19396     * @param root A view group that will be the parent.  Used to properly inflate the
19397     * layout_* parameters.
19398     * @see LayoutInflater
19399     */
19400    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
19401        LayoutInflater factory = LayoutInflater.from(context);
19402        return factory.inflate(resource, root);
19403    }
19404
19405    /**
19406     * Scroll the view with standard behavior for scrolling beyond the normal
19407     * content boundaries. Views that call this method should override
19408     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
19409     * results of an over-scroll operation.
19410     *
19411     * Views can use this method to handle any touch or fling-based scrolling.
19412     *
19413     * @param deltaX Change in X in pixels
19414     * @param deltaY Change in Y in pixels
19415     * @param scrollX Current X scroll value in pixels before applying deltaX
19416     * @param scrollY Current Y scroll value in pixels before applying deltaY
19417     * @param scrollRangeX Maximum content scroll range along the X axis
19418     * @param scrollRangeY Maximum content scroll range along the Y axis
19419     * @param maxOverScrollX Number of pixels to overscroll by in either direction
19420     *          along the X axis.
19421     * @param maxOverScrollY Number of pixels to overscroll by in either direction
19422     *          along the Y axis.
19423     * @param isTouchEvent true if this scroll operation is the result of a touch event.
19424     * @return true if scrolling was clamped to an over-scroll boundary along either
19425     *          axis, false otherwise.
19426     */
19427    @SuppressWarnings({"UnusedParameters"})
19428    protected boolean overScrollBy(int deltaX, int deltaY,
19429            int scrollX, int scrollY,
19430            int scrollRangeX, int scrollRangeY,
19431            int maxOverScrollX, int maxOverScrollY,
19432            boolean isTouchEvent) {
19433        final int overScrollMode = mOverScrollMode;
19434        final boolean canScrollHorizontal =
19435                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
19436        final boolean canScrollVertical =
19437                computeVerticalScrollRange() > computeVerticalScrollExtent();
19438        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
19439                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
19440        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
19441                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
19442
19443        int newScrollX = scrollX + deltaX;
19444        if (!overScrollHorizontal) {
19445            maxOverScrollX = 0;
19446        }
19447
19448        int newScrollY = scrollY + deltaY;
19449        if (!overScrollVertical) {
19450            maxOverScrollY = 0;
19451        }
19452
19453        // Clamp values if at the limits and record
19454        final int left = -maxOverScrollX;
19455        final int right = maxOverScrollX + scrollRangeX;
19456        final int top = -maxOverScrollY;
19457        final int bottom = maxOverScrollY + scrollRangeY;
19458
19459        boolean clampedX = false;
19460        if (newScrollX > right) {
19461            newScrollX = right;
19462            clampedX = true;
19463        } else if (newScrollX < left) {
19464            newScrollX = left;
19465            clampedX = true;
19466        }
19467
19468        boolean clampedY = false;
19469        if (newScrollY > bottom) {
19470            newScrollY = bottom;
19471            clampedY = true;
19472        } else if (newScrollY < top) {
19473            newScrollY = top;
19474            clampedY = true;
19475        }
19476
19477        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
19478
19479        return clampedX || clampedY;
19480    }
19481
19482    /**
19483     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
19484     * respond to the results of an over-scroll operation.
19485     *
19486     * @param scrollX New X scroll value in pixels
19487     * @param scrollY New Y scroll value in pixels
19488     * @param clampedX True if scrollX was clamped to an over-scroll boundary
19489     * @param clampedY True if scrollY was clamped to an over-scroll boundary
19490     */
19491    protected void onOverScrolled(int scrollX, int scrollY,
19492            boolean clampedX, boolean clampedY) {
19493        // Intentionally empty.
19494    }
19495
19496    /**
19497     * Returns the over-scroll mode for this view. The result will be
19498     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19499     * (allow over-scrolling only if the view content is larger than the container),
19500     * or {@link #OVER_SCROLL_NEVER}.
19501     *
19502     * @return This view's over-scroll mode.
19503     */
19504    public int getOverScrollMode() {
19505        return mOverScrollMode;
19506    }
19507
19508    /**
19509     * Set the over-scroll mode for this view. Valid over-scroll modes are
19510     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
19511     * (allow over-scrolling only if the view content is larger than the container),
19512     * or {@link #OVER_SCROLL_NEVER}.
19513     *
19514     * Setting the over-scroll mode of a view will have an effect only if the
19515     * view is capable of scrolling.
19516     *
19517     * @param overScrollMode The new over-scroll mode for this view.
19518     */
19519    public void setOverScrollMode(int overScrollMode) {
19520        if (overScrollMode != OVER_SCROLL_ALWAYS &&
19521                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
19522                overScrollMode != OVER_SCROLL_NEVER) {
19523            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
19524        }
19525        mOverScrollMode = overScrollMode;
19526    }
19527
19528    /**
19529     * Enable or disable nested scrolling for this view.
19530     *
19531     * <p>If this property is set to true the view will be permitted to initiate nested
19532     * scrolling operations with a compatible parent view in the current hierarchy. If this
19533     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
19534     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
19535     * the nested scroll.</p>
19536     *
19537     * @param enabled true to enable nested scrolling, false to disable
19538     *
19539     * @see #isNestedScrollingEnabled()
19540     */
19541    public void setNestedScrollingEnabled(boolean enabled) {
19542        if (enabled) {
19543            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
19544        } else {
19545            stopNestedScroll();
19546            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
19547        }
19548    }
19549
19550    /**
19551     * Returns true if nested scrolling is enabled for this view.
19552     *
19553     * <p>If nested scrolling is enabled and this View class implementation supports it,
19554     * this view will act as a nested scrolling child view when applicable, forwarding data
19555     * about the scroll operation in progress to a compatible and cooperating nested scrolling
19556     * parent.</p>
19557     *
19558     * @return true if nested scrolling is enabled
19559     *
19560     * @see #setNestedScrollingEnabled(boolean)
19561     */
19562    public boolean isNestedScrollingEnabled() {
19563        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
19564                PFLAG3_NESTED_SCROLLING_ENABLED;
19565    }
19566
19567    /**
19568     * Begin a nestable scroll operation along the given axes.
19569     *
19570     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
19571     *
19572     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
19573     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
19574     * In the case of touch scrolling the nested scroll will be terminated automatically in
19575     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
19576     * In the event of programmatic scrolling the caller must explicitly call
19577     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
19578     *
19579     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
19580     * If it returns false the caller may ignore the rest of this contract until the next scroll.
19581     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
19582     *
19583     * <p>At each incremental step of the scroll the caller should invoke
19584     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
19585     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
19586     * parent at least partially consumed the scroll and the caller should adjust the amount it
19587     * scrolls by.</p>
19588     *
19589     * <p>After applying the remainder of the scroll delta the caller should invoke
19590     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
19591     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
19592     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
19593     * </p>
19594     *
19595     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
19596     *             {@link #SCROLL_AXIS_VERTICAL}.
19597     * @return true if a cooperative parent was found and nested scrolling has been enabled for
19598     *         the current gesture.
19599     *
19600     * @see #stopNestedScroll()
19601     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19602     * @see #dispatchNestedScroll(int, int, int, int, int[])
19603     */
19604    public boolean startNestedScroll(int axes) {
19605        if (hasNestedScrollingParent()) {
19606            // Already in progress
19607            return true;
19608        }
19609        if (isNestedScrollingEnabled()) {
19610            ViewParent p = getParent();
19611            View child = this;
19612            while (p != null) {
19613                try {
19614                    if (p.onStartNestedScroll(child, this, axes)) {
19615                        mNestedScrollingParent = p;
19616                        p.onNestedScrollAccepted(child, this, axes);
19617                        return true;
19618                    }
19619                } catch (AbstractMethodError e) {
19620                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
19621                            "method onStartNestedScroll", e);
19622                    // Allow the search upward to continue
19623                }
19624                if (p instanceof View) {
19625                    child = (View) p;
19626                }
19627                p = p.getParent();
19628            }
19629        }
19630        return false;
19631    }
19632
19633    /**
19634     * Stop a nested scroll in progress.
19635     *
19636     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
19637     *
19638     * @see #startNestedScroll(int)
19639     */
19640    public void stopNestedScroll() {
19641        if (mNestedScrollingParent != null) {
19642            mNestedScrollingParent.onStopNestedScroll(this);
19643            mNestedScrollingParent = null;
19644        }
19645    }
19646
19647    /**
19648     * Returns true if this view has a nested scrolling parent.
19649     *
19650     * <p>The presence of a nested scrolling parent indicates that this view has initiated
19651     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
19652     *
19653     * @return whether this view has a nested scrolling parent
19654     */
19655    public boolean hasNestedScrollingParent() {
19656        return mNestedScrollingParent != null;
19657    }
19658
19659    /**
19660     * Dispatch one step of a nested scroll in progress.
19661     *
19662     * <p>Implementations of views that support nested scrolling should call this to report
19663     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
19664     * is not currently in progress or nested scrolling is not
19665     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
19666     *
19667     * <p>Compatible View implementations should also call
19668     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
19669     * consuming a component of the scroll event themselves.</p>
19670     *
19671     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
19672     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
19673     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
19674     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
19675     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19676     *                       in local view coordinates of this view from before this operation
19677     *                       to after it completes. View implementations may use this to adjust
19678     *                       expected input coordinate tracking.
19679     * @return true if the event was dispatched, false if it could not be dispatched.
19680     * @see #dispatchNestedPreScroll(int, int, int[], int[])
19681     */
19682    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
19683            int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) {
19684        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19685            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
19686                int startX = 0;
19687                int startY = 0;
19688                if (offsetInWindow != null) {
19689                    getLocationInWindow(offsetInWindow);
19690                    startX = offsetInWindow[0];
19691                    startY = offsetInWindow[1];
19692                }
19693
19694                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
19695                        dxUnconsumed, dyUnconsumed);
19696
19697                if (offsetInWindow != null) {
19698                    getLocationInWindow(offsetInWindow);
19699                    offsetInWindow[0] -= startX;
19700                    offsetInWindow[1] -= startY;
19701                }
19702                return true;
19703            } else if (offsetInWindow != null) {
19704                // No motion, no dispatch. Keep offsetInWindow up to date.
19705                offsetInWindow[0] = 0;
19706                offsetInWindow[1] = 0;
19707            }
19708        }
19709        return false;
19710    }
19711
19712    /**
19713     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
19714     *
19715     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
19716     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
19717     * scrolling operation to consume some or all of the scroll operation before the child view
19718     * consumes it.</p>
19719     *
19720     * @param dx Horizontal scroll distance in pixels
19721     * @param dy Vertical scroll distance in pixels
19722     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
19723     *                 and consumed[1] the consumed dy.
19724     * @param offsetInWindow Optional. If not null, on return this will contain the offset
19725     *                       in local view coordinates of this view from before this operation
19726     *                       to after it completes. View implementations may use this to adjust
19727     *                       expected input coordinate tracking.
19728     * @return true if the parent consumed some or all of the scroll delta
19729     * @see #dispatchNestedScroll(int, int, int, int, int[])
19730     */
19731    public boolean dispatchNestedPreScroll(int dx, int dy,
19732            @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) {
19733        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19734            if (dx != 0 || dy != 0) {
19735                int startX = 0;
19736                int startY = 0;
19737                if (offsetInWindow != null) {
19738                    getLocationInWindow(offsetInWindow);
19739                    startX = offsetInWindow[0];
19740                    startY = offsetInWindow[1];
19741                }
19742
19743                if (consumed == null) {
19744                    if (mTempNestedScrollConsumed == null) {
19745                        mTempNestedScrollConsumed = new int[2];
19746                    }
19747                    consumed = mTempNestedScrollConsumed;
19748                }
19749                consumed[0] = 0;
19750                consumed[1] = 0;
19751                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
19752
19753                if (offsetInWindow != null) {
19754                    getLocationInWindow(offsetInWindow);
19755                    offsetInWindow[0] -= startX;
19756                    offsetInWindow[1] -= startY;
19757                }
19758                return consumed[0] != 0 || consumed[1] != 0;
19759            } else if (offsetInWindow != null) {
19760                offsetInWindow[0] = 0;
19761                offsetInWindow[1] = 0;
19762            }
19763        }
19764        return false;
19765    }
19766
19767    /**
19768     * Dispatch a fling to a nested scrolling parent.
19769     *
19770     * <p>This method should be used to indicate that a nested scrolling child has detected
19771     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
19772     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
19773     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
19774     * along a scrollable axis.</p>
19775     *
19776     * <p>If a nested scrolling child view would normally fling but it is at the edge of
19777     * its own content, it can use this method to delegate the fling to its nested scrolling
19778     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
19779     *
19780     * @param velocityX Horizontal fling velocity in pixels per second
19781     * @param velocityY Vertical fling velocity in pixels per second
19782     * @param consumed true if the child consumed the fling, false otherwise
19783     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
19784     */
19785    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
19786        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19787            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
19788        }
19789        return false;
19790    }
19791
19792    /**
19793     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
19794     *
19795     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
19796     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
19797     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
19798     * before the child view consumes it. If this method returns <code>true</code>, a nested
19799     * parent view consumed the fling and this view should not scroll as a result.</p>
19800     *
19801     * <p>For a better user experience, only one view in a nested scrolling chain should consume
19802     * the fling at a time. If a parent view consumed the fling this method will return false.
19803     * Custom view implementations should account for this in two ways:</p>
19804     *
19805     * <ul>
19806     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
19807     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
19808     *     position regardless.</li>
19809     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
19810     *     even to settle back to a valid idle position.</li>
19811     * </ul>
19812     *
19813     * <p>Views should also not offer fling velocities to nested parent views along an axis
19814     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
19815     * should not offer a horizontal fling velocity to its parents since scrolling along that
19816     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
19817     *
19818     * @param velocityX Horizontal fling velocity in pixels per second
19819     * @param velocityY Vertical fling velocity in pixels per second
19820     * @return true if a nested scrolling parent consumed the fling
19821     */
19822    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
19823        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
19824            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
19825        }
19826        return false;
19827    }
19828
19829    /**
19830     * Gets a scale factor that determines the distance the view should scroll
19831     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
19832     * @return The vertical scroll scale factor.
19833     * @hide
19834     */
19835    protected float getVerticalScrollFactor() {
19836        if (mVerticalScrollFactor == 0) {
19837            TypedValue outValue = new TypedValue();
19838            if (!mContext.getTheme().resolveAttribute(
19839                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
19840                throw new IllegalStateException(
19841                        "Expected theme to define listPreferredItemHeight.");
19842            }
19843            mVerticalScrollFactor = outValue.getDimension(
19844                    mContext.getResources().getDisplayMetrics());
19845        }
19846        return mVerticalScrollFactor;
19847    }
19848
19849    /**
19850     * Gets a scale factor that determines the distance the view should scroll
19851     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
19852     * @return The horizontal scroll scale factor.
19853     * @hide
19854     */
19855    protected float getHorizontalScrollFactor() {
19856        // TODO: Should use something else.
19857        return getVerticalScrollFactor();
19858    }
19859
19860    /**
19861     * Return the value specifying the text direction or policy that was set with
19862     * {@link #setTextDirection(int)}.
19863     *
19864     * @return the defined text direction. It can be one of:
19865     *
19866     * {@link #TEXT_DIRECTION_INHERIT},
19867     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19868     * {@link #TEXT_DIRECTION_ANY_RTL},
19869     * {@link #TEXT_DIRECTION_LTR},
19870     * {@link #TEXT_DIRECTION_RTL},
19871     * {@link #TEXT_DIRECTION_LOCALE},
19872     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19873     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19874     *
19875     * @attr ref android.R.styleable#View_textDirection
19876     *
19877     * @hide
19878     */
19879    @ViewDebug.ExportedProperty(category = "text", mapping = {
19880            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19881            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19882            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19883            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19884            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19885            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19886            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19887            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19888    })
19889    public int getRawTextDirection() {
19890        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
19891    }
19892
19893    /**
19894     * Set the text direction.
19895     *
19896     * @param textDirection the direction to set. Should be one of:
19897     *
19898     * {@link #TEXT_DIRECTION_INHERIT},
19899     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19900     * {@link #TEXT_DIRECTION_ANY_RTL},
19901     * {@link #TEXT_DIRECTION_LTR},
19902     * {@link #TEXT_DIRECTION_RTL},
19903     * {@link #TEXT_DIRECTION_LOCALE}
19904     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19905     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL},
19906     *
19907     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
19908     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
19909     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
19910     *
19911     * @attr ref android.R.styleable#View_textDirection
19912     */
19913    public void setTextDirection(int textDirection) {
19914        if (getRawTextDirection() != textDirection) {
19915            // Reset the current text direction and the resolved one
19916            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
19917            resetResolvedTextDirection();
19918            // Set the new text direction
19919            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
19920            // Do resolution
19921            resolveTextDirection();
19922            // Notify change
19923            onRtlPropertiesChanged(getLayoutDirection());
19924            // Refresh
19925            requestLayout();
19926            invalidate(true);
19927        }
19928    }
19929
19930    /**
19931     * Return the resolved text direction.
19932     *
19933     * @return the resolved text direction. Returns one of:
19934     *
19935     * {@link #TEXT_DIRECTION_FIRST_STRONG},
19936     * {@link #TEXT_DIRECTION_ANY_RTL},
19937     * {@link #TEXT_DIRECTION_LTR},
19938     * {@link #TEXT_DIRECTION_RTL},
19939     * {@link #TEXT_DIRECTION_LOCALE},
19940     * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR},
19941     * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}
19942     *
19943     * @attr ref android.R.styleable#View_textDirection
19944     */
19945    @ViewDebug.ExportedProperty(category = "text", mapping = {
19946            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
19947            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
19948            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
19949            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
19950            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
19951            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"),
19952            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"),
19953            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL")
19954    })
19955    public int getTextDirection() {
19956        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
19957    }
19958
19959    /**
19960     * Resolve the text direction.
19961     *
19962     * @return true if resolution has been done, false otherwise.
19963     *
19964     * @hide
19965     */
19966    public boolean resolveTextDirection() {
19967        // Reset any previous text direction resolution
19968        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
19969
19970        if (hasRtlSupport()) {
19971            // Set resolved text direction flag depending on text direction flag
19972            final int textDirection = getRawTextDirection();
19973            switch(textDirection) {
19974                case TEXT_DIRECTION_INHERIT:
19975                    if (!canResolveTextDirection()) {
19976                        // We cannot do the resolution if there is no parent, so use the default one
19977                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19978                        // Resolution will need to happen again later
19979                        return false;
19980                    }
19981
19982                    // Parent has not yet resolved, so we still return the default
19983                    try {
19984                        if (!mParent.isTextDirectionResolved()) {
19985                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19986                            // Resolution will need to happen again later
19987                            return false;
19988                        }
19989                    } catch (AbstractMethodError e) {
19990                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19991                                " does not fully implement ViewParent", e);
19992                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
19993                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
19994                        return true;
19995                    }
19996
19997                    // Set current resolved direction to the same value as the parent's one
19998                    int parentResolvedDirection;
19999                    try {
20000                        parentResolvedDirection = mParent.getTextDirection();
20001                    } catch (AbstractMethodError e) {
20002                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20003                                " does not fully implement ViewParent", e);
20004                        parentResolvedDirection = TEXT_DIRECTION_LTR;
20005                    }
20006                    switch (parentResolvedDirection) {
20007                        case TEXT_DIRECTION_FIRST_STRONG:
20008                        case TEXT_DIRECTION_ANY_RTL:
20009                        case TEXT_DIRECTION_LTR:
20010                        case TEXT_DIRECTION_RTL:
20011                        case TEXT_DIRECTION_LOCALE:
20012                        case TEXT_DIRECTION_FIRST_STRONG_LTR:
20013                        case TEXT_DIRECTION_FIRST_STRONG_RTL:
20014                            mPrivateFlags2 |=
20015                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20016                            break;
20017                        default:
20018                            // Default resolved direction is "first strong" heuristic
20019                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20020                    }
20021                    break;
20022                case TEXT_DIRECTION_FIRST_STRONG:
20023                case TEXT_DIRECTION_ANY_RTL:
20024                case TEXT_DIRECTION_LTR:
20025                case TEXT_DIRECTION_RTL:
20026                case TEXT_DIRECTION_LOCALE:
20027                case TEXT_DIRECTION_FIRST_STRONG_LTR:
20028                case TEXT_DIRECTION_FIRST_STRONG_RTL:
20029                    // Resolved direction is the same as text direction
20030                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
20031                    break;
20032                default:
20033                    // Default resolved direction is "first strong" heuristic
20034                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20035            }
20036        } else {
20037            // Default resolved direction is "first strong" heuristic
20038            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20039        }
20040
20041        // Set to resolved
20042        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
20043        return true;
20044    }
20045
20046    /**
20047     * Check if text direction resolution can be done.
20048     *
20049     * @return true if text direction resolution can be done otherwise return false.
20050     */
20051    public boolean canResolveTextDirection() {
20052        switch (getRawTextDirection()) {
20053            case TEXT_DIRECTION_INHERIT:
20054                if (mParent != null) {
20055                    try {
20056                        return mParent.canResolveTextDirection();
20057                    } catch (AbstractMethodError e) {
20058                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20059                                " does not fully implement ViewParent", e);
20060                    }
20061                }
20062                return false;
20063
20064            default:
20065                return true;
20066        }
20067    }
20068
20069    /**
20070     * Reset resolved text direction. Text direction will be resolved during a call to
20071     * {@link #onMeasure(int, int)}.
20072     *
20073     * @hide
20074     */
20075    public void resetResolvedTextDirection() {
20076        // Reset any previous text direction resolution
20077        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
20078        // Set to default value
20079        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
20080    }
20081
20082    /**
20083     * @return true if text direction is inherited.
20084     *
20085     * @hide
20086     */
20087    public boolean isTextDirectionInherited() {
20088        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
20089    }
20090
20091    /**
20092     * @return true if text direction is resolved.
20093     */
20094    public boolean isTextDirectionResolved() {
20095        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
20096    }
20097
20098    /**
20099     * Return the value specifying the text alignment or policy that was set with
20100     * {@link #setTextAlignment(int)}.
20101     *
20102     * @return the defined text alignment. It can be one of:
20103     *
20104     * {@link #TEXT_ALIGNMENT_INHERIT},
20105     * {@link #TEXT_ALIGNMENT_GRAVITY},
20106     * {@link #TEXT_ALIGNMENT_CENTER},
20107     * {@link #TEXT_ALIGNMENT_TEXT_START},
20108     * {@link #TEXT_ALIGNMENT_TEXT_END},
20109     * {@link #TEXT_ALIGNMENT_VIEW_START},
20110     * {@link #TEXT_ALIGNMENT_VIEW_END}
20111     *
20112     * @attr ref android.R.styleable#View_textAlignment
20113     *
20114     * @hide
20115     */
20116    @ViewDebug.ExportedProperty(category = "text", mapping = {
20117            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20118            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20119            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20120            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20121            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20122            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20123            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20124    })
20125    @TextAlignment
20126    public int getRawTextAlignment() {
20127        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
20128    }
20129
20130    /**
20131     * Set the text alignment.
20132     *
20133     * @param textAlignment The text alignment to set. Should be one of
20134     *
20135     * {@link #TEXT_ALIGNMENT_INHERIT},
20136     * {@link #TEXT_ALIGNMENT_GRAVITY},
20137     * {@link #TEXT_ALIGNMENT_CENTER},
20138     * {@link #TEXT_ALIGNMENT_TEXT_START},
20139     * {@link #TEXT_ALIGNMENT_TEXT_END},
20140     * {@link #TEXT_ALIGNMENT_VIEW_START},
20141     * {@link #TEXT_ALIGNMENT_VIEW_END}
20142     *
20143     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
20144     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
20145     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
20146     *
20147     * @attr ref android.R.styleable#View_textAlignment
20148     */
20149    public void setTextAlignment(@TextAlignment int textAlignment) {
20150        if (textAlignment != getRawTextAlignment()) {
20151            // Reset the current and resolved text alignment
20152            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
20153            resetResolvedTextAlignment();
20154            // Set the new text alignment
20155            mPrivateFlags2 |=
20156                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
20157            // Do resolution
20158            resolveTextAlignment();
20159            // Notify change
20160            onRtlPropertiesChanged(getLayoutDirection());
20161            // Refresh
20162            requestLayout();
20163            invalidate(true);
20164        }
20165    }
20166
20167    /**
20168     * Return the resolved text alignment.
20169     *
20170     * @return the resolved text alignment. Returns one of:
20171     *
20172     * {@link #TEXT_ALIGNMENT_GRAVITY},
20173     * {@link #TEXT_ALIGNMENT_CENTER},
20174     * {@link #TEXT_ALIGNMENT_TEXT_START},
20175     * {@link #TEXT_ALIGNMENT_TEXT_END},
20176     * {@link #TEXT_ALIGNMENT_VIEW_START},
20177     * {@link #TEXT_ALIGNMENT_VIEW_END}
20178     *
20179     * @attr ref android.R.styleable#View_textAlignment
20180     */
20181    @ViewDebug.ExportedProperty(category = "text", mapping = {
20182            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
20183            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
20184            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
20185            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
20186            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
20187            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
20188            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
20189    })
20190    @TextAlignment
20191    public int getTextAlignment() {
20192        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
20193                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
20194    }
20195
20196    /**
20197     * Resolve the text alignment.
20198     *
20199     * @return true if resolution has been done, false otherwise.
20200     *
20201     * @hide
20202     */
20203    public boolean resolveTextAlignment() {
20204        // Reset any previous text alignment resolution
20205        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20206
20207        if (hasRtlSupport()) {
20208            // Set resolved text alignment flag depending on text alignment flag
20209            final int textAlignment = getRawTextAlignment();
20210            switch (textAlignment) {
20211                case TEXT_ALIGNMENT_INHERIT:
20212                    // Check if we can resolve the text alignment
20213                    if (!canResolveTextAlignment()) {
20214                        // We cannot do the resolution if there is no parent so use the default
20215                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20216                        // Resolution will need to happen again later
20217                        return false;
20218                    }
20219
20220                    // Parent has not yet resolved, so we still return the default
20221                    try {
20222                        if (!mParent.isTextAlignmentResolved()) {
20223                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20224                            // Resolution will need to happen again later
20225                            return false;
20226                        }
20227                    } catch (AbstractMethodError e) {
20228                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20229                                " does not fully implement ViewParent", e);
20230                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
20231                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20232                        return true;
20233                    }
20234
20235                    int parentResolvedTextAlignment;
20236                    try {
20237                        parentResolvedTextAlignment = mParent.getTextAlignment();
20238                    } catch (AbstractMethodError e) {
20239                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20240                                " does not fully implement ViewParent", e);
20241                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
20242                    }
20243                    switch (parentResolvedTextAlignment) {
20244                        case TEXT_ALIGNMENT_GRAVITY:
20245                        case TEXT_ALIGNMENT_TEXT_START:
20246                        case TEXT_ALIGNMENT_TEXT_END:
20247                        case TEXT_ALIGNMENT_CENTER:
20248                        case TEXT_ALIGNMENT_VIEW_START:
20249                        case TEXT_ALIGNMENT_VIEW_END:
20250                            // Resolved text alignment is the same as the parent resolved
20251                            // text alignment
20252                            mPrivateFlags2 |=
20253                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20254                            break;
20255                        default:
20256                            // Use default resolved text alignment
20257                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20258                    }
20259                    break;
20260                case TEXT_ALIGNMENT_GRAVITY:
20261                case TEXT_ALIGNMENT_TEXT_START:
20262                case TEXT_ALIGNMENT_TEXT_END:
20263                case TEXT_ALIGNMENT_CENTER:
20264                case TEXT_ALIGNMENT_VIEW_START:
20265                case TEXT_ALIGNMENT_VIEW_END:
20266                    // Resolved text alignment is the same as text alignment
20267                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
20268                    break;
20269                default:
20270                    // Use default resolved text alignment
20271                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20272            }
20273        } else {
20274            // Use default resolved text alignment
20275            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20276        }
20277
20278        // Set the resolved
20279        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20280        return true;
20281    }
20282
20283    /**
20284     * Check if text alignment resolution can be done.
20285     *
20286     * @return true if text alignment resolution can be done otherwise return false.
20287     */
20288    public boolean canResolveTextAlignment() {
20289        switch (getRawTextAlignment()) {
20290            case TEXT_DIRECTION_INHERIT:
20291                if (mParent != null) {
20292                    try {
20293                        return mParent.canResolveTextAlignment();
20294                    } catch (AbstractMethodError e) {
20295                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
20296                                " does not fully implement ViewParent", e);
20297                    }
20298                }
20299                return false;
20300
20301            default:
20302                return true;
20303        }
20304    }
20305
20306    /**
20307     * Reset resolved text alignment. Text alignment will be resolved during a call to
20308     * {@link #onMeasure(int, int)}.
20309     *
20310     * @hide
20311     */
20312    public void resetResolvedTextAlignment() {
20313        // Reset any previous text alignment resolution
20314        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
20315        // Set to default
20316        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
20317    }
20318
20319    /**
20320     * @return true if text alignment is inherited.
20321     *
20322     * @hide
20323     */
20324    public boolean isTextAlignmentInherited() {
20325        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
20326    }
20327
20328    /**
20329     * @return true if text alignment is resolved.
20330     */
20331    public boolean isTextAlignmentResolved() {
20332        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
20333    }
20334
20335    /**
20336     * Generate a value suitable for use in {@link #setId(int)}.
20337     * This value will not collide with ID values generated at build time by aapt for R.id.
20338     *
20339     * @return a generated ID value
20340     */
20341    public static int generateViewId() {
20342        for (;;) {
20343            final int result = sNextGeneratedId.get();
20344            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
20345            int newValue = result + 1;
20346            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
20347            if (sNextGeneratedId.compareAndSet(result, newValue)) {
20348                return result;
20349            }
20350        }
20351    }
20352
20353    /**
20354     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
20355     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
20356     *                           a normal View or a ViewGroup with
20357     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
20358     * @hide
20359     */
20360    public void captureTransitioningViews(List<View> transitioningViews) {
20361        if (getVisibility() == View.VISIBLE) {
20362            transitioningViews.add(this);
20363        }
20364    }
20365
20366    /**
20367     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
20368     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
20369     * @hide
20370     */
20371    public void findNamedViews(Map<String, View> namedElements) {
20372        if (getVisibility() == VISIBLE || mGhostView != null) {
20373            String transitionName = getTransitionName();
20374            if (transitionName != null) {
20375                namedElements.put(transitionName, this);
20376            }
20377        }
20378    }
20379
20380    //
20381    // Properties
20382    //
20383    /**
20384     * A Property wrapper around the <code>alpha</code> functionality handled by the
20385     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
20386     */
20387    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
20388        @Override
20389        public void setValue(View object, float value) {
20390            object.setAlpha(value);
20391        }
20392
20393        @Override
20394        public Float get(View object) {
20395            return object.getAlpha();
20396        }
20397    };
20398
20399    /**
20400     * A Property wrapper around the <code>translationX</code> functionality handled by the
20401     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
20402     */
20403    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
20404        @Override
20405        public void setValue(View object, float value) {
20406            object.setTranslationX(value);
20407        }
20408
20409                @Override
20410        public Float get(View object) {
20411            return object.getTranslationX();
20412        }
20413    };
20414
20415    /**
20416     * A Property wrapper around the <code>translationY</code> functionality handled by the
20417     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
20418     */
20419    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
20420        @Override
20421        public void setValue(View object, float value) {
20422            object.setTranslationY(value);
20423        }
20424
20425        @Override
20426        public Float get(View object) {
20427            return object.getTranslationY();
20428        }
20429    };
20430
20431    /**
20432     * A Property wrapper around the <code>translationZ</code> functionality handled by the
20433     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
20434     */
20435    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
20436        @Override
20437        public void setValue(View object, float value) {
20438            object.setTranslationZ(value);
20439        }
20440
20441        @Override
20442        public Float get(View object) {
20443            return object.getTranslationZ();
20444        }
20445    };
20446
20447    /**
20448     * A Property wrapper around the <code>x</code> functionality handled by the
20449     * {@link View#setX(float)} and {@link View#getX()} methods.
20450     */
20451    public static final Property<View, Float> X = new FloatProperty<View>("x") {
20452        @Override
20453        public void setValue(View object, float value) {
20454            object.setX(value);
20455        }
20456
20457        @Override
20458        public Float get(View object) {
20459            return object.getX();
20460        }
20461    };
20462
20463    /**
20464     * A Property wrapper around the <code>y</code> functionality handled by the
20465     * {@link View#setY(float)} and {@link View#getY()} methods.
20466     */
20467    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
20468        @Override
20469        public void setValue(View object, float value) {
20470            object.setY(value);
20471        }
20472
20473        @Override
20474        public Float get(View object) {
20475            return object.getY();
20476        }
20477    };
20478
20479    /**
20480     * A Property wrapper around the <code>z</code> functionality handled by the
20481     * {@link View#setZ(float)} and {@link View#getZ()} methods.
20482     */
20483    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
20484        @Override
20485        public void setValue(View object, float value) {
20486            object.setZ(value);
20487        }
20488
20489        @Override
20490        public Float get(View object) {
20491            return object.getZ();
20492        }
20493    };
20494
20495    /**
20496     * A Property wrapper around the <code>rotation</code> functionality handled by the
20497     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
20498     */
20499    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
20500        @Override
20501        public void setValue(View object, float value) {
20502            object.setRotation(value);
20503        }
20504
20505        @Override
20506        public Float get(View object) {
20507            return object.getRotation();
20508        }
20509    };
20510
20511    /**
20512     * A Property wrapper around the <code>rotationX</code> functionality handled by the
20513     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
20514     */
20515    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
20516        @Override
20517        public void setValue(View object, float value) {
20518            object.setRotationX(value);
20519        }
20520
20521        @Override
20522        public Float get(View object) {
20523            return object.getRotationX();
20524        }
20525    };
20526
20527    /**
20528     * A Property wrapper around the <code>rotationY</code> functionality handled by the
20529     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
20530     */
20531    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
20532        @Override
20533        public void setValue(View object, float value) {
20534            object.setRotationY(value);
20535        }
20536
20537        @Override
20538        public Float get(View object) {
20539            return object.getRotationY();
20540        }
20541    };
20542
20543    /**
20544     * A Property wrapper around the <code>scaleX</code> functionality handled by the
20545     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
20546     */
20547    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
20548        @Override
20549        public void setValue(View object, float value) {
20550            object.setScaleX(value);
20551        }
20552
20553        @Override
20554        public Float get(View object) {
20555            return object.getScaleX();
20556        }
20557    };
20558
20559    /**
20560     * A Property wrapper around the <code>scaleY</code> functionality handled by the
20561     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
20562     */
20563    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
20564        @Override
20565        public void setValue(View object, float value) {
20566            object.setScaleY(value);
20567        }
20568
20569        @Override
20570        public Float get(View object) {
20571            return object.getScaleY();
20572        }
20573    };
20574
20575    /**
20576     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
20577     * Each MeasureSpec represents a requirement for either the width or the height.
20578     * A MeasureSpec is comprised of a size and a mode. There are three possible
20579     * modes:
20580     * <dl>
20581     * <dt>UNSPECIFIED</dt>
20582     * <dd>
20583     * The parent has not imposed any constraint on the child. It can be whatever size
20584     * it wants.
20585     * </dd>
20586     *
20587     * <dt>EXACTLY</dt>
20588     * <dd>
20589     * The parent has determined an exact size for the child. The child is going to be
20590     * given those bounds regardless of how big it wants to be.
20591     * </dd>
20592     *
20593     * <dt>AT_MOST</dt>
20594     * <dd>
20595     * The child can be as large as it wants up to the specified size.
20596     * </dd>
20597     * </dl>
20598     *
20599     * MeasureSpecs are implemented as ints to reduce object allocation. This class
20600     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
20601     */
20602    public static class MeasureSpec {
20603        private static final int MODE_SHIFT = 30;
20604        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
20605
20606        /**
20607         * Measure specification mode: The parent has not imposed any constraint
20608         * on the child. It can be whatever size it wants.
20609         */
20610        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
20611
20612        /**
20613         * Measure specification mode: The parent has determined an exact size
20614         * for the child. The child is going to be given those bounds regardless
20615         * of how big it wants to be.
20616         */
20617        public static final int EXACTLY     = 1 << MODE_SHIFT;
20618
20619        /**
20620         * Measure specification mode: The child can be as large as it wants up
20621         * to the specified size.
20622         */
20623        public static final int AT_MOST     = 2 << MODE_SHIFT;
20624
20625        /**
20626         * Creates a measure specification based on the supplied size and mode.
20627         *
20628         * The mode must always be one of the following:
20629         * <ul>
20630         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
20631         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
20632         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
20633         * </ul>
20634         *
20635         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
20636         * implementation was such that the order of arguments did not matter
20637         * and overflow in either value could impact the resulting MeasureSpec.
20638         * {@link android.widget.RelativeLayout} was affected by this bug.
20639         * Apps targeting API levels greater than 17 will get the fixed, more strict
20640         * behavior.</p>
20641         *
20642         * @param size the size of the measure specification
20643         * @param mode the mode of the measure specification
20644         * @return the measure specification based on size and mode
20645         */
20646        public static int makeMeasureSpec(int size, int mode) {
20647            if (sUseBrokenMakeMeasureSpec) {
20648                return size + mode;
20649            } else {
20650                return (size & ~MODE_MASK) | (mode & MODE_MASK);
20651            }
20652        }
20653
20654        /**
20655         * Extracts the mode from the supplied measure specification.
20656         *
20657         * @param measureSpec the measure specification to extract the mode from
20658         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
20659         *         {@link android.view.View.MeasureSpec#AT_MOST} or
20660         *         {@link android.view.View.MeasureSpec#EXACTLY}
20661         */
20662        public static int getMode(int measureSpec) {
20663            return (measureSpec & MODE_MASK);
20664        }
20665
20666        /**
20667         * Extracts the size from the supplied measure specification.
20668         *
20669         * @param measureSpec the measure specification to extract the size from
20670         * @return the size in pixels defined in the supplied measure specification
20671         */
20672        public static int getSize(int measureSpec) {
20673            return (measureSpec & ~MODE_MASK);
20674        }
20675
20676        static int adjust(int measureSpec, int delta) {
20677            final int mode = getMode(measureSpec);
20678            int size = getSize(measureSpec);
20679            if (mode == UNSPECIFIED) {
20680                // No need to adjust size for UNSPECIFIED mode.
20681                return makeMeasureSpec(size, UNSPECIFIED);
20682            }
20683            size += delta;
20684            if (size < 0) {
20685                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
20686                        ") spec: " + toString(measureSpec) + " delta: " + delta);
20687                size = 0;
20688            }
20689            return makeMeasureSpec(size, mode);
20690        }
20691
20692        /**
20693         * Returns a String representation of the specified measure
20694         * specification.
20695         *
20696         * @param measureSpec the measure specification to convert to a String
20697         * @return a String with the following format: "MeasureSpec: MODE SIZE"
20698         */
20699        public static String toString(int measureSpec) {
20700            int mode = getMode(measureSpec);
20701            int size = getSize(measureSpec);
20702
20703            StringBuilder sb = new StringBuilder("MeasureSpec: ");
20704
20705            if (mode == UNSPECIFIED)
20706                sb.append("UNSPECIFIED ");
20707            else if (mode == EXACTLY)
20708                sb.append("EXACTLY ");
20709            else if (mode == AT_MOST)
20710                sb.append("AT_MOST ");
20711            else
20712                sb.append(mode).append(" ");
20713
20714            sb.append(size);
20715            return sb.toString();
20716        }
20717    }
20718
20719    private final class CheckForLongPress implements Runnable {
20720        private int mOriginalWindowAttachCount;
20721
20722        @Override
20723        public void run() {
20724            if (isPressed() && (mParent != null)
20725                    && mOriginalWindowAttachCount == mWindowAttachCount) {
20726                if (performLongClick()) {
20727                    mHasPerformedLongPress = true;
20728                }
20729            }
20730        }
20731
20732        public void rememberWindowAttachCount() {
20733            mOriginalWindowAttachCount = mWindowAttachCount;
20734        }
20735    }
20736
20737    private final class CheckForTap implements Runnable {
20738        public float x;
20739        public float y;
20740
20741        @Override
20742        public void run() {
20743            mPrivateFlags &= ~PFLAG_PREPRESSED;
20744            setPressed(true, x, y);
20745            checkForLongClick(ViewConfiguration.getTapTimeout());
20746        }
20747    }
20748
20749    private final class PerformClick implements Runnable {
20750        @Override
20751        public void run() {
20752            performClick();
20753        }
20754    }
20755
20756    /** @hide */
20757    public void hackTurnOffWindowResizeAnim(boolean off) {
20758        mAttachInfo.mTurnOffWindowResizeAnim = off;
20759    }
20760
20761    /**
20762     * This method returns a ViewPropertyAnimator object, which can be used to animate
20763     * specific properties on this View.
20764     *
20765     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
20766     */
20767    public ViewPropertyAnimator animate() {
20768        if (mAnimator == null) {
20769            mAnimator = new ViewPropertyAnimator(this);
20770        }
20771        return mAnimator;
20772    }
20773
20774    /**
20775     * Sets the name of the View to be used to identify Views in Transitions.
20776     * Names should be unique in the View hierarchy.
20777     *
20778     * @param transitionName The name of the View to uniquely identify it for Transitions.
20779     */
20780    public final void setTransitionName(String transitionName) {
20781        mTransitionName = transitionName;
20782    }
20783
20784    /**
20785     * Returns the name of the View to be used to identify Views in Transitions.
20786     * Names should be unique in the View hierarchy.
20787     *
20788     * <p>This returns null if the View has not been given a name.</p>
20789     *
20790     * @return The name used of the View to be used to identify Views in Transitions or null
20791     * if no name has been given.
20792     */
20793    @ViewDebug.ExportedProperty
20794    public String getTransitionName() {
20795        return mTransitionName;
20796    }
20797
20798    /**
20799     * Interface definition for a callback to be invoked when a hardware key event is
20800     * dispatched to this view. The callback will be invoked before the key event is
20801     * given to the view. This is only useful for hardware keyboards; a software input
20802     * method has no obligation to trigger this listener.
20803     */
20804    public interface OnKeyListener {
20805        /**
20806         * Called when a hardware key is dispatched to a view. This allows listeners to
20807         * get a chance to respond before the target view.
20808         * <p>Key presses in software keyboards will generally NOT trigger this method,
20809         * although some may elect to do so in some situations. Do not assume a
20810         * software input method has to be key-based; even if it is, it may use key presses
20811         * in a different way than you expect, so there is no way to reliably catch soft
20812         * input key presses.
20813         *
20814         * @param v The view the key has been dispatched to.
20815         * @param keyCode The code for the physical key that was pressed
20816         * @param event The KeyEvent object containing full information about
20817         *        the event.
20818         * @return True if the listener has consumed the event, false otherwise.
20819         */
20820        boolean onKey(View v, int keyCode, KeyEvent event);
20821    }
20822
20823    /**
20824     * Interface definition for a callback to be invoked when a touch event is
20825     * dispatched to this view. The callback will be invoked before the touch
20826     * event is given to the view.
20827     */
20828    public interface OnTouchListener {
20829        /**
20830         * Called when a touch event is dispatched to a view. This allows listeners to
20831         * get a chance to respond before the target view.
20832         *
20833         * @param v The view the touch event has been dispatched to.
20834         * @param event The MotionEvent object containing full information about
20835         *        the event.
20836         * @return True if the listener has consumed the event, false otherwise.
20837         */
20838        boolean onTouch(View v, MotionEvent event);
20839    }
20840
20841    /**
20842     * Interface definition for a callback to be invoked when a hover event is
20843     * dispatched to this view. The callback will be invoked before the hover
20844     * event is given to the view.
20845     */
20846    public interface OnHoverListener {
20847        /**
20848         * Called when a hover event is dispatched to a view. This allows listeners to
20849         * get a chance to respond before the target view.
20850         *
20851         * @param v The view the hover event has been dispatched to.
20852         * @param event The MotionEvent object containing full information about
20853         *        the event.
20854         * @return True if the listener has consumed the event, false otherwise.
20855         */
20856        boolean onHover(View v, MotionEvent event);
20857    }
20858
20859    /**
20860     * Interface definition for a callback to be invoked when a generic motion event is
20861     * dispatched to this view. The callback will be invoked before the generic motion
20862     * event is given to the view.
20863     */
20864    public interface OnGenericMotionListener {
20865        /**
20866         * Called when a generic motion event is dispatched to a view. This allows listeners to
20867         * get a chance to respond before the target view.
20868         *
20869         * @param v The view the generic motion event has been dispatched to.
20870         * @param event The MotionEvent object containing full information about
20871         *        the event.
20872         * @return True if the listener has consumed the event, false otherwise.
20873         */
20874        boolean onGenericMotion(View v, MotionEvent event);
20875    }
20876
20877    /**
20878     * Interface definition for a callback to be invoked when a view has been clicked and held.
20879     */
20880    public interface OnLongClickListener {
20881        /**
20882         * Called when a view has been clicked and held.
20883         *
20884         * @param v The view that was clicked and held.
20885         *
20886         * @return true if the callback consumed the long click, false otherwise.
20887         */
20888        boolean onLongClick(View v);
20889    }
20890
20891    /**
20892     * Interface definition for a callback to be invoked when a drag is being dispatched
20893     * to this view.  The callback will be invoked before the hosting view's own
20894     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
20895     * onDrag(event) behavior, it should return 'false' from this callback.
20896     *
20897     * <div class="special reference">
20898     * <h3>Developer Guides</h3>
20899     * <p>For a guide to implementing drag and drop features, read the
20900     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
20901     * </div>
20902     */
20903    public interface OnDragListener {
20904        /**
20905         * Called when a drag event is dispatched to a view. This allows listeners
20906         * to get a chance to override base View behavior.
20907         *
20908         * @param v The View that received the drag event.
20909         * @param event The {@link android.view.DragEvent} object for the drag event.
20910         * @return {@code true} if the drag event was handled successfully, or {@code false}
20911         * if the drag event was not handled. Note that {@code false} will trigger the View
20912         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
20913         */
20914        boolean onDrag(View v, DragEvent event);
20915    }
20916
20917    /**
20918     * Interface definition for a callback to be invoked when the focus state of
20919     * a view changed.
20920     */
20921    public interface OnFocusChangeListener {
20922        /**
20923         * Called when the focus state of a view has changed.
20924         *
20925         * @param v The view whose state has changed.
20926         * @param hasFocus The new focus state of v.
20927         */
20928        void onFocusChange(View v, boolean hasFocus);
20929    }
20930
20931    /**
20932     * Interface definition for a callback to be invoked when a view is clicked.
20933     */
20934    public interface OnClickListener {
20935        /**
20936         * Called when a view has been clicked.
20937         *
20938         * @param v The view that was clicked.
20939         */
20940        void onClick(View v);
20941    }
20942
20943    /**
20944     * Interface definition for a callback to be invoked when a view is touched with a stylus while
20945     * the stylus button is pressed.
20946     */
20947    public interface OnStylusButtonPressListener {
20948        /**
20949         * Called when a view is touched with a stylus while the stylus button is pressed.
20950         *
20951         * @param v The view that was touched.
20952         * @return true if the callback consumed the stylus button press, false otherwise.
20953         */
20954        boolean onStylusButtonPress(View v);
20955    }
20956
20957    /**
20958     * Interface definition for a callback to be invoked when the context menu
20959     * for this view is being built.
20960     */
20961    public interface OnCreateContextMenuListener {
20962        /**
20963         * Called when the context menu for this view is being built. It is not
20964         * safe to hold onto the menu after this method returns.
20965         *
20966         * @param menu The context menu that is being built
20967         * @param v The view for which the context menu is being built
20968         * @param menuInfo Extra information about the item for which the
20969         *            context menu should be shown. This information will vary
20970         *            depending on the class of v.
20971         */
20972        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
20973    }
20974
20975    /**
20976     * Interface definition for a callback to be invoked when the status bar changes
20977     * visibility.  This reports <strong>global</strong> changes to the system UI
20978     * state, not what the application is requesting.
20979     *
20980     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
20981     */
20982    public interface OnSystemUiVisibilityChangeListener {
20983        /**
20984         * Called when the status bar changes visibility because of a call to
20985         * {@link View#setSystemUiVisibility(int)}.
20986         *
20987         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
20988         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
20989         * This tells you the <strong>global</strong> state of these UI visibility
20990         * flags, not what your app is currently applying.
20991         */
20992        public void onSystemUiVisibilityChange(int visibility);
20993    }
20994
20995    /**
20996     * Interface definition for a callback to be invoked when this view is attached
20997     * or detached from its window.
20998     */
20999    public interface OnAttachStateChangeListener {
21000        /**
21001         * Called when the view is attached to a window.
21002         * @param v The view that was attached
21003         */
21004        public void onViewAttachedToWindow(View v);
21005        /**
21006         * Called when the view is detached from a window.
21007         * @param v The view that was detached
21008         */
21009        public void onViewDetachedFromWindow(View v);
21010    }
21011
21012    /**
21013     * Listener for applying window insets on a view in a custom way.
21014     *
21015     * <p>Apps may choose to implement this interface if they want to apply custom policy
21016     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
21017     * is set, its
21018     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
21019     * method will be called instead of the View's own
21020     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
21021     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
21022     * the View's normal behavior as part of its own.</p>
21023     */
21024    public interface OnApplyWindowInsetsListener {
21025        /**
21026         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
21027         * on a View, this listener method will be called instead of the view's own
21028         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
21029         *
21030         * @param v The view applying window insets
21031         * @param insets The insets to apply
21032         * @return The insets supplied, minus any insets that were consumed
21033         */
21034        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
21035    }
21036
21037    private final class UnsetPressedState implements Runnable {
21038        @Override
21039        public void run() {
21040            setPressed(false);
21041        }
21042    }
21043
21044    /**
21045     * Base class for derived classes that want to save and restore their own
21046     * state in {@link android.view.View#onSaveInstanceState()}.
21047     */
21048    public static class BaseSavedState extends AbsSavedState {
21049        String mStartActivityRequestWhoSaved;
21050
21051        /**
21052         * Constructor used when reading from a parcel. Reads the state of the superclass.
21053         *
21054         * @param source
21055         */
21056        public BaseSavedState(Parcel source) {
21057            super(source);
21058            mStartActivityRequestWhoSaved = source.readString();
21059        }
21060
21061        /**
21062         * Constructor called by derived classes when creating their SavedState objects
21063         *
21064         * @param superState The state of the superclass of this view
21065         */
21066        public BaseSavedState(Parcelable superState) {
21067            super(superState);
21068        }
21069
21070        @Override
21071        public void writeToParcel(Parcel out, int flags) {
21072            super.writeToParcel(out, flags);
21073            out.writeString(mStartActivityRequestWhoSaved);
21074        }
21075
21076        public static final Parcelable.Creator<BaseSavedState> CREATOR =
21077                new Parcelable.Creator<BaseSavedState>() {
21078            public BaseSavedState createFromParcel(Parcel in) {
21079                return new BaseSavedState(in);
21080            }
21081
21082            public BaseSavedState[] newArray(int size) {
21083                return new BaseSavedState[size];
21084            }
21085        };
21086    }
21087
21088    /**
21089     * A set of information given to a view when it is attached to its parent
21090     * window.
21091     */
21092    final static class AttachInfo {
21093        interface Callbacks {
21094            void playSoundEffect(int effectId);
21095            boolean performHapticFeedback(int effectId, boolean always);
21096        }
21097
21098        /**
21099         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
21100         * to a Handler. This class contains the target (View) to invalidate and
21101         * the coordinates of the dirty rectangle.
21102         *
21103         * For performance purposes, this class also implements a pool of up to
21104         * POOL_LIMIT objects that get reused. This reduces memory allocations
21105         * whenever possible.
21106         */
21107        static class InvalidateInfo {
21108            private static final int POOL_LIMIT = 10;
21109
21110            private static final SynchronizedPool<InvalidateInfo> sPool =
21111                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
21112
21113            View target;
21114
21115            int left;
21116            int top;
21117            int right;
21118            int bottom;
21119
21120            public static InvalidateInfo obtain() {
21121                InvalidateInfo instance = sPool.acquire();
21122                return (instance != null) ? instance : new InvalidateInfo();
21123            }
21124
21125            public void recycle() {
21126                target = null;
21127                sPool.release(this);
21128            }
21129        }
21130
21131        final IWindowSession mSession;
21132
21133        final IWindow mWindow;
21134
21135        final IBinder mWindowToken;
21136
21137        final Display mDisplay;
21138
21139        final Callbacks mRootCallbacks;
21140
21141        IWindowId mIWindowId;
21142        WindowId mWindowId;
21143
21144        /**
21145         * The top view of the hierarchy.
21146         */
21147        View mRootView;
21148
21149        IBinder mPanelParentWindowToken;
21150
21151        boolean mHardwareAccelerated;
21152        boolean mHardwareAccelerationRequested;
21153        HardwareRenderer mHardwareRenderer;
21154        List<RenderNode> mPendingAnimatingRenderNodes;
21155
21156        /**
21157         * The state of the display to which the window is attached, as reported
21158         * by {@link Display#getState()}.  Note that the display state constants
21159         * declared by {@link Display} do not exactly line up with the screen state
21160         * constants declared by {@link View} (there are more display states than
21161         * screen states).
21162         */
21163        int mDisplayState = Display.STATE_UNKNOWN;
21164
21165        /**
21166         * Scale factor used by the compatibility mode
21167         */
21168        float mApplicationScale;
21169
21170        /**
21171         * Indicates whether the application is in compatibility mode
21172         */
21173        boolean mScalingRequired;
21174
21175        /**
21176         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
21177         */
21178        boolean mTurnOffWindowResizeAnim;
21179
21180        /**
21181         * Left position of this view's window
21182         */
21183        int mWindowLeft;
21184
21185        /**
21186         * Top position of this view's window
21187         */
21188        int mWindowTop;
21189
21190        /**
21191         * Indicates whether views need to use 32-bit drawing caches
21192         */
21193        boolean mUse32BitDrawingCache;
21194
21195        /**
21196         * For windows that are full-screen but using insets to layout inside
21197         * of the screen areas, these are the current insets to appear inside
21198         * the overscan area of the display.
21199         */
21200        final Rect mOverscanInsets = new Rect();
21201
21202        /**
21203         * For windows that are full-screen but using insets to layout inside
21204         * of the screen decorations, these are the current insets for the
21205         * content of the window.
21206         */
21207        final Rect mContentInsets = new Rect();
21208
21209        /**
21210         * For windows that are full-screen but using insets to layout inside
21211         * of the screen decorations, these are the current insets for the
21212         * actual visible parts of the window.
21213         */
21214        final Rect mVisibleInsets = new Rect();
21215
21216        /**
21217         * For windows that are full-screen but using insets to layout inside
21218         * of the screen decorations, these are the current insets for the
21219         * stable system windows.
21220         */
21221        final Rect mStableInsets = new Rect();
21222
21223        /**
21224         * The internal insets given by this window.  This value is
21225         * supplied by the client (through
21226         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
21227         * be given to the window manager when changed to be used in laying
21228         * out windows behind it.
21229         */
21230        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
21231                = new ViewTreeObserver.InternalInsetsInfo();
21232
21233        /**
21234         * Set to true when mGivenInternalInsets is non-empty.
21235         */
21236        boolean mHasNonEmptyGivenInternalInsets;
21237
21238        /**
21239         * All views in the window's hierarchy that serve as scroll containers,
21240         * used to determine if the window can be resized or must be panned
21241         * to adjust for a soft input area.
21242         */
21243        final ArrayList<View> mScrollContainers = new ArrayList<View>();
21244
21245        final KeyEvent.DispatcherState mKeyDispatchState
21246                = new KeyEvent.DispatcherState();
21247
21248        /**
21249         * Indicates whether the view's window currently has the focus.
21250         */
21251        boolean mHasWindowFocus;
21252
21253        /**
21254         * The current visibility of the window.
21255         */
21256        int mWindowVisibility;
21257
21258        /**
21259         * Indicates the time at which drawing started to occur.
21260         */
21261        long mDrawingTime;
21262
21263        /**
21264         * Indicates whether or not ignoring the DIRTY_MASK flags.
21265         */
21266        boolean mIgnoreDirtyState;
21267
21268        /**
21269         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
21270         * to avoid clearing that flag prematurely.
21271         */
21272        boolean mSetIgnoreDirtyState = false;
21273
21274        /**
21275         * Indicates whether the view's window is currently in touch mode.
21276         */
21277        boolean mInTouchMode;
21278
21279        /**
21280         * Indicates whether the view has requested unbuffered input dispatching for the current
21281         * event stream.
21282         */
21283        boolean mUnbufferedDispatchRequested;
21284
21285        /**
21286         * Indicates that ViewAncestor should trigger a global layout change
21287         * the next time it performs a traversal
21288         */
21289        boolean mRecomputeGlobalAttributes;
21290
21291        /**
21292         * Always report new attributes at next traversal.
21293         */
21294        boolean mForceReportNewAttributes;
21295
21296        /**
21297         * Set during a traveral if any views want to keep the screen on.
21298         */
21299        boolean mKeepScreenOn;
21300
21301        /**
21302         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
21303         */
21304        int mSystemUiVisibility;
21305
21306        /**
21307         * Hack to force certain system UI visibility flags to be cleared.
21308         */
21309        int mDisabledSystemUiVisibility;
21310
21311        /**
21312         * Last global system UI visibility reported by the window manager.
21313         */
21314        int mGlobalSystemUiVisibility;
21315
21316        /**
21317         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
21318         * attached.
21319         */
21320        boolean mHasSystemUiListeners;
21321
21322        /**
21323         * Set if the window has requested to extend into the overscan region
21324         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
21325         */
21326        boolean mOverscanRequested;
21327
21328        /**
21329         * Set if the visibility of any views has changed.
21330         */
21331        boolean mViewVisibilityChanged;
21332
21333        /**
21334         * Set to true if a view has been scrolled.
21335         */
21336        boolean mViewScrollChanged;
21337
21338        /**
21339         * Set to true if high contrast mode enabled
21340         */
21341        boolean mHighContrastText;
21342
21343        /**
21344         * Global to the view hierarchy used as a temporary for dealing with
21345         * x/y points in the transparent region computations.
21346         */
21347        final int[] mTransparentLocation = new int[2];
21348
21349        /**
21350         * Global to the view hierarchy used as a temporary for dealing with
21351         * x/y points in the ViewGroup.invalidateChild implementation.
21352         */
21353        final int[] mInvalidateChildLocation = new int[2];
21354
21355        /**
21356         * Global to the view hierarchy used as a temporary for dealng with
21357         * computing absolute on-screen location.
21358         */
21359        final int[] mTmpLocation = new int[2];
21360
21361        /**
21362         * Global to the view hierarchy used as a temporary for dealing with
21363         * x/y location when view is transformed.
21364         */
21365        final float[] mTmpTransformLocation = new float[2];
21366
21367        /**
21368         * The view tree observer used to dispatch global events like
21369         * layout, pre-draw, touch mode change, etc.
21370         */
21371        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
21372
21373        /**
21374         * A Canvas used by the view hierarchy to perform bitmap caching.
21375         */
21376        Canvas mCanvas;
21377
21378        /**
21379         * The view root impl.
21380         */
21381        final ViewRootImpl mViewRootImpl;
21382
21383        /**
21384         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
21385         * handler can be used to pump events in the UI events queue.
21386         */
21387        final Handler mHandler;
21388
21389        /**
21390         * Temporary for use in computing invalidate rectangles while
21391         * calling up the hierarchy.
21392         */
21393        final Rect mTmpInvalRect = new Rect();
21394
21395        /**
21396         * Temporary for use in computing hit areas with transformed views
21397         */
21398        final RectF mTmpTransformRect = new RectF();
21399
21400        /**
21401         * Temporary for use in computing hit areas with transformed views
21402         */
21403        final RectF mTmpTransformRect1 = new RectF();
21404
21405        /**
21406         * Temporary list of rectanges.
21407         */
21408        final List<RectF> mTmpRectList = new ArrayList<>();
21409
21410        /**
21411         * Temporary for use in transforming invalidation rect
21412         */
21413        final Matrix mTmpMatrix = new Matrix();
21414
21415        /**
21416         * Temporary for use in transforming invalidation rect
21417         */
21418        final Transformation mTmpTransformation = new Transformation();
21419
21420        /**
21421         * Temporary for use in querying outlines from OutlineProviders
21422         */
21423        final Outline mTmpOutline = new Outline();
21424
21425        /**
21426         * Temporary list for use in collecting focusable descendents of a view.
21427         */
21428        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
21429
21430        /**
21431         * The id of the window for accessibility purposes.
21432         */
21433        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
21434
21435        /**
21436         * Flags related to accessibility processing.
21437         *
21438         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
21439         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
21440         */
21441        int mAccessibilityFetchFlags;
21442
21443        /**
21444         * The drawable for highlighting accessibility focus.
21445         */
21446        Drawable mAccessibilityFocusDrawable;
21447
21448        /**
21449         * Show where the margins, bounds and layout bounds are for each view.
21450         */
21451        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
21452
21453        /**
21454         * Point used to compute visible regions.
21455         */
21456        final Point mPoint = new Point();
21457
21458        /**
21459         * Used to track which View originated a requestLayout() call, used when
21460         * requestLayout() is called during layout.
21461         */
21462        View mViewRequestingLayout;
21463
21464        /**
21465         * Creates a new set of attachment information with the specified
21466         * events handler and thread.
21467         *
21468         * @param handler the events handler the view must use
21469         */
21470        AttachInfo(IWindowSession session, IWindow window, Display display,
21471                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
21472            mSession = session;
21473            mWindow = window;
21474            mWindowToken = window.asBinder();
21475            mDisplay = display;
21476            mViewRootImpl = viewRootImpl;
21477            mHandler = handler;
21478            mRootCallbacks = effectPlayer;
21479        }
21480    }
21481
21482    /**
21483     * <p>ScrollabilityCache holds various fields used by a View when scrolling
21484     * is supported. This avoids keeping too many unused fields in most
21485     * instances of View.</p>
21486     */
21487    private static class ScrollabilityCache implements Runnable {
21488
21489        /**
21490         * Scrollbars are not visible
21491         */
21492        public static final int OFF = 0;
21493
21494        /**
21495         * Scrollbars are visible
21496         */
21497        public static final int ON = 1;
21498
21499        /**
21500         * Scrollbars are fading away
21501         */
21502        public static final int FADING = 2;
21503
21504        public boolean fadeScrollBars;
21505
21506        public int fadingEdgeLength;
21507        public int scrollBarDefaultDelayBeforeFade;
21508        public int scrollBarFadeDuration;
21509
21510        public int scrollBarSize;
21511        public ScrollBarDrawable scrollBar;
21512        public float[] interpolatorValues;
21513        public View host;
21514
21515        public final Paint paint;
21516        public final Matrix matrix;
21517        public Shader shader;
21518
21519        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
21520
21521        private static final float[] OPAQUE = { 255 };
21522        private static final float[] TRANSPARENT = { 0.0f };
21523
21524        /**
21525         * When fading should start. This time moves into the future every time
21526         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
21527         */
21528        public long fadeStartTime;
21529
21530
21531        /**
21532         * The current state of the scrollbars: ON, OFF, or FADING
21533         */
21534        public int state = OFF;
21535
21536        private int mLastColor;
21537
21538        public ScrollabilityCache(ViewConfiguration configuration, View host) {
21539            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
21540            scrollBarSize = configuration.getScaledScrollBarSize();
21541            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
21542            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
21543
21544            paint = new Paint();
21545            matrix = new Matrix();
21546            // use use a height of 1, and then wack the matrix each time we
21547            // actually use it.
21548            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21549            paint.setShader(shader);
21550            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21551
21552            this.host = host;
21553        }
21554
21555        public void setFadeColor(int color) {
21556            if (color != mLastColor) {
21557                mLastColor = color;
21558
21559                if (color != 0) {
21560                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
21561                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
21562                    paint.setShader(shader);
21563                    // Restore the default transfer mode (src_over)
21564                    paint.setXfermode(null);
21565                } else {
21566                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
21567                    paint.setShader(shader);
21568                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
21569                }
21570            }
21571        }
21572
21573        public void run() {
21574            long now = AnimationUtils.currentAnimationTimeMillis();
21575            if (now >= fadeStartTime) {
21576
21577                // the animation fades the scrollbars out by changing
21578                // the opacity (alpha) from fully opaque to fully
21579                // transparent
21580                int nextFrame = (int) now;
21581                int framesCount = 0;
21582
21583                Interpolator interpolator = scrollBarInterpolator;
21584
21585                // Start opaque
21586                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
21587
21588                // End transparent
21589                nextFrame += scrollBarFadeDuration;
21590                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
21591
21592                state = FADING;
21593
21594                // Kick off the fade animation
21595                host.invalidate(true);
21596            }
21597        }
21598    }
21599
21600    /**
21601     * Resuable callback for sending
21602     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
21603     */
21604    private class SendViewScrolledAccessibilityEvent implements Runnable {
21605        public volatile boolean mIsPending;
21606
21607        public void run() {
21608            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
21609            mIsPending = false;
21610        }
21611    }
21612
21613    /**
21614     * <p>
21615     * This class represents a delegate that can be registered in a {@link View}
21616     * to enhance accessibility support via composition rather via inheritance.
21617     * It is specifically targeted to widget developers that extend basic View
21618     * classes i.e. classes in package android.view, that would like their
21619     * applications to be backwards compatible.
21620     * </p>
21621     * <div class="special reference">
21622     * <h3>Developer Guides</h3>
21623     * <p>For more information about making applications accessible, read the
21624     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
21625     * developer guide.</p>
21626     * </div>
21627     * <p>
21628     * A scenario in which a developer would like to use an accessibility delegate
21629     * is overriding a method introduced in a later API version then the minimal API
21630     * version supported by the application. For example, the method
21631     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
21632     * in API version 4 when the accessibility APIs were first introduced. If a
21633     * developer would like his application to run on API version 4 devices (assuming
21634     * all other APIs used by the application are version 4 or lower) and take advantage
21635     * of this method, instead of overriding the method which would break the application's
21636     * backwards compatibility, he can override the corresponding method in this
21637     * delegate and register the delegate in the target View if the API version of
21638     * the system is high enough i.e. the API version is same or higher to the API
21639     * version that introduced
21640     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
21641     * </p>
21642     * <p>
21643     * Here is an example implementation:
21644     * </p>
21645     * <code><pre><p>
21646     * if (Build.VERSION.SDK_INT >= 14) {
21647     *     // If the API version is equal of higher than the version in
21648     *     // which onInitializeAccessibilityNodeInfo was introduced we
21649     *     // register a delegate with a customized implementation.
21650     *     View view = findViewById(R.id.view_id);
21651     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
21652     *         public void onInitializeAccessibilityNodeInfo(View host,
21653     *                 AccessibilityNodeInfo info) {
21654     *             // Let the default implementation populate the info.
21655     *             super.onInitializeAccessibilityNodeInfo(host, info);
21656     *             // Set some other information.
21657     *             info.setEnabled(host.isEnabled());
21658     *         }
21659     *     });
21660     * }
21661     * </code></pre></p>
21662     * <p>
21663     * This delegate contains methods that correspond to the accessibility methods
21664     * in View. If a delegate has been specified the implementation in View hands
21665     * off handling to the corresponding method in this delegate. The default
21666     * implementation the delegate methods behaves exactly as the corresponding
21667     * method in View for the case of no accessibility delegate been set. Hence,
21668     * to customize the behavior of a View method, clients can override only the
21669     * corresponding delegate method without altering the behavior of the rest
21670     * accessibility related methods of the host view.
21671     * </p>
21672     */
21673    public static class AccessibilityDelegate {
21674
21675        /**
21676         * Sends an accessibility event of the given type. If accessibility is not
21677         * enabled this method has no effect.
21678         * <p>
21679         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
21680         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
21681         * been set.
21682         * </p>
21683         *
21684         * @param host The View hosting the delegate.
21685         * @param eventType The type of the event to send.
21686         *
21687         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
21688         */
21689        public void sendAccessibilityEvent(View host, int eventType) {
21690            host.sendAccessibilityEventInternal(eventType);
21691        }
21692
21693        /**
21694         * Performs the specified accessibility action on the view. For
21695         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
21696         * <p>
21697         * The default implementation behaves as
21698         * {@link View#performAccessibilityAction(int, Bundle)
21699         *  View#performAccessibilityAction(int, Bundle)} for the case of
21700         *  no accessibility delegate been set.
21701         * </p>
21702         *
21703         * @param action The action to perform.
21704         * @return Whether the action was performed.
21705         *
21706         * @see View#performAccessibilityAction(int, Bundle)
21707         *      View#performAccessibilityAction(int, Bundle)
21708         */
21709        public boolean performAccessibilityAction(View host, int action, Bundle args) {
21710            return host.performAccessibilityActionInternal(action, args);
21711        }
21712
21713        /**
21714         * Sends an accessibility event. This method behaves exactly as
21715         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
21716         * empty {@link AccessibilityEvent} and does not perform a check whether
21717         * accessibility is enabled.
21718         * <p>
21719         * The default implementation behaves as
21720         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21721         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
21722         * the case of no accessibility delegate been set.
21723         * </p>
21724         *
21725         * @param host The View hosting the delegate.
21726         * @param event The event to send.
21727         *
21728         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21729         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
21730         */
21731        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
21732            host.sendAccessibilityEventUncheckedInternal(event);
21733        }
21734
21735        /**
21736         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
21737         * to its children for adding their text content to the event.
21738         * <p>
21739         * The default implementation behaves as
21740         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21741         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
21742         * the case of no accessibility delegate been set.
21743         * </p>
21744         *
21745         * @param host The View hosting the delegate.
21746         * @param event The event.
21747         * @return True if the event population was completed.
21748         *
21749         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21750         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
21751         */
21752        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21753            return host.dispatchPopulateAccessibilityEventInternal(event);
21754        }
21755
21756        /**
21757         * Gives a chance to the host View to populate the accessibility event with its
21758         * text content.
21759         * <p>
21760         * The default implementation behaves as
21761         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
21762         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
21763         * the case of no accessibility delegate been set.
21764         * </p>
21765         *
21766         * @param host The View hosting the delegate.
21767         * @param event The accessibility event which to populate.
21768         *
21769         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
21770         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
21771         */
21772        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
21773            host.onPopulateAccessibilityEventInternal(event);
21774        }
21775
21776        /**
21777         * Initializes an {@link AccessibilityEvent} with information about the
21778         * the host View which is the event source.
21779         * <p>
21780         * The default implementation behaves as
21781         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
21782         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
21783         * the case of no accessibility delegate been set.
21784         * </p>
21785         *
21786         * @param host The View hosting the delegate.
21787         * @param event The event to initialize.
21788         *
21789         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
21790         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
21791         */
21792        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
21793            host.onInitializeAccessibilityEventInternal(event);
21794        }
21795
21796        /**
21797         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
21798         * <p>
21799         * The default implementation behaves as
21800         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21801         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
21802         * the case of no accessibility delegate been set.
21803         * </p>
21804         *
21805         * @param host The View hosting the delegate.
21806         * @param info The instance to initialize.
21807         *
21808         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21809         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
21810         */
21811        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
21812            host.onInitializeAccessibilityNodeInfoInternal(info);
21813        }
21814
21815        /**
21816         * Called when a child of the host View has requested sending an
21817         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
21818         * to augment the event.
21819         * <p>
21820         * The default implementation behaves as
21821         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21822         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
21823         * the case of no accessibility delegate been set.
21824         * </p>
21825         *
21826         * @param host The View hosting the delegate.
21827         * @param child The child which requests sending the event.
21828         * @param event The event to be sent.
21829         * @return True if the event should be sent
21830         *
21831         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21832         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
21833         */
21834        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
21835                AccessibilityEvent event) {
21836            return host.onRequestSendAccessibilityEventInternal(child, event);
21837        }
21838
21839        /**
21840         * Gets the provider for managing a virtual view hierarchy rooted at this View
21841         * and reported to {@link android.accessibilityservice.AccessibilityService}s
21842         * that explore the window content.
21843         * <p>
21844         * The default implementation behaves as
21845         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
21846         * the case of no accessibility delegate been set.
21847         * </p>
21848         *
21849         * @return The provider.
21850         *
21851         * @see AccessibilityNodeProvider
21852         */
21853        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
21854            return null;
21855        }
21856
21857        /**
21858         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
21859         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
21860         * This method is responsible for obtaining an accessibility node info from a
21861         * pool of reusable instances and calling
21862         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
21863         * view to initialize the former.
21864         * <p>
21865         * <strong>Note:</strong> The client is responsible for recycling the obtained
21866         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
21867         * creation.
21868         * </p>
21869         * <p>
21870         * The default implementation behaves as
21871         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
21872         * the case of no accessibility delegate been set.
21873         * </p>
21874         * @return A populated {@link AccessibilityNodeInfo}.
21875         *
21876         * @see AccessibilityNodeInfo
21877         *
21878         * @hide
21879         */
21880        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
21881            return host.createAccessibilityNodeInfoInternal();
21882        }
21883    }
21884
21885    private class MatchIdPredicate implements Predicate<View> {
21886        public int mId;
21887
21888        @Override
21889        public boolean apply(View view) {
21890            return (view.mID == mId);
21891        }
21892    }
21893
21894    private class MatchLabelForPredicate implements Predicate<View> {
21895        private int mLabeledId;
21896
21897        @Override
21898        public boolean apply(View view) {
21899            return (view.mLabelForId == mLabeledId);
21900        }
21901    }
21902
21903    private class SendViewStateChangedAccessibilityEvent implements Runnable {
21904        private int mChangeTypes = 0;
21905        private boolean mPosted;
21906        private boolean mPostedWithDelay;
21907        private long mLastEventTimeMillis;
21908
21909        @Override
21910        public void run() {
21911            mPosted = false;
21912            mPostedWithDelay = false;
21913            mLastEventTimeMillis = SystemClock.uptimeMillis();
21914            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
21915                final AccessibilityEvent event = AccessibilityEvent.obtain();
21916                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
21917                event.setContentChangeTypes(mChangeTypes);
21918                sendAccessibilityEventUnchecked(event);
21919            }
21920            mChangeTypes = 0;
21921        }
21922
21923        public void runOrPost(int changeType) {
21924            mChangeTypes |= changeType;
21925
21926            // If this is a live region or the child of a live region, collect
21927            // all events from this frame and send them on the next frame.
21928            if (inLiveRegion()) {
21929                // If we're already posted with a delay, remove that.
21930                if (mPostedWithDelay) {
21931                    removeCallbacks(this);
21932                    mPostedWithDelay = false;
21933                }
21934                // Only post if we're not already posted.
21935                if (!mPosted) {
21936                    post(this);
21937                    mPosted = true;
21938                }
21939                return;
21940            }
21941
21942            if (mPosted) {
21943                return;
21944            }
21945
21946            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
21947            final long minEventIntevalMillis =
21948                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
21949            if (timeSinceLastMillis >= minEventIntevalMillis) {
21950                removeCallbacks(this);
21951                run();
21952            } else {
21953                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
21954                mPostedWithDelay = true;
21955            }
21956        }
21957    }
21958
21959    private boolean inLiveRegion() {
21960        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21961            return true;
21962        }
21963
21964        ViewParent parent = getParent();
21965        while (parent instanceof View) {
21966            if (((View) parent).getAccessibilityLiveRegion()
21967                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
21968                return true;
21969            }
21970            parent = parent.getParent();
21971        }
21972
21973        return false;
21974    }
21975
21976    /**
21977     * Dump all private flags in readable format, useful for documentation and
21978     * sanity checking.
21979     */
21980    private static void dumpFlags() {
21981        final HashMap<String, String> found = Maps.newHashMap();
21982        try {
21983            for (Field field : View.class.getDeclaredFields()) {
21984                final int modifiers = field.getModifiers();
21985                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
21986                    if (field.getType().equals(int.class)) {
21987                        final int value = field.getInt(null);
21988                        dumpFlag(found, field.getName(), value);
21989                    } else if (field.getType().equals(int[].class)) {
21990                        final int[] values = (int[]) field.get(null);
21991                        for (int i = 0; i < values.length; i++) {
21992                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
21993                        }
21994                    }
21995                }
21996            }
21997        } catch (IllegalAccessException e) {
21998            throw new RuntimeException(e);
21999        }
22000
22001        final ArrayList<String> keys = Lists.newArrayList();
22002        keys.addAll(found.keySet());
22003        Collections.sort(keys);
22004        for (String key : keys) {
22005            Log.d(VIEW_LOG_TAG, found.get(key));
22006        }
22007    }
22008
22009    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
22010        // Sort flags by prefix, then by bits, always keeping unique keys
22011        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
22012        final int prefix = name.indexOf('_');
22013        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
22014        final String output = bits + " " + name;
22015        found.put(key, output);
22016    }
22017}
22018