View.java revision f86cb678a5afd94505c42497817e7f63427683b9
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.IntDef;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.content.ClipData;
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.content.res.TypedArray;
30import android.graphics.Bitmap;
31import android.graphics.Canvas;
32import android.graphics.Insets;
33import android.graphics.Interpolator;
34import android.graphics.LinearGradient;
35import android.graphics.Matrix;
36import android.graphics.Outline;
37import android.graphics.Paint;
38import android.graphics.PixelFormat;
39import android.graphics.Point;
40import android.graphics.PorterDuff;
41import android.graphics.PorterDuffXfermode;
42import android.graphics.Rect;
43import android.graphics.RectF;
44import android.graphics.Region;
45import android.graphics.Shader;
46import android.graphics.drawable.ColorDrawable;
47import android.graphics.drawable.Drawable;
48import android.hardware.display.DisplayManagerGlobal;
49import android.os.Bundle;
50import android.os.Handler;
51import android.os.IBinder;
52import android.os.Parcel;
53import android.os.Parcelable;
54import android.os.RemoteException;
55import android.os.SystemClock;
56import android.os.SystemProperties;
57import android.text.TextUtils;
58import android.util.AttributeSet;
59import android.util.FloatProperty;
60import android.util.LayoutDirection;
61import android.util.Log;
62import android.util.LongSparseLongArray;
63import android.util.Pools.SynchronizedPool;
64import android.util.Property;
65import android.util.SparseArray;
66import android.util.SuperNotCalledException;
67import android.util.TypedValue;
68import android.view.ContextMenu.ContextMenuInfo;
69import android.view.AccessibilityIterators.TextSegmentIterator;
70import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
71import android.view.AccessibilityIterators.WordTextSegmentIterator;
72import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
73import android.view.accessibility.AccessibilityEvent;
74import android.view.accessibility.AccessibilityEventSource;
75import android.view.accessibility.AccessibilityManager;
76import android.view.accessibility.AccessibilityNodeInfo;
77import android.view.accessibility.AccessibilityNodeProvider;
78import android.view.animation.Animation;
79import android.view.animation.AnimationUtils;
80import android.view.animation.Transformation;
81import android.view.inputmethod.EditorInfo;
82import android.view.inputmethod.InputConnection;
83import android.view.inputmethod.InputMethodManager;
84import android.widget.ScrollBarDrawable;
85
86import static android.os.Build.VERSION_CODES.*;
87import static java.lang.Math.max;
88
89import com.android.internal.R;
90import com.android.internal.util.Predicate;
91import com.android.internal.view.menu.MenuBuilder;
92import com.google.android.collect.Lists;
93import com.google.android.collect.Maps;
94
95import java.lang.annotation.Retention;
96import java.lang.annotation.RetentionPolicy;
97import java.lang.ref.WeakReference;
98import java.lang.reflect.Field;
99import java.lang.reflect.InvocationTargetException;
100import java.lang.reflect.Method;
101import java.lang.reflect.Modifier;
102import java.util.ArrayList;
103import java.util.Arrays;
104import java.util.Collections;
105import java.util.HashMap;
106import java.util.List;
107import java.util.Locale;
108import java.util.Map;
109import java.util.concurrent.CopyOnWriteArrayList;
110import java.util.concurrent.atomic.AtomicInteger;
111
112/**
113 * <p>
114 * This class represents the basic building block for user interface components. A View
115 * occupies a rectangular area on the screen and is responsible for drawing and
116 * event handling. View is the base class for <em>widgets</em>, which are
117 * used to create interactive UI components (buttons, text fields, etc.). The
118 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
119 * are invisible containers that hold other Views (or other ViewGroups) and define
120 * their layout properties.
121 * </p>
122 *
123 * <div class="special reference">
124 * <h3>Developer Guides</h3>
125 * <p>For information about using this class to develop your application's user interface,
126 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
127 * </div>
128 *
129 * <a name="Using"></a>
130 * <h3>Using Views</h3>
131 * <p>
132 * All of the views in a window are arranged in a single tree. You can add views
133 * either from code or by specifying a tree of views in one or more XML layout
134 * files. There are many specialized subclasses of views that act as controls or
135 * are capable of displaying text, images, or other content.
136 * </p>
137 * <p>
138 * Once you have created a tree of views, there are typically a few types of
139 * common operations you may wish to perform:
140 * <ul>
141 * <li><strong>Set properties:</strong> for example setting the text of a
142 * {@link android.widget.TextView}. The available properties and the methods
143 * that set them will vary among the different subclasses of views. Note that
144 * properties that are known at build time can be set in the XML layout
145 * files.</li>
146 * <li><strong>Set focus:</strong> The framework will handled moving focus in
147 * response to user input. To force focus to a specific view, call
148 * {@link #requestFocus}.</li>
149 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
150 * that will be notified when something interesting happens to the view. For
151 * example, all views will let you set a listener to be notified when the view
152 * gains or loses focus. You can register such a listener using
153 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
154 * Other view subclasses offer more specialized listeners. For example, a Button
155 * exposes a listener to notify clients when the button is clicked.</li>
156 * <li><strong>Set visibility:</strong> You can hide or show views using
157 * {@link #setVisibility(int)}.</li>
158 * </ul>
159 * </p>
160 * <p><em>
161 * Note: The Android framework is responsible for measuring, laying out and
162 * drawing views. You should not call methods that perform these actions on
163 * views yourself unless you are actually implementing a
164 * {@link android.view.ViewGroup}.
165 * </em></p>
166 *
167 * <a name="Lifecycle"></a>
168 * <h3>Implementing a Custom View</h3>
169 *
170 * <p>
171 * To implement a custom view, you will usually begin by providing overrides for
172 * some of the standard methods that the framework calls on all views. You do
173 * not need to override all of these methods. In fact, you can start by just
174 * overriding {@link #onDraw(android.graphics.Canvas)}.
175 * <table border="2" width="85%" align="center" cellpadding="5">
176 *     <thead>
177 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
178 *     </thead>
179 *
180 *     <tbody>
181 *     <tr>
182 *         <td rowspan="2">Creation</td>
183 *         <td>Constructors</td>
184 *         <td>There is a form of the constructor that are called when the view
185 *         is created from code and a form that is called when the view is
186 *         inflated from a layout file. The second form should parse and apply
187 *         any attributes defined in the layout file.
188 *         </td>
189 *     </tr>
190 *     <tr>
191 *         <td><code>{@link #onFinishInflate()}</code></td>
192 *         <td>Called after a view and all of its children has been inflated
193 *         from XML.</td>
194 *     </tr>
195 *
196 *     <tr>
197 *         <td rowspan="3">Layout</td>
198 *         <td><code>{@link #onMeasure(int, int)}</code></td>
199 *         <td>Called to determine the size requirements for this view and all
200 *         of its children.
201 *         </td>
202 *     </tr>
203 *     <tr>
204 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
205 *         <td>Called when this view should assign a size and position to all
206 *         of its children.
207 *         </td>
208 *     </tr>
209 *     <tr>
210 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
211 *         <td>Called when the size of this view has changed.
212 *         </td>
213 *     </tr>
214 *
215 *     <tr>
216 *         <td>Drawing</td>
217 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
218 *         <td>Called when the view should render its content.
219 *         </td>
220 *     </tr>
221 *
222 *     <tr>
223 *         <td rowspan="4">Event processing</td>
224 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
225 *         <td>Called when a new hardware key event occurs.
226 *         </td>
227 *     </tr>
228 *     <tr>
229 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
230 *         <td>Called when a hardware key up event occurs.
231 *         </td>
232 *     </tr>
233 *     <tr>
234 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
235 *         <td>Called when a trackball motion event occurs.
236 *         </td>
237 *     </tr>
238 *     <tr>
239 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
240 *         <td>Called when a touch screen motion event occurs.
241 *         </td>
242 *     </tr>
243 *
244 *     <tr>
245 *         <td rowspan="2">Focus</td>
246 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
247 *         <td>Called when the view gains or loses focus.
248 *         </td>
249 *     </tr>
250 *
251 *     <tr>
252 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
253 *         <td>Called when the window containing the view gains or loses focus.
254 *         </td>
255 *     </tr>
256 *
257 *     <tr>
258 *         <td rowspan="3">Attaching</td>
259 *         <td><code>{@link #onAttachedToWindow()}</code></td>
260 *         <td>Called when the view is attached to a window.
261 *         </td>
262 *     </tr>
263 *
264 *     <tr>
265 *         <td><code>{@link #onDetachedFromWindow}</code></td>
266 *         <td>Called when the view is detached from its window.
267 *         </td>
268 *     </tr>
269 *
270 *     <tr>
271 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
272 *         <td>Called when the visibility of the window containing the view
273 *         has changed.
274 *         </td>
275 *     </tr>
276 *     </tbody>
277 *
278 * </table>
279 * </p>
280 *
281 * <a name="IDs"></a>
282 * <h3>IDs</h3>
283 * Views may have an integer id associated with them. These ids are typically
284 * assigned in the layout XML files, and are used to find specific views within
285 * the view tree. A common pattern is to:
286 * <ul>
287 * <li>Define a Button in the layout file and assign it a unique ID.
288 * <pre>
289 * &lt;Button
290 *     android:id="@+id/my_button"
291 *     android:layout_width="wrap_content"
292 *     android:layout_height="wrap_content"
293 *     android:text="@string/my_button_text"/&gt;
294 * </pre></li>
295 * <li>From the onCreate method of an Activity, find the Button
296 * <pre class="prettyprint">
297 *      Button myButton = (Button) findViewById(R.id.my_button);
298 * </pre></li>
299 * </ul>
300 * <p>
301 * View IDs need not be unique throughout the tree, but it is good practice to
302 * ensure that they are at least unique within the part of the tree you are
303 * searching.
304 * </p>
305 *
306 * <a name="Position"></a>
307 * <h3>Position</h3>
308 * <p>
309 * The geometry of a view is that of a rectangle. A view has a location,
310 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
311 * two dimensions, expressed as a width and a height. The unit for location
312 * and dimensions is the pixel.
313 * </p>
314 *
315 * <p>
316 * It is possible to retrieve the location of a view by invoking the methods
317 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
318 * coordinate of the rectangle representing the view. The latter returns the
319 * top, or Y, coordinate of the rectangle representing the view. These methods
320 * both return the location of the view relative to its parent. For instance,
321 * when getLeft() returns 20, that means the view is located 20 pixels to the
322 * right of the left edge of its direct parent.
323 * </p>
324 *
325 * <p>
326 * In addition, several convenience methods are offered to avoid unnecessary
327 * computations, namely {@link #getRight()} and {@link #getBottom()}.
328 * These methods return the coordinates of the right and bottom edges of the
329 * rectangle representing the view. For instance, calling {@link #getRight()}
330 * is similar to the following computation: <code>getLeft() + getWidth()</code>
331 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
332 * </p>
333 *
334 * <a name="SizePaddingMargins"></a>
335 * <h3>Size, padding and margins</h3>
336 * <p>
337 * The size of a view is expressed with a width and a height. A view actually
338 * possess two pairs of width and height values.
339 * </p>
340 *
341 * <p>
342 * The first pair is known as <em>measured width</em> and
343 * <em>measured height</em>. These dimensions define how big a view wants to be
344 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
345 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
346 * and {@link #getMeasuredHeight()}.
347 * </p>
348 *
349 * <p>
350 * The second pair is simply known as <em>width</em> and <em>height</em>, or
351 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
352 * dimensions define the actual size of the view on screen, at drawing time and
353 * after layout. These values may, but do not have to, be different from the
354 * measured width and height. The width and height can be obtained by calling
355 * {@link #getWidth()} and {@link #getHeight()}.
356 * </p>
357 *
358 * <p>
359 * To measure its dimensions, a view takes into account its padding. The padding
360 * is expressed in pixels for the left, top, right and bottom parts of the view.
361 * Padding can be used to offset the content of the view by a specific amount of
362 * pixels. For instance, a left padding of 2 will push the view's content by
363 * 2 pixels to the right of the left edge. Padding can be set using the
364 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
365 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
366 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
367 * {@link #getPaddingEnd()}.
368 * </p>
369 *
370 * <p>
371 * Even though a view can define a padding, it does not provide any support for
372 * margins. However, view groups provide such a support. Refer to
373 * {@link android.view.ViewGroup} and
374 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
375 * </p>
376 *
377 * <a name="Layout"></a>
378 * <h3>Layout</h3>
379 * <p>
380 * Layout is a two pass process: a measure pass and a layout pass. The measuring
381 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
382 * of the view tree. Each view pushes dimension specifications down the tree
383 * during the recursion. At the end of the measure pass, every view has stored
384 * its measurements. The second pass happens in
385 * {@link #layout(int,int,int,int)} and is also top-down. During
386 * this pass each parent is responsible for positioning all of its children
387 * using the sizes computed in the measure pass.
388 * </p>
389 *
390 * <p>
391 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
392 * {@link #getMeasuredHeight()} values must be set, along with those for all of
393 * that view's descendants. A view's measured width and measured height values
394 * must respect the constraints imposed by the view's parents. This guarantees
395 * that at the end of the measure pass, all parents accept all of their
396 * children's measurements. A parent view may call measure() more than once on
397 * its children. For example, the parent may measure each child once with
398 * unspecified dimensions to find out how big they want to be, then call
399 * measure() on them again with actual numbers if the sum of all the children's
400 * unconstrained sizes is too big or too small.
401 * </p>
402 *
403 * <p>
404 * The measure pass uses two classes to communicate dimensions. The
405 * {@link MeasureSpec} class is used by views to tell their parents how they
406 * want to be measured and positioned. The base LayoutParams class just
407 * describes how big the view wants to be for both width and height. For each
408 * dimension, it can specify one of:
409 * <ul>
410 * <li> an exact number
411 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
412 * (minus padding)
413 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
414 * enclose its content (plus padding).
415 * </ul>
416 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
417 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
418 * an X and Y value.
419 * </p>
420 *
421 * <p>
422 * MeasureSpecs are used to push requirements down the tree from parent to
423 * child. A MeasureSpec can be in one of three modes:
424 * <ul>
425 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
426 * of a child view. For example, a LinearLayout may call measure() on its child
427 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
428 * tall the child view wants to be given a width of 240 pixels.
429 * <li>EXACTLY: This is used by the parent to impose an exact size on the
430 * child. The child must use this size, and guarantee that all of its
431 * descendants will fit within this size.
432 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
433 * child. The child must guarantee that it and all of its descendants will fit
434 * within this size.
435 * </ul>
436 * </p>
437 *
438 * <p>
439 * To intiate a layout, call {@link #requestLayout}. This method is typically
440 * called by a view on itself when it believes that is can no longer fit within
441 * its current bounds.
442 * </p>
443 *
444 * <a name="Drawing"></a>
445 * <h3>Drawing</h3>
446 * <p>
447 * Drawing is handled by walking the tree and rendering each view that
448 * intersects the invalid region. Because the tree is traversed in-order,
449 * this means that parents will draw before (i.e., behind) their children, with
450 * siblings drawn in the order they appear in the tree.
451 * If you set a background drawable for a View, then the View will draw it for you
452 * before calling back to its <code>onDraw()</code> method.
453 * </p>
454 *
455 * <p>
456 * Note that the framework will not draw views that are not in the invalid region.
457 * </p>
458 *
459 * <p>
460 * To force a view to draw, call {@link #invalidate()}.
461 * </p>
462 *
463 * <a name="EventHandlingThreading"></a>
464 * <h3>Event Handling and Threading</h3>
465 * <p>
466 * The basic cycle of a view is as follows:
467 * <ol>
468 * <li>An event comes in and is dispatched to the appropriate view. The view
469 * handles the event and notifies any listeners.</li>
470 * <li>If in the course of processing the event, the view's bounds may need
471 * to be changed, the view will call {@link #requestLayout()}.</li>
472 * <li>Similarly, if in the course of processing the event the view's appearance
473 * may need to be changed, the view will call {@link #invalidate()}.</li>
474 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
475 * the framework will take care of measuring, laying out, and drawing the tree
476 * as appropriate.</li>
477 * </ol>
478 * </p>
479 *
480 * <p><em>Note: The entire view tree is single threaded. You must always be on
481 * the UI thread when calling any method on any view.</em>
482 * If you are doing work on other threads and want to update the state of a view
483 * from that thread, you should use a {@link Handler}.
484 * </p>
485 *
486 * <a name="FocusHandling"></a>
487 * <h3>Focus Handling</h3>
488 * <p>
489 * The framework will handle routine focus movement in response to user input.
490 * This includes changing the focus as views are removed or hidden, or as new
491 * views become available. Views indicate their willingness to take focus
492 * through the {@link #isFocusable} method. To change whether a view can take
493 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
494 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
495 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
496 * </p>
497 * <p>
498 * Focus movement is based on an algorithm which finds the nearest neighbor in a
499 * given direction. In rare cases, the default algorithm may not match the
500 * intended behavior of the developer. In these situations, you can provide
501 * explicit overrides by using these XML attributes in the layout file:
502 * <pre>
503 * nextFocusDown
504 * nextFocusLeft
505 * nextFocusRight
506 * nextFocusUp
507 * </pre>
508 * </p>
509 *
510 *
511 * <p>
512 * To get a particular view to take focus, call {@link #requestFocus()}.
513 * </p>
514 *
515 * <a name="TouchMode"></a>
516 * <h3>Touch Mode</h3>
517 * <p>
518 * When a user is navigating a user interface via directional keys such as a D-pad, it is
519 * necessary to give focus to actionable items such as buttons so the user can see
520 * what will take input.  If the device has touch capabilities, however, and the user
521 * begins interacting with the interface by touching it, it is no longer necessary to
522 * always highlight, or give focus to, a particular view.  This motivates a mode
523 * for interaction named 'touch mode'.
524 * </p>
525 * <p>
526 * For a touch capable device, once the user touches the screen, the device
527 * will enter touch mode.  From this point onward, only views for which
528 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
529 * Other views that are touchable, like buttons, will not take focus when touched; they will
530 * only fire the on click listeners.
531 * </p>
532 * <p>
533 * Any time a user hits a directional key, such as a D-pad direction, the view device will
534 * exit touch mode, and find a view to take focus, so that the user may resume interacting
535 * with the user interface without touching the screen again.
536 * </p>
537 * <p>
538 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
539 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
540 * </p>
541 *
542 * <a name="Scrolling"></a>
543 * <h3>Scrolling</h3>
544 * <p>
545 * The framework provides basic support for views that wish to internally
546 * scroll their content. This includes keeping track of the X and Y scroll
547 * offset as well as mechanisms for drawing scrollbars. See
548 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
549 * {@link #awakenScrollBars()} for more details.
550 * </p>
551 *
552 * <a name="Tags"></a>
553 * <h3>Tags</h3>
554 * <p>
555 * Unlike IDs, tags are not used to identify views. Tags are essentially an
556 * extra piece of information that can be associated with a view. They are most
557 * often used as a convenience to store data related to views in the views
558 * themselves rather than by putting them in a separate structure.
559 * </p>
560 *
561 * <a name="Properties"></a>
562 * <h3>Properties</h3>
563 * <p>
564 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
565 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
566 * available both in the {@link Property} form as well as in similarly-named setter/getter
567 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
568 * be used to set persistent state associated with these rendering-related properties on the view.
569 * The properties and methods can also be used in conjunction with
570 * {@link android.animation.Animator Animator}-based animations, described more in the
571 * <a href="#Animation">Animation</a> section.
572 * </p>
573 *
574 * <a name="Animation"></a>
575 * <h3>Animation</h3>
576 * <p>
577 * Starting with Android 3.0, the preferred way of animating views is to use the
578 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
579 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
580 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
581 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
582 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
583 * makes animating these View properties particularly easy and efficient.
584 * </p>
585 * <p>
586 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
587 * You can attach an {@link Animation} object to a view using
588 * {@link #setAnimation(Animation)} or
589 * {@link #startAnimation(Animation)}. The animation can alter the scale,
590 * rotation, translation and alpha of a view over time. If the animation is
591 * attached to a view that has children, the animation will affect the entire
592 * subtree rooted by that node. When an animation is started, the framework will
593 * take care of redrawing the appropriate views until the animation completes.
594 * </p>
595 *
596 * <a name="Security"></a>
597 * <h3>Security</h3>
598 * <p>
599 * Sometimes it is essential that an application be able to verify that an action
600 * is being performed with the full knowledge and consent of the user, such as
601 * granting a permission request, making a purchase or clicking on an advertisement.
602 * Unfortunately, a malicious application could try to spoof the user into
603 * performing these actions, unaware, by concealing the intended purpose of the view.
604 * As a remedy, the framework offers a touch filtering mechanism that can be used to
605 * improve the security of views that provide access to sensitive functionality.
606 * </p><p>
607 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
608 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
609 * will discard touches that are received whenever the view's window is obscured by
610 * another visible window.  As a result, the view will not receive touches whenever a
611 * toast, dialog or other window appears above the view's window.
612 * </p><p>
613 * For more fine-grained control over security, consider overriding the
614 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
615 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
616 * </p>
617 *
618 * @attr ref android.R.styleable#View_alpha
619 * @attr ref android.R.styleable#View_background
620 * @attr ref android.R.styleable#View_clickable
621 * @attr ref android.R.styleable#View_contentDescription
622 * @attr ref android.R.styleable#View_drawingCacheQuality
623 * @attr ref android.R.styleable#View_duplicateParentState
624 * @attr ref android.R.styleable#View_id
625 * @attr ref android.R.styleable#View_requiresFadingEdge
626 * @attr ref android.R.styleable#View_fadeScrollbars
627 * @attr ref android.R.styleable#View_fadingEdgeLength
628 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
629 * @attr ref android.R.styleable#View_fitsSystemWindows
630 * @attr ref android.R.styleable#View_isScrollContainer
631 * @attr ref android.R.styleable#View_focusable
632 * @attr ref android.R.styleable#View_focusableInTouchMode
633 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
634 * @attr ref android.R.styleable#View_keepScreenOn
635 * @attr ref android.R.styleable#View_layerType
636 * @attr ref android.R.styleable#View_layoutDirection
637 * @attr ref android.R.styleable#View_longClickable
638 * @attr ref android.R.styleable#View_minHeight
639 * @attr ref android.R.styleable#View_minWidth
640 * @attr ref android.R.styleable#View_nextFocusDown
641 * @attr ref android.R.styleable#View_nextFocusLeft
642 * @attr ref android.R.styleable#View_nextFocusRight
643 * @attr ref android.R.styleable#View_nextFocusUp
644 * @attr ref android.R.styleable#View_onClick
645 * @attr ref android.R.styleable#View_padding
646 * @attr ref android.R.styleable#View_paddingBottom
647 * @attr ref android.R.styleable#View_paddingLeft
648 * @attr ref android.R.styleable#View_paddingRight
649 * @attr ref android.R.styleable#View_paddingTop
650 * @attr ref android.R.styleable#View_paddingStart
651 * @attr ref android.R.styleable#View_paddingEnd
652 * @attr ref android.R.styleable#View_saveEnabled
653 * @attr ref android.R.styleable#View_rotation
654 * @attr ref android.R.styleable#View_rotationX
655 * @attr ref android.R.styleable#View_rotationY
656 * @attr ref android.R.styleable#View_scaleX
657 * @attr ref android.R.styleable#View_scaleY
658 * @attr ref android.R.styleable#View_scrollX
659 * @attr ref android.R.styleable#View_scrollY
660 * @attr ref android.R.styleable#View_scrollbarSize
661 * @attr ref android.R.styleable#View_scrollbarStyle
662 * @attr ref android.R.styleable#View_scrollbars
663 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
664 * @attr ref android.R.styleable#View_scrollbarFadeDuration
665 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
666 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
667 * @attr ref android.R.styleable#View_scrollbarThumbVertical
668 * @attr ref android.R.styleable#View_scrollbarTrackVertical
669 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
670 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
671 * @attr ref android.R.styleable#View_stateListAnimator
672 * @attr ref android.R.styleable#View_transitionName
673 * @attr ref android.R.styleable#View_soundEffectsEnabled
674 * @attr ref android.R.styleable#View_tag
675 * @attr ref android.R.styleable#View_textAlignment
676 * @attr ref android.R.styleable#View_textDirection
677 * @attr ref android.R.styleable#View_transformPivotX
678 * @attr ref android.R.styleable#View_transformPivotY
679 * @attr ref android.R.styleable#View_translationX
680 * @attr ref android.R.styleable#View_translationY
681 * @attr ref android.R.styleable#View_translationZ
682 * @attr ref android.R.styleable#View_visibility
683 *
684 * @see android.view.ViewGroup
685 */
686public class View implements Drawable.Callback, KeyEvent.Callback,
687        AccessibilityEventSource {
688    private static final boolean DBG = false;
689
690    /**
691     * The logging tag used by this class with android.util.Log.
692     */
693    protected static final String VIEW_LOG_TAG = "View";
694
695    /**
696     * When set to true, apps will draw debugging information about their layouts.
697     *
698     * @hide
699     */
700    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
701
702    /**
703     * When set to true, this view will save its attribute data.
704     *
705     * @hide
706     */
707    public static boolean mDebugViewAttributes = false;
708
709    /**
710     * Used to mark a View that has no ID.
711     */
712    public static final int NO_ID = -1;
713
714    /**
715     * Signals that compatibility booleans have been initialized according to
716     * target SDK versions.
717     */
718    private static boolean sCompatibilityDone = false;
719
720    /**
721     * Use the old (broken) way of building MeasureSpecs.
722     */
723    private static boolean sUseBrokenMakeMeasureSpec = false;
724
725    /**
726     * Ignore any optimizations using the measure cache.
727     */
728    private static boolean sIgnoreMeasureCache = false;
729
730    /**
731     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
732     * calling setFlags.
733     */
734    private static final int NOT_FOCUSABLE = 0x00000000;
735
736    /**
737     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
738     * setFlags.
739     */
740    private static final int FOCUSABLE = 0x00000001;
741
742    /**
743     * Mask for use with setFlags indicating bits used for focus.
744     */
745    private static final int FOCUSABLE_MASK = 0x00000001;
746
747    /**
748     * This view will adjust its padding to fit sytem windows (e.g. status bar)
749     */
750    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
751
752    /** @hide */
753    @IntDef({VISIBLE, INVISIBLE, GONE})
754    @Retention(RetentionPolicy.SOURCE)
755    public @interface Visibility {}
756
757    /**
758     * This view is visible.
759     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
760     * android:visibility}.
761     */
762    public static final int VISIBLE = 0x00000000;
763
764    /**
765     * This view is invisible, but it still takes up space for layout purposes.
766     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
767     * android:visibility}.
768     */
769    public static final int INVISIBLE = 0x00000004;
770
771    /**
772     * This view is invisible, and it doesn't take any space for layout
773     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
774     * android:visibility}.
775     */
776    public static final int GONE = 0x00000008;
777
778    /**
779     * Mask for use with setFlags indicating bits used for visibility.
780     * {@hide}
781     */
782    static final int VISIBILITY_MASK = 0x0000000C;
783
784    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
785
786    /**
787     * This view is enabled. Interpretation varies by subclass.
788     * Use with ENABLED_MASK when calling setFlags.
789     * {@hide}
790     */
791    static final int ENABLED = 0x00000000;
792
793    /**
794     * This view is disabled. Interpretation varies by subclass.
795     * Use with ENABLED_MASK when calling setFlags.
796     * {@hide}
797     */
798    static final int DISABLED = 0x00000020;
799
800   /**
801    * Mask for use with setFlags indicating bits used for indicating whether
802    * this view is enabled
803    * {@hide}
804    */
805    static final int ENABLED_MASK = 0x00000020;
806
807    /**
808     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
809     * called and further optimizations will be performed. It is okay to have
810     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
811     * {@hide}
812     */
813    static final int WILL_NOT_DRAW = 0x00000080;
814
815    /**
816     * Mask for use with setFlags indicating bits used for indicating whether
817     * this view is will draw
818     * {@hide}
819     */
820    static final int DRAW_MASK = 0x00000080;
821
822    /**
823     * <p>This view doesn't show scrollbars.</p>
824     * {@hide}
825     */
826    static final int SCROLLBARS_NONE = 0x00000000;
827
828    /**
829     * <p>This view shows horizontal scrollbars.</p>
830     * {@hide}
831     */
832    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
833
834    /**
835     * <p>This view shows vertical scrollbars.</p>
836     * {@hide}
837     */
838    static final int SCROLLBARS_VERTICAL = 0x00000200;
839
840    /**
841     * <p>Mask for use with setFlags indicating bits used for indicating which
842     * scrollbars are enabled.</p>
843     * {@hide}
844     */
845    static final int SCROLLBARS_MASK = 0x00000300;
846
847    /**
848     * Indicates that the view should filter touches when its window is obscured.
849     * Refer to the class comments for more information about this security feature.
850     * {@hide}
851     */
852    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
853
854    /**
855     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
856     * that they are optional and should be skipped if the window has
857     * requested system UI flags that ignore those insets for layout.
858     */
859    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
860
861    /**
862     * <p>This view doesn't show fading edges.</p>
863     * {@hide}
864     */
865    static final int FADING_EDGE_NONE = 0x00000000;
866
867    /**
868     * <p>This view shows horizontal fading edges.</p>
869     * {@hide}
870     */
871    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
872
873    /**
874     * <p>This view shows vertical fading edges.</p>
875     * {@hide}
876     */
877    static final int FADING_EDGE_VERTICAL = 0x00002000;
878
879    /**
880     * <p>Mask for use with setFlags indicating bits used for indicating which
881     * fading edges are enabled.</p>
882     * {@hide}
883     */
884    static final int FADING_EDGE_MASK = 0x00003000;
885
886    /**
887     * <p>Indicates this view can be clicked. When clickable, a View reacts
888     * to clicks by notifying the OnClickListener.<p>
889     * {@hide}
890     */
891    static final int CLICKABLE = 0x00004000;
892
893    /**
894     * <p>Indicates this view is caching its drawing into a bitmap.</p>
895     * {@hide}
896     */
897    static final int DRAWING_CACHE_ENABLED = 0x00008000;
898
899    /**
900     * <p>Indicates that no icicle should be saved for this view.<p>
901     * {@hide}
902     */
903    static final int SAVE_DISABLED = 0x000010000;
904
905    /**
906     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
907     * property.</p>
908     * {@hide}
909     */
910    static final int SAVE_DISABLED_MASK = 0x000010000;
911
912    /**
913     * <p>Indicates that no drawing cache should ever be created for this view.<p>
914     * {@hide}
915     */
916    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
917
918    /**
919     * <p>Indicates this view can take / keep focus when int touch mode.</p>
920     * {@hide}
921     */
922    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
923
924    /** @hide */
925    @Retention(RetentionPolicy.SOURCE)
926    @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO})
927    public @interface DrawingCacheQuality {}
928
929    /**
930     * <p>Enables low quality mode for the drawing cache.</p>
931     */
932    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
933
934    /**
935     * <p>Enables high quality mode for the drawing cache.</p>
936     */
937    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
938
939    /**
940     * <p>Enables automatic quality mode for the drawing cache.</p>
941     */
942    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
943
944    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
945            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
946    };
947
948    /**
949     * <p>Mask for use with setFlags indicating bits used for the cache
950     * quality property.</p>
951     * {@hide}
952     */
953    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
954
955    /**
956     * <p>
957     * Indicates this view can be long clicked. When long clickable, a View
958     * reacts to long clicks by notifying the OnLongClickListener or showing a
959     * context menu.
960     * </p>
961     * {@hide}
962     */
963    static final int LONG_CLICKABLE = 0x00200000;
964
965    /**
966     * <p>Indicates that this view gets its drawable states from its direct parent
967     * and ignores its original internal states.</p>
968     *
969     * @hide
970     */
971    static final int DUPLICATE_PARENT_STATE = 0x00400000;
972
973    /** @hide */
974    @IntDef({
975        SCROLLBARS_INSIDE_OVERLAY,
976        SCROLLBARS_INSIDE_INSET,
977        SCROLLBARS_OUTSIDE_OVERLAY,
978        SCROLLBARS_OUTSIDE_INSET
979    })
980    @Retention(RetentionPolicy.SOURCE)
981    public @interface ScrollBarStyle {}
982
983    /**
984     * The scrollbar style to display the scrollbars inside the content area,
985     * without increasing the padding. The scrollbars will be overlaid with
986     * translucency on the view's content.
987     */
988    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
989
990    /**
991     * The scrollbar style to display the scrollbars inside the padded area,
992     * increasing the padding of the view. The scrollbars will not overlap the
993     * content area of the view.
994     */
995    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
996
997    /**
998     * The scrollbar style to display the scrollbars at the edge of the view,
999     * without increasing the padding. The scrollbars will be overlaid with
1000     * translucency.
1001     */
1002    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
1003
1004    /**
1005     * The scrollbar style to display the scrollbars at the edge of the view,
1006     * increasing the padding of the view. The scrollbars will only overlap the
1007     * background, if any.
1008     */
1009    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
1010
1011    /**
1012     * Mask to check if the scrollbar style is overlay or inset.
1013     * {@hide}
1014     */
1015    static final int SCROLLBARS_INSET_MASK = 0x01000000;
1016
1017    /**
1018     * Mask to check if the scrollbar style is inside or outside.
1019     * {@hide}
1020     */
1021    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
1022
1023    /**
1024     * Mask for scrollbar style.
1025     * {@hide}
1026     */
1027    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
1028
1029    /**
1030     * View flag indicating that the screen should remain on while the
1031     * window containing this view is visible to the user.  This effectively
1032     * takes care of automatically setting the WindowManager's
1033     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
1034     */
1035    public static final int KEEP_SCREEN_ON = 0x04000000;
1036
1037    /**
1038     * View flag indicating whether this view should have sound effects enabled
1039     * for events such as clicking and touching.
1040     */
1041    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
1042
1043    /**
1044     * View flag indicating whether this view should have haptic feedback
1045     * enabled for events such as long presses.
1046     */
1047    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
1048
1049    /**
1050     * <p>Indicates that the view hierarchy should stop saving state when
1051     * it reaches this view.  If state saving is initiated immediately at
1052     * the view, it will be allowed.
1053     * {@hide}
1054     */
1055    static final int PARENT_SAVE_DISABLED = 0x20000000;
1056
1057    /**
1058     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1059     * {@hide}
1060     */
1061    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1062
1063    /** @hide */
1064    @IntDef(flag = true,
1065            value = {
1066                FOCUSABLES_ALL,
1067                FOCUSABLES_TOUCH_MODE
1068            })
1069    @Retention(RetentionPolicy.SOURCE)
1070    public @interface FocusableMode {}
1071
1072    /**
1073     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1074     * should add all focusable Views regardless if they are focusable in touch mode.
1075     */
1076    public static final int FOCUSABLES_ALL = 0x00000000;
1077
1078    /**
1079     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1080     * should add only Views focusable in touch mode.
1081     */
1082    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1083
1084    /** @hide */
1085    @IntDef({
1086            FOCUS_BACKWARD,
1087            FOCUS_FORWARD,
1088            FOCUS_LEFT,
1089            FOCUS_UP,
1090            FOCUS_RIGHT,
1091            FOCUS_DOWN
1092    })
1093    @Retention(RetentionPolicy.SOURCE)
1094    public @interface FocusDirection {}
1095
1096    /** @hide */
1097    @IntDef({
1098            FOCUS_LEFT,
1099            FOCUS_UP,
1100            FOCUS_RIGHT,
1101            FOCUS_DOWN
1102    })
1103    @Retention(RetentionPolicy.SOURCE)
1104    public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward
1105
1106    /**
1107     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1108     * item.
1109     */
1110    public static final int FOCUS_BACKWARD = 0x00000001;
1111
1112    /**
1113     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1114     * item.
1115     */
1116    public static final int FOCUS_FORWARD = 0x00000002;
1117
1118    /**
1119     * Use with {@link #focusSearch(int)}. Move focus to the left.
1120     */
1121    public static final int FOCUS_LEFT = 0x00000011;
1122
1123    /**
1124     * Use with {@link #focusSearch(int)}. Move focus up.
1125     */
1126    public static final int FOCUS_UP = 0x00000021;
1127
1128    /**
1129     * Use with {@link #focusSearch(int)}. Move focus to the right.
1130     */
1131    public static final int FOCUS_RIGHT = 0x00000042;
1132
1133    /**
1134     * Use with {@link #focusSearch(int)}. Move focus down.
1135     */
1136    public static final int FOCUS_DOWN = 0x00000082;
1137
1138    /**
1139     * Bits of {@link #getMeasuredWidthAndState()} and
1140     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1141     */
1142    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1143
1144    /**
1145     * Bits of {@link #getMeasuredWidthAndState()} and
1146     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1147     */
1148    public static final int MEASURED_STATE_MASK = 0xff000000;
1149
1150    /**
1151     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1152     * for functions that combine both width and height into a single int,
1153     * such as {@link #getMeasuredState()} and the childState argument of
1154     * {@link #resolveSizeAndState(int, int, int)}.
1155     */
1156    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1157
1158    /**
1159     * Bit of {@link #getMeasuredWidthAndState()} and
1160     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1161     * is smaller that the space the view would like to have.
1162     */
1163    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1164
1165    /**
1166     * Base View state sets
1167     */
1168    // Singles
1169    /**
1170     * Indicates the view has no states set. States are used with
1171     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1172     * view depending on its state.
1173     *
1174     * @see android.graphics.drawable.Drawable
1175     * @see #getDrawableState()
1176     */
1177    protected static final int[] EMPTY_STATE_SET;
1178    /**
1179     * Indicates the view is enabled. States are used with
1180     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1181     * view depending on its state.
1182     *
1183     * @see android.graphics.drawable.Drawable
1184     * @see #getDrawableState()
1185     */
1186    protected static final int[] ENABLED_STATE_SET;
1187    /**
1188     * Indicates the view is focused. States are used with
1189     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1190     * view depending on its state.
1191     *
1192     * @see android.graphics.drawable.Drawable
1193     * @see #getDrawableState()
1194     */
1195    protected static final int[] FOCUSED_STATE_SET;
1196    /**
1197     * Indicates the view is selected. States are used with
1198     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1199     * view depending on its state.
1200     *
1201     * @see android.graphics.drawable.Drawable
1202     * @see #getDrawableState()
1203     */
1204    protected static final int[] SELECTED_STATE_SET;
1205    /**
1206     * Indicates the view is pressed. States are used with
1207     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1208     * view depending on its state.
1209     *
1210     * @see android.graphics.drawable.Drawable
1211     * @see #getDrawableState()
1212     */
1213    protected static final int[] PRESSED_STATE_SET;
1214    /**
1215     * Indicates the view's window has focus. States are used with
1216     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1217     * view depending on its state.
1218     *
1219     * @see android.graphics.drawable.Drawable
1220     * @see #getDrawableState()
1221     */
1222    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1223    // Doubles
1224    /**
1225     * Indicates the view is enabled and has the focus.
1226     *
1227     * @see #ENABLED_STATE_SET
1228     * @see #FOCUSED_STATE_SET
1229     */
1230    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is enabled and selected.
1233     *
1234     * @see #ENABLED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] ENABLED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is enabled and that its window has focus.
1240     *
1241     * @see #ENABLED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is focused and selected.
1247     *
1248     * @see #FOCUSED_STATE_SET
1249     * @see #SELECTED_STATE_SET
1250     */
1251    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1252    /**
1253     * Indicates the view has the focus and that its window has the focus.
1254     *
1255     * @see #FOCUSED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is selected and that its window has the focus.
1261     *
1262     * @see #SELECTED_STATE_SET
1263     * @see #WINDOW_FOCUSED_STATE_SET
1264     */
1265    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1266    // Triples
1267    /**
1268     * Indicates the view is enabled, focused and selected.
1269     *
1270     * @see #ENABLED_STATE_SET
1271     * @see #FOCUSED_STATE_SET
1272     * @see #SELECTED_STATE_SET
1273     */
1274    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1275    /**
1276     * Indicates the view is enabled, focused and its window has the focus.
1277     *
1278     * @see #ENABLED_STATE_SET
1279     * @see #FOCUSED_STATE_SET
1280     * @see #WINDOW_FOCUSED_STATE_SET
1281     */
1282    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1283    /**
1284     * Indicates the view is enabled, selected and its window has the focus.
1285     *
1286     * @see #ENABLED_STATE_SET
1287     * @see #SELECTED_STATE_SET
1288     * @see #WINDOW_FOCUSED_STATE_SET
1289     */
1290    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1291    /**
1292     * Indicates the view is focused, selected and its window has the focus.
1293     *
1294     * @see #FOCUSED_STATE_SET
1295     * @see #SELECTED_STATE_SET
1296     * @see #WINDOW_FOCUSED_STATE_SET
1297     */
1298    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1299    /**
1300     * Indicates the view is enabled, focused, selected and its window
1301     * has the focus.
1302     *
1303     * @see #ENABLED_STATE_SET
1304     * @see #FOCUSED_STATE_SET
1305     * @see #SELECTED_STATE_SET
1306     * @see #WINDOW_FOCUSED_STATE_SET
1307     */
1308    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is pressed and its window has the focus.
1311     *
1312     * @see #PRESSED_STATE_SET
1313     * @see #WINDOW_FOCUSED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed and selected.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #SELECTED_STATE_SET
1321     */
1322    protected static final int[] PRESSED_SELECTED_STATE_SET;
1323    /**
1324     * Indicates the view is pressed, selected and its window has the focus.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #SELECTED_STATE_SET
1328     * @see #WINDOW_FOCUSED_STATE_SET
1329     */
1330    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1331    /**
1332     * Indicates the view is pressed and focused.
1333     *
1334     * @see #PRESSED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, focused and its window has the focus.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #FOCUSED_STATE_SET
1343     * @see #WINDOW_FOCUSED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed, focused and selected.
1348     *
1349     * @see #PRESSED_STATE_SET
1350     * @see #SELECTED_STATE_SET
1351     * @see #FOCUSED_STATE_SET
1352     */
1353    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1354    /**
1355     * Indicates the view is pressed, focused, selected and its window has the focus.
1356     *
1357     * @see #PRESSED_STATE_SET
1358     * @see #FOCUSED_STATE_SET
1359     * @see #SELECTED_STATE_SET
1360     * @see #WINDOW_FOCUSED_STATE_SET
1361     */
1362    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1363    /**
1364     * Indicates the view is pressed and enabled.
1365     *
1366     * @see #PRESSED_STATE_SET
1367     * @see #ENABLED_STATE_SET
1368     */
1369    protected static final int[] PRESSED_ENABLED_STATE_SET;
1370    /**
1371     * Indicates the view is pressed, enabled and its window has the focus.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #ENABLED_STATE_SET
1375     * @see #WINDOW_FOCUSED_STATE_SET
1376     */
1377    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1378    /**
1379     * Indicates the view is pressed, enabled and selected.
1380     *
1381     * @see #PRESSED_STATE_SET
1382     * @see #ENABLED_STATE_SET
1383     * @see #SELECTED_STATE_SET
1384     */
1385    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1386    /**
1387     * Indicates the view is pressed, enabled, selected and its window has the
1388     * focus.
1389     *
1390     * @see #PRESSED_STATE_SET
1391     * @see #ENABLED_STATE_SET
1392     * @see #SELECTED_STATE_SET
1393     * @see #WINDOW_FOCUSED_STATE_SET
1394     */
1395    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1396    /**
1397     * Indicates the view is pressed, enabled and focused.
1398     *
1399     * @see #PRESSED_STATE_SET
1400     * @see #ENABLED_STATE_SET
1401     * @see #FOCUSED_STATE_SET
1402     */
1403    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1404    /**
1405     * Indicates the view is pressed, enabled, focused and its window has the
1406     * focus.
1407     *
1408     * @see #PRESSED_STATE_SET
1409     * @see #ENABLED_STATE_SET
1410     * @see #FOCUSED_STATE_SET
1411     * @see #WINDOW_FOCUSED_STATE_SET
1412     */
1413    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1414    /**
1415     * Indicates the view is pressed, enabled, focused and selected.
1416     *
1417     * @see #PRESSED_STATE_SET
1418     * @see #ENABLED_STATE_SET
1419     * @see #SELECTED_STATE_SET
1420     * @see #FOCUSED_STATE_SET
1421     */
1422    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1423    /**
1424     * Indicates the view is pressed, enabled, focused, selected and its window
1425     * has the focus.
1426     *
1427     * @see #PRESSED_STATE_SET
1428     * @see #ENABLED_STATE_SET
1429     * @see #SELECTED_STATE_SET
1430     * @see #FOCUSED_STATE_SET
1431     * @see #WINDOW_FOCUSED_STATE_SET
1432     */
1433    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1434
1435    /**
1436     * The order here is very important to {@link #getDrawableState()}
1437     */
1438    private static final int[][] VIEW_STATE_SETS;
1439
1440    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1441    static final int VIEW_STATE_SELECTED = 1 << 1;
1442    static final int VIEW_STATE_FOCUSED = 1 << 2;
1443    static final int VIEW_STATE_ENABLED = 1 << 3;
1444    static final int VIEW_STATE_PRESSED = 1 << 4;
1445    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1446    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1447    static final int VIEW_STATE_HOVERED = 1 << 7;
1448    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1449    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1450
1451    static final int[] VIEW_STATE_IDS = new int[] {
1452        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1453        R.attr.state_selected,          VIEW_STATE_SELECTED,
1454        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1455        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1456        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1457        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1458        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1459        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1460        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1461        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1462    };
1463
1464    static {
1465        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1466            throw new IllegalStateException(
1467                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1468        }
1469        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1470        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1471            int viewState = R.styleable.ViewDrawableStates[i];
1472            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1473                if (VIEW_STATE_IDS[j] == viewState) {
1474                    orderedIds[i * 2] = viewState;
1475                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1476                }
1477            }
1478        }
1479        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1480        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1481        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1482            int numBits = Integer.bitCount(i);
1483            int[] set = new int[numBits];
1484            int pos = 0;
1485            for (int j = 0; j < orderedIds.length; j += 2) {
1486                if ((i & orderedIds[j+1]) != 0) {
1487                    set[pos++] = orderedIds[j];
1488                }
1489            }
1490            VIEW_STATE_SETS[i] = set;
1491        }
1492
1493        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1494        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1495        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1496        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1498        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1499        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1501        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1502                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1503        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1505                | VIEW_STATE_FOCUSED];
1506        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1507        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1509        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1511        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1512                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1513                | VIEW_STATE_ENABLED];
1514        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1515                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1516        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1518                | VIEW_STATE_ENABLED];
1519        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1521                | VIEW_STATE_ENABLED];
1522        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1523                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1524                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1525
1526        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1527        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1528                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1529        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1530                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1531        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1532                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1533                | VIEW_STATE_PRESSED];
1534        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1535                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1536        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1537                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1538                | VIEW_STATE_PRESSED];
1539        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1540                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1541                | VIEW_STATE_PRESSED];
1542        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1543                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1544                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1545        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1546                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1547        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1548                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1549                | VIEW_STATE_PRESSED];
1550        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1551                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1552                | VIEW_STATE_PRESSED];
1553        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1554                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1555                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1556        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1557                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1558                | VIEW_STATE_PRESSED];
1559        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1560                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1561                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1562        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1563                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1564                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1565        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1566                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1567                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1568                | VIEW_STATE_PRESSED];
1569    }
1570
1571    /**
1572     * Accessibility event types that are dispatched for text population.
1573     */
1574    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1575            AccessibilityEvent.TYPE_VIEW_CLICKED
1576            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1577            | AccessibilityEvent.TYPE_VIEW_SELECTED
1578            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1579            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1580            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1581            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1582            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1583            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1584            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1585            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1586
1587    /**
1588     * Temporary Rect currently for use in setBackground().  This will probably
1589     * be extended in the future to hold our own class with more than just
1590     * a Rect. :)
1591     */
1592    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1593
1594    /**
1595     * Map used to store views' tags.
1596     */
1597    private SparseArray<Object> mKeyedTags;
1598
1599    /**
1600     * The next available accessibility id.
1601     */
1602    private static int sNextAccessibilityViewId;
1603
1604    /**
1605     * The animation currently associated with this view.
1606     * @hide
1607     */
1608    protected Animation mCurrentAnimation = null;
1609
1610    /**
1611     * Width as measured during measure pass.
1612     * {@hide}
1613     */
1614    @ViewDebug.ExportedProperty(category = "measurement")
1615    int mMeasuredWidth;
1616
1617    /**
1618     * Height as measured during measure pass.
1619     * {@hide}
1620     */
1621    @ViewDebug.ExportedProperty(category = "measurement")
1622    int mMeasuredHeight;
1623
1624    /**
1625     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1626     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1627     * its display list. This flag, used only when hw accelerated, allows us to clear the
1628     * flag while retaining this information until it's needed (at getDisplayList() time and
1629     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1630     *
1631     * {@hide}
1632     */
1633    boolean mRecreateDisplayList = false;
1634
1635    /**
1636     * The view's identifier.
1637     * {@hide}
1638     *
1639     * @see #setId(int)
1640     * @see #getId()
1641     */
1642    @ViewDebug.ExportedProperty(resolveId = true)
1643    int mID = NO_ID;
1644
1645    /**
1646     * The stable ID of this view for accessibility purposes.
1647     */
1648    int mAccessibilityViewId = NO_ID;
1649
1650    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1651
1652    SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent;
1653
1654    /**
1655     * The view's tag.
1656     * {@hide}
1657     *
1658     * @see #setTag(Object)
1659     * @see #getTag()
1660     */
1661    protected Object mTag = null;
1662
1663    // for mPrivateFlags:
1664    /** {@hide} */
1665    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1666    /** {@hide} */
1667    static final int PFLAG_FOCUSED                     = 0x00000002;
1668    /** {@hide} */
1669    static final int PFLAG_SELECTED                    = 0x00000004;
1670    /** {@hide} */
1671    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1672    /** {@hide} */
1673    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1674    /** {@hide} */
1675    static final int PFLAG_DRAWN                       = 0x00000020;
1676    /**
1677     * When this flag is set, this view is running an animation on behalf of its
1678     * children and should therefore not cancel invalidate requests, even if they
1679     * lie outside of this view's bounds.
1680     *
1681     * {@hide}
1682     */
1683    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1684    /** {@hide} */
1685    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1686    /** {@hide} */
1687    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1688    /** {@hide} */
1689    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1690    /** {@hide} */
1691    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1692    /** {@hide} */
1693    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1694    /** {@hide} */
1695    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1696    /** {@hide} */
1697    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1698
1699    private static final int PFLAG_PRESSED             = 0x00004000;
1700
1701    /** {@hide} */
1702    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1703    /**
1704     * Flag used to indicate that this view should be drawn once more (and only once
1705     * more) after its animation has completed.
1706     * {@hide}
1707     */
1708    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1709
1710    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1711
1712    /**
1713     * Indicates that the View returned true when onSetAlpha() was called and that
1714     * the alpha must be restored.
1715     * {@hide}
1716     */
1717    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1718
1719    /**
1720     * Set by {@link #setScrollContainer(boolean)}.
1721     */
1722    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1723
1724    /**
1725     * Set by {@link #setScrollContainer(boolean)}.
1726     */
1727    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1728
1729    /**
1730     * View flag indicating whether this view was invalidated (fully or partially.)
1731     *
1732     * @hide
1733     */
1734    static final int PFLAG_DIRTY                       = 0x00200000;
1735
1736    /**
1737     * View flag indicating whether this view was invalidated by an opaque
1738     * invalidate request.
1739     *
1740     * @hide
1741     */
1742    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1743
1744    /**
1745     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1746     *
1747     * @hide
1748     */
1749    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1750
1751    /**
1752     * Indicates whether the background is opaque.
1753     *
1754     * @hide
1755     */
1756    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1757
1758    /**
1759     * Indicates whether the scrollbars are opaque.
1760     *
1761     * @hide
1762     */
1763    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1764
1765    /**
1766     * Indicates whether the view is opaque.
1767     *
1768     * @hide
1769     */
1770    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1771
1772    /**
1773     * Indicates a prepressed state;
1774     * the short time between ACTION_DOWN and recognizing
1775     * a 'real' press. Prepressed is used to recognize quick taps
1776     * even when they are shorter than ViewConfiguration.getTapTimeout().
1777     *
1778     * @hide
1779     */
1780    private static final int PFLAG_PREPRESSED          = 0x02000000;
1781
1782    /**
1783     * Indicates whether the view is temporarily detached.
1784     *
1785     * @hide
1786     */
1787    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1788
1789    /**
1790     * Indicates that we should awaken scroll bars once attached
1791     *
1792     * @hide
1793     */
1794    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1795
1796    /**
1797     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1798     * @hide
1799     */
1800    private static final int PFLAG_HOVERED             = 0x10000000;
1801
1802    /**
1803     * no longer needed, should be reused
1804     */
1805    private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000;
1806
1807    /** {@hide} */
1808    static final int PFLAG_ACTIVATED                   = 0x40000000;
1809
1810    /**
1811     * Indicates that this view was specifically invalidated, not just dirtied because some
1812     * child view was invalidated. The flag is used to determine when we need to recreate
1813     * a view's display list (as opposed to just returning a reference to its existing
1814     * display list).
1815     *
1816     * @hide
1817     */
1818    static final int PFLAG_INVALIDATED                 = 0x80000000;
1819
1820    /**
1821     * Masks for mPrivateFlags2, as generated by dumpFlags():
1822     *
1823     * |-------|-------|-------|-------|
1824     *                                 1 PFLAG2_DRAG_CAN_ACCEPT
1825     *                                1  PFLAG2_DRAG_HOVERED
1826     *                              11   PFLAG2_LAYOUT_DIRECTION_MASK
1827     *                             1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1828     *                            1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1829     *                            11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1830     *                           1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1831     *                          1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1832     *                          11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1833     *                         1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1834     *                         1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1835     *                         111       PFLAG2_TEXT_DIRECTION_MASK
1836     *                        1          PFLAG2_TEXT_DIRECTION_RESOLVED
1837     *                       1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1838     *                     111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1839     *                    1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1840     *                   1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1841     *                   11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1842     *                  1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1843     *                  1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1844     *                  11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1845     *                  111              PFLAG2_TEXT_ALIGNMENT_MASK
1846     *                 1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1847     *                1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1848     *              111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1849     *           111                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1850     *         11                        PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK
1851     *       1                           PFLAG2_ACCESSIBILITY_FOCUSED
1852     *      1                            PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED
1853     *     1                             PFLAG2_VIEW_QUICK_REJECTED
1854     *    1                              PFLAG2_PADDING_RESOLVED
1855     *   1                               PFLAG2_DRAWABLE_RESOLVED
1856     *  1                                PFLAG2_HAS_TRANSIENT_STATE
1857     * |-------|-------|-------|-------|
1858     */
1859
1860    /**
1861     * Indicates that this view has reported that it can accept the current drag's content.
1862     * Cleared when the drag operation concludes.
1863     * @hide
1864     */
1865    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1866
1867    /**
1868     * Indicates that this view is currently directly under the drag location in a
1869     * drag-and-drop operation involving content that it can accept.  Cleared when
1870     * the drag exits the view, or when the drag operation concludes.
1871     * @hide
1872     */
1873    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1874
1875    /** @hide */
1876    @IntDef({
1877        LAYOUT_DIRECTION_LTR,
1878        LAYOUT_DIRECTION_RTL,
1879        LAYOUT_DIRECTION_INHERIT,
1880        LAYOUT_DIRECTION_LOCALE
1881    })
1882    @Retention(RetentionPolicy.SOURCE)
1883    // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection
1884    public @interface LayoutDir {}
1885
1886    /** @hide */
1887    @IntDef({
1888        LAYOUT_DIRECTION_LTR,
1889        LAYOUT_DIRECTION_RTL
1890    })
1891    @Retention(RetentionPolicy.SOURCE)
1892    public @interface ResolvedLayoutDir {}
1893
1894    /**
1895     * Horizontal layout direction of this view is from Left to Right.
1896     * Use with {@link #setLayoutDirection}.
1897     */
1898    public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR;
1899
1900    /**
1901     * Horizontal layout direction of this view is from Right to Left.
1902     * Use with {@link #setLayoutDirection}.
1903     */
1904    public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL;
1905
1906    /**
1907     * Horizontal layout direction of this view is inherited from its parent.
1908     * Use with {@link #setLayoutDirection}.
1909     */
1910    public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT;
1911
1912    /**
1913     * Horizontal layout direction of this view is from deduced from the default language
1914     * script for the locale. Use with {@link #setLayoutDirection}.
1915     */
1916    public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE;
1917
1918    /**
1919     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1920     * @hide
1921     */
1922    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1923
1924    /**
1925     * Mask for use with private flags indicating bits used for horizontal layout direction.
1926     * @hide
1927     */
1928    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1929
1930    /**
1931     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1932     * right-to-left direction.
1933     * @hide
1934     */
1935    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1936
1937    /**
1938     * Indicates whether the view horizontal layout direction has been resolved.
1939     * @hide
1940     */
1941    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1942
1943    /**
1944     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1945     * @hide
1946     */
1947    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1948            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1949
1950    /*
1951     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1952     * flag value.
1953     * @hide
1954     */
1955    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1956            LAYOUT_DIRECTION_LTR,
1957            LAYOUT_DIRECTION_RTL,
1958            LAYOUT_DIRECTION_INHERIT,
1959            LAYOUT_DIRECTION_LOCALE
1960    };
1961
1962    /**
1963     * Default horizontal layout direction.
1964     */
1965    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1966
1967    /**
1968     * Default horizontal layout direction.
1969     * @hide
1970     */
1971    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1972
1973    /**
1974     * Text direction is inherited thru {@link ViewGroup}
1975     */
1976    public static final int TEXT_DIRECTION_INHERIT = 0;
1977
1978    /**
1979     * Text direction is using "first strong algorithm". The first strong directional character
1980     * determines the paragraph direction. If there is no strong directional character, the
1981     * paragraph direction is the view's resolved layout direction.
1982     */
1983    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1984
1985    /**
1986     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1987     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1988     * If there are neither, the paragraph direction is the view's resolved layout direction.
1989     */
1990    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1991
1992    /**
1993     * Text direction is forced to LTR.
1994     */
1995    public static final int TEXT_DIRECTION_LTR = 3;
1996
1997    /**
1998     * Text direction is forced to RTL.
1999     */
2000    public static final int TEXT_DIRECTION_RTL = 4;
2001
2002    /**
2003     * Text direction is coming from the system Locale.
2004     */
2005    public static final int TEXT_DIRECTION_LOCALE = 5;
2006
2007    /**
2008     * Default text direction is inherited
2009     */
2010    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
2011
2012    /**
2013     * Default resolved text direction
2014     * @hide
2015     */
2016    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
2017
2018    /**
2019     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
2020     * @hide
2021     */
2022    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
2023
2024    /**
2025     * Mask for use with private flags indicating bits used for text direction.
2026     * @hide
2027     */
2028    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
2029            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2030
2031    /**
2032     * Array of text direction flags for mapping attribute "textDirection" to correct
2033     * flag value.
2034     * @hide
2035     */
2036    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
2037            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2038            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2039            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2040            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2041            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
2042            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
2043    };
2044
2045    /**
2046     * Indicates whether the view text direction has been resolved.
2047     * @hide
2048     */
2049    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
2050            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
2051
2052    /**
2053     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2054     * @hide
2055     */
2056    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
2057
2058    /**
2059     * Mask for use with private flags indicating bits used for resolved text direction.
2060     * @hide
2061     */
2062    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
2063            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2064
2065    /**
2066     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
2067     * @hide
2068     */
2069    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
2070            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
2071
2072    /** @hide */
2073    @IntDef({
2074        TEXT_ALIGNMENT_INHERIT,
2075        TEXT_ALIGNMENT_GRAVITY,
2076        TEXT_ALIGNMENT_CENTER,
2077        TEXT_ALIGNMENT_TEXT_START,
2078        TEXT_ALIGNMENT_TEXT_END,
2079        TEXT_ALIGNMENT_VIEW_START,
2080        TEXT_ALIGNMENT_VIEW_END
2081    })
2082    @Retention(RetentionPolicy.SOURCE)
2083    public @interface TextAlignment {}
2084
2085    /**
2086     * Default text alignment. The text alignment of this View is inherited from its parent.
2087     * Use with {@link #setTextAlignment(int)}
2088     */
2089    public static final int TEXT_ALIGNMENT_INHERIT = 0;
2090
2091    /**
2092     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
2093     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
2094     *
2095     * Use with {@link #setTextAlignment(int)}
2096     */
2097    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2098
2099    /**
2100     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2101     *
2102     * Use with {@link #setTextAlignment(int)}
2103     */
2104    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2105
2106    /**
2107     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2108     *
2109     * Use with {@link #setTextAlignment(int)}
2110     */
2111    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2112
2113    /**
2114     * Center the paragraph, e.g. ALIGN_CENTER.
2115     *
2116     * Use with {@link #setTextAlignment(int)}
2117     */
2118    public static final int TEXT_ALIGNMENT_CENTER = 4;
2119
2120    /**
2121     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2122     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2123     *
2124     * Use with {@link #setTextAlignment(int)}
2125     */
2126    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2127
2128    /**
2129     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2130     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2131     *
2132     * Use with {@link #setTextAlignment(int)}
2133     */
2134    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2135
2136    /**
2137     * Default text alignment is inherited
2138     */
2139    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2140
2141    /**
2142     * Default resolved text alignment
2143     * @hide
2144     */
2145    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2146
2147    /**
2148      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2149      * @hide
2150      */
2151    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2152
2153    /**
2154      * Mask for use with private flags indicating bits used for text alignment.
2155      * @hide
2156      */
2157    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2158
2159    /**
2160     * Array of text direction flags for mapping attribute "textAlignment" to correct
2161     * flag value.
2162     * @hide
2163     */
2164    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2165            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2166            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2167            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2168            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2169            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2170            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2171            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2172    };
2173
2174    /**
2175     * Indicates whether the view text alignment has been resolved.
2176     * @hide
2177     */
2178    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2179
2180    /**
2181     * Bit shift to get the resolved text alignment.
2182     * @hide
2183     */
2184    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2185
2186    /**
2187     * Mask for use with private flags indicating bits used for text alignment.
2188     * @hide
2189     */
2190    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2191            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2192
2193    /**
2194     * Indicates whether if the view text alignment has been resolved to gravity
2195     */
2196    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2197            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2198
2199    // Accessiblity constants for mPrivateFlags2
2200
2201    /**
2202     * Shift for the bits in {@link #mPrivateFlags2} related to the
2203     * "importantForAccessibility" attribute.
2204     */
2205    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2206
2207    /**
2208     * Automatically determine whether a view is important for accessibility.
2209     */
2210    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2211
2212    /**
2213     * The view is important for accessibility.
2214     */
2215    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2216
2217    /**
2218     * The view is not important for accessibility.
2219     */
2220    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2221
2222    /**
2223     * The view is not important for accessibility, nor are any of its
2224     * descendant views.
2225     */
2226    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004;
2227
2228    /**
2229     * The default whether the view is important for accessibility.
2230     */
2231    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2232
2233    /**
2234     * Mask for obtainig the bits which specify how to determine
2235     * whether a view is important for accessibility.
2236     */
2237    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2238        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO
2239        | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)
2240        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2241
2242    /**
2243     * Shift for the bits in {@link #mPrivateFlags2} related to the
2244     * "accessibilityLiveRegion" attribute.
2245     */
2246    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23;
2247
2248    /**
2249     * Live region mode specifying that accessibility services should not
2250     * automatically announce changes to this view. This is the default live
2251     * region mode for most views.
2252     * <p>
2253     * Use with {@link #setAccessibilityLiveRegion(int)}.
2254     */
2255    public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000;
2256
2257    /**
2258     * Live region mode specifying that accessibility services should announce
2259     * changes to this view.
2260     * <p>
2261     * Use with {@link #setAccessibilityLiveRegion(int)}.
2262     */
2263    public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
2264
2265    /**
2266     * Live region mode specifying that accessibility services should interrupt
2267     * ongoing speech to immediately announce changes to this view.
2268     * <p>
2269     * Use with {@link #setAccessibilityLiveRegion(int)}.
2270     */
2271    public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002;
2272
2273    /**
2274     * The default whether the view is important for accessibility.
2275     */
2276    static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE;
2277
2278    /**
2279     * Mask for obtaining the bits which specify a view's accessibility live
2280     * region mode.
2281     */
2282    static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE
2283            | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
2284            << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
2285
2286    /**
2287     * Flag indicating whether a view has accessibility focus.
2288     */
2289    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000;
2290
2291    /**
2292     * Flag whether the accessibility state of the subtree rooted at this view changed.
2293     */
2294    static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000;
2295
2296    /**
2297     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2298     * is used to check whether later changes to the view's transform should invalidate the
2299     * view to force the quickReject test to run again.
2300     */
2301    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2302
2303    /**
2304     * Flag indicating that start/end padding has been resolved into left/right padding
2305     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2306     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2307     * during measurement. In some special cases this is required such as when an adapter-based
2308     * view measures prospective children without attaching them to a window.
2309     */
2310    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2311
2312    /**
2313     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2314     */
2315    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2316
2317    /**
2318     * Indicates that the view is tracking some sort of transient state
2319     * that the app should not need to be aware of, but that the framework
2320     * should take special care to preserve.
2321     */
2322    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000;
2323
2324    /**
2325     * Group of bits indicating that RTL properties resolution is done.
2326     */
2327    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2328            PFLAG2_TEXT_DIRECTION_RESOLVED |
2329            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2330            PFLAG2_PADDING_RESOLVED |
2331            PFLAG2_DRAWABLE_RESOLVED;
2332
2333    // There are a couple of flags left in mPrivateFlags2
2334
2335    /* End of masks for mPrivateFlags2 */
2336
2337    /**
2338     * Masks for mPrivateFlags3, as generated by dumpFlags():
2339     *
2340     * |-------|-------|-------|-------|
2341     *                                 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM
2342     *                                1  PFLAG3_VIEW_IS_ANIMATING_ALPHA
2343     *                               1   PFLAG3_IS_LAID_OUT
2344     *                              1    PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT
2345     *                             1     PFLAG3_CALLED_SUPER
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     * Always allow a user to over-scroll this view, provided it is a
2404     * view that can scroll.
2405     *
2406     * @see #getOverScrollMode()
2407     * @see #setOverScrollMode(int)
2408     */
2409    public static final int OVER_SCROLL_ALWAYS = 0;
2410
2411    /**
2412     * Allow a user to over-scroll this view only if the content is large
2413     * enough to meaningfully scroll, provided it is a view that can scroll.
2414     *
2415     * @see #getOverScrollMode()
2416     * @see #setOverScrollMode(int)
2417     */
2418    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2419
2420    /**
2421     * Never allow a user to over-scroll this view.
2422     *
2423     * @see #getOverScrollMode()
2424     * @see #setOverScrollMode(int)
2425     */
2426    public static final int OVER_SCROLL_NEVER = 2;
2427
2428    /**
2429     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2430     * requested the system UI (status bar) to be visible (the default).
2431     *
2432     * @see #setSystemUiVisibility(int)
2433     */
2434    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2435
2436    /**
2437     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2438     * system UI to enter an unobtrusive "low profile" mode.
2439     *
2440     * <p>This is for use in games, book readers, video players, or any other
2441     * "immersive" application where the usual system chrome is deemed too distracting.
2442     *
2443     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2444     *
2445     * @see #setSystemUiVisibility(int)
2446     */
2447    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2448
2449    /**
2450     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2451     * system navigation be temporarily hidden.
2452     *
2453     * <p>This is an even less obtrusive state than that called for by
2454     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2455     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2456     * those to disappear. This is useful (in conjunction with the
2457     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2458     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2459     * window flags) for displaying content using every last pixel on the display.
2460     *
2461     * <p>There is a limitation: because navigation controls are so important, the least user
2462     * interaction will cause them to reappear immediately.  When this happens, both
2463     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2464     * so that both elements reappear at the same time.
2465     *
2466     * @see #setSystemUiVisibility(int)
2467     */
2468    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2469
2470    /**
2471     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2472     * into the normal fullscreen mode so that its content can take over the screen
2473     * while still allowing the user to interact with the application.
2474     *
2475     * <p>This has the same visual effect as
2476     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2477     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2478     * meaning that non-critical screen decorations (such as the status bar) will be
2479     * hidden while the user is in the View's window, focusing the experience on
2480     * that content.  Unlike the window flag, if you are using ActionBar in
2481     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2482     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2483     * hide the action bar.
2484     *
2485     * <p>This approach to going fullscreen is best used over the window flag when
2486     * it is a transient state -- that is, the application does this at certain
2487     * points in its user interaction where it wants to allow the user to focus
2488     * on content, but not as a continuous state.  For situations where the application
2489     * would like to simply stay full screen the entire time (such as a game that
2490     * wants to take over the screen), the
2491     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2492     * is usually a better approach.  The state set here will be removed by the system
2493     * in various situations (such as the user moving to another application) like
2494     * the other system UI states.
2495     *
2496     * <p>When using this flag, the application should provide some easy facility
2497     * for the user to go out of it.  A common example would be in an e-book
2498     * reader, where tapping on the screen brings back whatever screen and UI
2499     * decorations that had been hidden while the user was immersed in reading
2500     * the book.
2501     *
2502     * @see #setSystemUiVisibility(int)
2503     */
2504    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2505
2506    /**
2507     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2508     * flags, we would like a stable view of the content insets given to
2509     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2510     * will always represent the worst case that the application can expect
2511     * as a continuous state.  In the stock Android UI this is the space for
2512     * the system bar, nav bar, and status bar, but not more transient elements
2513     * such as an input method.
2514     *
2515     * The stable layout your UI sees is based on the system UI modes you can
2516     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2517     * then you will get a stable layout for changes of the
2518     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2519     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2520     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2521     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2522     * with a stable layout.  (Note that you should avoid using
2523     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2524     *
2525     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2526     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2527     * then a hidden status bar will be considered a "stable" state for purposes
2528     * here.  This allows your UI to continually hide the status bar, while still
2529     * using the system UI flags to hide the action bar while still retaining
2530     * a stable layout.  Note that changing the window fullscreen flag will never
2531     * provide a stable layout for a clean transition.
2532     *
2533     * <p>If you are using ActionBar in
2534     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2535     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2536     * insets it adds to those given to the application.
2537     */
2538    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2539
2540    /**
2541     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2542     * to be layed out as if it has requested
2543     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2544     * allows it to avoid artifacts when switching in and out of that mode, at
2545     * the expense that some of its user interface may be covered by screen
2546     * decorations when they are shown.  You can perform layout of your inner
2547     * UI elements to account for the navigation system UI through the
2548     * {@link #fitSystemWindows(Rect)} method.
2549     */
2550    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2551
2552    /**
2553     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2554     * to be layed out as if it has requested
2555     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2556     * allows it to avoid artifacts when switching in and out of that mode, at
2557     * the expense that some of its user interface may be covered by screen
2558     * decorations when they are shown.  You can perform layout of your inner
2559     * UI elements to account for non-fullscreen system UI through the
2560     * {@link #fitSystemWindows(Rect)} method.
2561     */
2562    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2563
2564    /**
2565     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2566     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
2567     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
2568     * user interaction.
2569     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
2570     * has an effect when used in combination with that flag.</p>
2571     */
2572    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
2573
2574    /**
2575     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
2576     * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
2577     * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
2578     * experience while also hiding the system bars.  If this flag is not set,
2579     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user
2580     * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system
2581     * if the user swipes from the top of the screen.
2582     * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with
2583     * system gestures, such as swiping from the top of the screen.  These transient system bars
2584     * will overlay app’s content, may have some degree of transparency, and will automatically
2585     * hide after a short timeout.
2586     * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and
2587     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
2588     * with one or both of those flags.</p>
2589     */
2590    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
2591
2592    /**
2593     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2594     */
2595    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2596
2597    /**
2598     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2599     */
2600    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2601
2602    /**
2603     * @hide
2604     *
2605     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2606     * out of the public fields to keep the undefined bits out of the developer's way.
2607     *
2608     * Flag to make the status bar not expandable.  Unless you also
2609     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2610     */
2611    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2612
2613    /**
2614     * @hide
2615     *
2616     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2617     * out of the public fields to keep the undefined bits out of the developer's way.
2618     *
2619     * Flag to hide notification icons and scrolling ticker text.
2620     */
2621    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2622
2623    /**
2624     * @hide
2625     *
2626     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2627     * out of the public fields to keep the undefined bits out of the developer's way.
2628     *
2629     * Flag to disable incoming notification alerts.  This will not block
2630     * icons, but it will block sound, vibrating and other visual or aural notifications.
2631     */
2632    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2633
2634    /**
2635     * @hide
2636     *
2637     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2638     * out of the public fields to keep the undefined bits out of the developer's way.
2639     *
2640     * Flag to hide only the scrolling ticker.  Note that
2641     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2642     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2643     */
2644    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2645
2646    /**
2647     * @hide
2648     *
2649     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2650     * out of the public fields to keep the undefined bits out of the developer's way.
2651     *
2652     * Flag to hide the center system info area.
2653     */
2654    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2655
2656    /**
2657     * @hide
2658     *
2659     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2660     * out of the public fields to keep the undefined bits out of the developer's way.
2661     *
2662     * Flag to hide only the home button.  Don't use this
2663     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2664     */
2665    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2666
2667    /**
2668     * @hide
2669     *
2670     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2671     * out of the public fields to keep the undefined bits out of the developer's way.
2672     *
2673     * Flag to hide only the back button. Don't use this
2674     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2675     */
2676    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2677
2678    /**
2679     * @hide
2680     *
2681     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2682     * out of the public fields to keep the undefined bits out of the developer's way.
2683     *
2684     * Flag to hide only the clock.  You might use this if your activity has
2685     * its own clock making the status bar's clock redundant.
2686     */
2687    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2688
2689    /**
2690     * @hide
2691     *
2692     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2693     * out of the public fields to keep the undefined bits out of the developer's way.
2694     *
2695     * Flag to hide only the recent apps button. Don't use this
2696     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2697     */
2698    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2699
2700    /**
2701     * @hide
2702     *
2703     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2704     * out of the public fields to keep the undefined bits out of the developer's way.
2705     *
2706     * Flag to disable the global search gesture. Don't use this
2707     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2708     */
2709    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2710
2711    /**
2712     * @hide
2713     *
2714     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2715     * out of the public fields to keep the undefined bits out of the developer's way.
2716     *
2717     * Flag to specify that the status bar is displayed in transient mode.
2718     */
2719    public static final int STATUS_BAR_TRANSIENT = 0x04000000;
2720
2721    /**
2722     * @hide
2723     *
2724     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2725     * out of the public fields to keep the undefined bits out of the developer's way.
2726     *
2727     * Flag to specify that the navigation bar is displayed in transient mode.
2728     */
2729    public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000;
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 hidden status bar would like to be shown.
2738     */
2739    public static final int STATUS_BAR_UNHIDE = 0x10000000;
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 hidden navigation bar would like to be shown.
2748     */
2749    public static final int NAVIGATION_BAR_UNHIDE = 0x20000000;
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 status bar is displayed in translucent mode.
2758     */
2759    public static final int STATUS_BAR_TRANSLUCENT = 0x40000000;
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 navigation bar is displayed in translucent mode.
2768     */
2769    public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000;
2770
2771    /**
2772     * @hide
2773     *
2774     * Whether Recents is visible or not.
2775     */
2776    public static final int RECENT_APPS_VISIBLE = 0x00004000;
2777
2778    /**
2779     * @hide
2780     *
2781     * Makes system ui transparent.
2782     */
2783    public static final int SYSTEM_UI_TRANSPARENT = 0x00008000;
2784
2785    /**
2786     * @hide
2787     */
2788    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF;
2789
2790    /**
2791     * These are the system UI flags that can be cleared by events outside
2792     * of an application.  Currently this is just the ability to tap on the
2793     * screen while hiding the navigation bar to have it return.
2794     * @hide
2795     */
2796    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2797            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2798            | SYSTEM_UI_FLAG_FULLSCREEN;
2799
2800    /**
2801     * Flags that can impact the layout in relation to system UI.
2802     */
2803    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2804            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2805            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2806
2807    /** @hide */
2808    @IntDef(flag = true,
2809            value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION })
2810    @Retention(RetentionPolicy.SOURCE)
2811    public @interface FindViewFlags {}
2812
2813    /**
2814     * Find views that render the specified text.
2815     *
2816     * @see #findViewsWithText(ArrayList, CharSequence, int)
2817     */
2818    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2819
2820    /**
2821     * Find find views that contain the specified content description.
2822     *
2823     * @see #findViewsWithText(ArrayList, CharSequence, int)
2824     */
2825    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2826
2827    /**
2828     * Find views that contain {@link AccessibilityNodeProvider}. Such
2829     * a View is a root of virtual view hierarchy and may contain the searched
2830     * text. If this flag is set Views with providers are automatically
2831     * added and it is a responsibility of the client to call the APIs of
2832     * the provider to determine whether the virtual tree rooted at this View
2833     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2834     * representing the virtual views with this text.
2835     *
2836     * @see #findViewsWithText(ArrayList, CharSequence, int)
2837     *
2838     * @hide
2839     */
2840    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2841
2842    /**
2843     * The undefined cursor position.
2844     *
2845     * @hide
2846     */
2847    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2848
2849    /**
2850     * Indicates that the screen has changed state and is now off.
2851     *
2852     * @see #onScreenStateChanged(int)
2853     */
2854    public static final int SCREEN_STATE_OFF = 0x0;
2855
2856    /**
2857     * Indicates that the screen has changed state and is now on.
2858     *
2859     * @see #onScreenStateChanged(int)
2860     */
2861    public static final int SCREEN_STATE_ON = 0x1;
2862
2863    /**
2864     * Indicates no axis of view scrolling.
2865     */
2866    public static final int SCROLL_AXIS_NONE = 0;
2867
2868    /**
2869     * Indicates scrolling along the horizontal axis.
2870     */
2871    public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0;
2872
2873    /**
2874     * Indicates scrolling along the vertical axis.
2875     */
2876    public static final int SCROLL_AXIS_VERTICAL = 1 << 1;
2877
2878    /**
2879     * Controls the over-scroll mode for this view.
2880     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2881     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2882     * and {@link #OVER_SCROLL_NEVER}.
2883     */
2884    private int mOverScrollMode;
2885
2886    /**
2887     * The parent this view is attached to.
2888     * {@hide}
2889     *
2890     * @see #getParent()
2891     */
2892    protected ViewParent mParent;
2893
2894    /**
2895     * {@hide}
2896     */
2897    AttachInfo mAttachInfo;
2898
2899    /**
2900     * {@hide}
2901     */
2902    @ViewDebug.ExportedProperty(flagMapping = {
2903        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2904                name = "FORCE_LAYOUT"),
2905        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2906                name = "LAYOUT_REQUIRED"),
2907        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2908            name = "DRAWING_CACHE_INVALID", outputIf = false),
2909        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2910        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2911        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2912        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2913    }, formatToHexString = true)
2914    int mPrivateFlags;
2915    int mPrivateFlags2;
2916    int mPrivateFlags3;
2917
2918    /**
2919     * This view's request for the visibility of the status bar.
2920     * @hide
2921     */
2922    @ViewDebug.ExportedProperty(flagMapping = {
2923        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2924                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2925                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2926        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2927                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2928                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2929        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2930                                equals = SYSTEM_UI_FLAG_VISIBLE,
2931                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2932    }, formatToHexString = true)
2933    int mSystemUiVisibility;
2934
2935    /**
2936     * Reference count for transient state.
2937     * @see #setHasTransientState(boolean)
2938     */
2939    int mTransientStateCount = 0;
2940
2941    /**
2942     * Count of how many windows this view has been attached to.
2943     */
2944    int mWindowAttachCount;
2945
2946    /**
2947     * The layout parameters associated with this view and used by the parent
2948     * {@link android.view.ViewGroup} to determine how this view should be
2949     * laid out.
2950     * {@hide}
2951     */
2952    protected ViewGroup.LayoutParams mLayoutParams;
2953
2954    /**
2955     * The view flags hold various views states.
2956     * {@hide}
2957     */
2958    @ViewDebug.ExportedProperty(formatToHexString = true)
2959    int mViewFlags;
2960
2961    static class TransformationInfo {
2962        /**
2963         * The transform matrix for the View. This transform is calculated internally
2964         * based on the translation, rotation, and scale properties.
2965         *
2966         * Do *not* use this variable directly; instead call getMatrix(), which will
2967         * load the value from the View's RenderNode.
2968         */
2969        private final Matrix mMatrix = new Matrix();
2970
2971        /**
2972         * The inverse transform matrix for the View. This transform is calculated
2973         * internally based on the translation, rotation, and scale properties.
2974         *
2975         * Do *not* use this variable directly; instead call getInverseMatrix(),
2976         * which will load the value from the View's RenderNode.
2977         */
2978        private Matrix mInverseMatrix;
2979
2980        /**
2981         * The opacity of the View. This is a value from 0 to 1, where 0 means
2982         * completely transparent and 1 means completely opaque.
2983         */
2984        @ViewDebug.ExportedProperty
2985        float mAlpha = 1f;
2986
2987        /**
2988         * The opacity of the view as manipulated by the Fade transition. This is a hidden
2989         * property only used by transitions, which is composited with the other alpha
2990         * values to calculate the final visual alpha value.
2991         */
2992        float mTransitionAlpha = 1f;
2993    }
2994
2995    TransformationInfo mTransformationInfo;
2996
2997    /**
2998     * Current clip bounds. to which all drawing of this view are constrained.
2999     */
3000    Rect mClipBounds = null;
3001
3002    private boolean mLastIsOpaque;
3003
3004    /**
3005     * The distance in pixels from the left edge of this view's parent
3006     * to the left edge of this view.
3007     * {@hide}
3008     */
3009    @ViewDebug.ExportedProperty(category = "layout")
3010    protected int mLeft;
3011    /**
3012     * The distance in pixels from the left edge of this view's parent
3013     * to the right edge of this view.
3014     * {@hide}
3015     */
3016    @ViewDebug.ExportedProperty(category = "layout")
3017    protected int mRight;
3018    /**
3019     * The distance in pixels from the top edge of this view's parent
3020     * to the top edge of this view.
3021     * {@hide}
3022     */
3023    @ViewDebug.ExportedProperty(category = "layout")
3024    protected int mTop;
3025    /**
3026     * The distance in pixels from the top edge of this view's parent
3027     * to the bottom edge of this view.
3028     * {@hide}
3029     */
3030    @ViewDebug.ExportedProperty(category = "layout")
3031    protected int mBottom;
3032
3033    /**
3034     * The offset, in pixels, by which the content of this view is scrolled
3035     * horizontally.
3036     * {@hide}
3037     */
3038    @ViewDebug.ExportedProperty(category = "scrolling")
3039    protected int mScrollX;
3040    /**
3041     * The offset, in pixels, by which the content of this view is scrolled
3042     * vertically.
3043     * {@hide}
3044     */
3045    @ViewDebug.ExportedProperty(category = "scrolling")
3046    protected int mScrollY;
3047
3048    /**
3049     * The left padding in pixels, that is the distance in pixels between the
3050     * left edge of this view and the left edge of its content.
3051     * {@hide}
3052     */
3053    @ViewDebug.ExportedProperty(category = "padding")
3054    protected int mPaddingLeft = 0;
3055    /**
3056     * The right padding in pixels, that is the distance in pixels between the
3057     * right edge of this view and the right edge of its content.
3058     * {@hide}
3059     */
3060    @ViewDebug.ExportedProperty(category = "padding")
3061    protected int mPaddingRight = 0;
3062    /**
3063     * The top padding in pixels, that is the distance in pixels between the
3064     * top edge of this view and the top edge of its content.
3065     * {@hide}
3066     */
3067    @ViewDebug.ExportedProperty(category = "padding")
3068    protected int mPaddingTop;
3069    /**
3070     * The bottom padding in pixels, that is the distance in pixels between the
3071     * bottom edge of this view and the bottom edge of its content.
3072     * {@hide}
3073     */
3074    @ViewDebug.ExportedProperty(category = "padding")
3075    protected int mPaddingBottom;
3076
3077    /**
3078     * The layout insets in pixels, that is the distance in pixels between the
3079     * visible edges of this view its bounds.
3080     */
3081    private Insets mLayoutInsets;
3082
3083    /**
3084     * Briefly describes the view and is primarily used for accessibility support.
3085     */
3086    private CharSequence mContentDescription;
3087
3088    /**
3089     * Specifies the id of a view for which this view serves as a label for
3090     * accessibility purposes.
3091     */
3092    private int mLabelForId = View.NO_ID;
3093
3094    /**
3095     * Predicate for matching labeled view id with its label for
3096     * accessibility purposes.
3097     */
3098    private MatchLabelForPredicate mMatchLabelForPredicate;
3099
3100    /**
3101     * Predicate for matching a view by its id.
3102     */
3103    private MatchIdPredicate mMatchIdPredicate;
3104
3105    /**
3106     * Cache the paddingRight set by the user to append to the scrollbar's size.
3107     *
3108     * @hide
3109     */
3110    @ViewDebug.ExportedProperty(category = "padding")
3111    protected int mUserPaddingRight;
3112
3113    /**
3114     * Cache the paddingBottom set by the user to append to the scrollbar's size.
3115     *
3116     * @hide
3117     */
3118    @ViewDebug.ExportedProperty(category = "padding")
3119    protected int mUserPaddingBottom;
3120
3121    /**
3122     * Cache the paddingLeft set by the user to append to the scrollbar's size.
3123     *
3124     * @hide
3125     */
3126    @ViewDebug.ExportedProperty(category = "padding")
3127    protected int mUserPaddingLeft;
3128
3129    /**
3130     * Cache the paddingStart set by the user to append to the scrollbar's size.
3131     *
3132     */
3133    @ViewDebug.ExportedProperty(category = "padding")
3134    int mUserPaddingStart;
3135
3136    /**
3137     * Cache the paddingEnd set by the user to append to the scrollbar's size.
3138     *
3139     */
3140    @ViewDebug.ExportedProperty(category = "padding")
3141    int mUserPaddingEnd;
3142
3143    /**
3144     * Cache initial left padding.
3145     *
3146     * @hide
3147     */
3148    int mUserPaddingLeftInitial;
3149
3150    /**
3151     * Cache initial right padding.
3152     *
3153     * @hide
3154     */
3155    int mUserPaddingRightInitial;
3156
3157    /**
3158     * Default undefined padding
3159     */
3160    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
3161
3162    /**
3163     * Cache if a left padding has been defined
3164     */
3165    private boolean mLeftPaddingDefined = false;
3166
3167    /**
3168     * Cache if a right padding has been defined
3169     */
3170    private boolean mRightPaddingDefined = false;
3171
3172    /**
3173     * @hide
3174     */
3175    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
3176    /**
3177     * @hide
3178     */
3179    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
3180
3181    private LongSparseLongArray mMeasureCache;
3182
3183    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
3184    private Drawable mBackground;
3185    private ColorStateList mBackgroundTintList = null;
3186    private PorterDuff.Mode mBackgroundTintMode = PorterDuff.Mode.SRC_ATOP;
3187    private boolean mHasBackgroundTint = false;
3188
3189    /**
3190     * RenderNode used for backgrounds.
3191     * <p>
3192     * When non-null and valid, this is expected to contain an up-to-date copy
3193     * of the background drawable. It is cleared on temporary detach, and reset
3194     * on cleanup.
3195     */
3196    private RenderNode mBackgroundRenderNode;
3197
3198    private int mBackgroundResource;
3199    private boolean mBackgroundSizeChanged;
3200
3201    private String mTransitionName;
3202
3203    static class ListenerInfo {
3204        /**
3205         * Listener used to dispatch focus change events.
3206         * This field should be made private, so it is hidden from the SDK.
3207         * {@hide}
3208         */
3209        protected OnFocusChangeListener mOnFocusChangeListener;
3210
3211        /**
3212         * Listeners for layout change events.
3213         */
3214        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
3215
3216        /**
3217         * Listeners for attach events.
3218         */
3219        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
3220
3221        /**
3222         * Listener used to dispatch click events.
3223         * This field should be made private, so it is hidden from the SDK.
3224         * {@hide}
3225         */
3226        public OnClickListener mOnClickListener;
3227
3228        /**
3229         * Listener used to dispatch long click events.
3230         * This field should be made private, so it is hidden from the SDK.
3231         * {@hide}
3232         */
3233        protected OnLongClickListener mOnLongClickListener;
3234
3235        /**
3236         * Listener used to build the context menu.
3237         * This field should be made private, so it is hidden from the SDK.
3238         * {@hide}
3239         */
3240        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
3241
3242        private OnKeyListener mOnKeyListener;
3243
3244        private OnTouchListener mOnTouchListener;
3245
3246        private OnHoverListener mOnHoverListener;
3247
3248        private OnGenericMotionListener mOnGenericMotionListener;
3249
3250        private OnDragListener mOnDragListener;
3251
3252        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
3253
3254        OnApplyWindowInsetsListener mOnApplyWindowInsetsListener;
3255    }
3256
3257    ListenerInfo mListenerInfo;
3258
3259    /**
3260     * The application environment this view lives in.
3261     * This field should be made private, so it is hidden from the SDK.
3262     * {@hide}
3263     */
3264    @ViewDebug.ExportedProperty(deepExport = true)
3265    protected Context mContext;
3266
3267    private final Resources mResources;
3268
3269    private ScrollabilityCache mScrollCache;
3270
3271    private int[] mDrawableState = null;
3272
3273    ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND;
3274
3275    /**
3276     * Animator that automatically runs based on state changes.
3277     */
3278    private StateListAnimator mStateListAnimator;
3279
3280    /**
3281     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3282     * the user may specify which view to go to next.
3283     */
3284    private int mNextFocusLeftId = View.NO_ID;
3285
3286    /**
3287     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3288     * the user may specify which view to go to next.
3289     */
3290    private int mNextFocusRightId = View.NO_ID;
3291
3292    /**
3293     * When this view has focus and the next focus is {@link #FOCUS_UP},
3294     * the user may specify which view to go to next.
3295     */
3296    private int mNextFocusUpId = View.NO_ID;
3297
3298    /**
3299     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3300     * the user may specify which view to go to next.
3301     */
3302    private int mNextFocusDownId = View.NO_ID;
3303
3304    /**
3305     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3306     * the user may specify which view to go to next.
3307     */
3308    int mNextFocusForwardId = View.NO_ID;
3309
3310    private CheckForLongPress mPendingCheckForLongPress;
3311    private CheckForTap mPendingCheckForTap = null;
3312    private PerformClick mPerformClick;
3313    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3314
3315    private UnsetPressedState mUnsetPressedState;
3316
3317    /**
3318     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3319     * up event while a long press is invoked as soon as the long press duration is reached, so
3320     * a long press could be performed before the tap is checked, in which case the tap's action
3321     * should not be invoked.
3322     */
3323    private boolean mHasPerformedLongPress;
3324
3325    /**
3326     * The minimum height of the view. We'll try our best to have the height
3327     * of this view to at least this amount.
3328     */
3329    @ViewDebug.ExportedProperty(category = "measurement")
3330    private int mMinHeight;
3331
3332    /**
3333     * The minimum width of the view. We'll try our best to have the width
3334     * of this view to at least this amount.
3335     */
3336    @ViewDebug.ExportedProperty(category = "measurement")
3337    private int mMinWidth;
3338
3339    /**
3340     * The delegate to handle touch events that are physically in this view
3341     * but should be handled by another view.
3342     */
3343    private TouchDelegate mTouchDelegate = null;
3344
3345    /**
3346     * Solid color to use as a background when creating the drawing cache. Enables
3347     * the cache to use 16 bit bitmaps instead of 32 bit.
3348     */
3349    private int mDrawingCacheBackgroundColor = 0;
3350
3351    /**
3352     * Special tree observer used when mAttachInfo is null.
3353     */
3354    private ViewTreeObserver mFloatingTreeObserver;
3355
3356    /**
3357     * Cache the touch slop from the context that created the view.
3358     */
3359    private int mTouchSlop;
3360
3361    /**
3362     * Object that handles automatic animation of view properties.
3363     */
3364    private ViewPropertyAnimator mAnimator = null;
3365
3366    /**
3367     * Flag indicating that a drag can cross window boundaries.  When
3368     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3369     * with this flag set, all visible applications will be able to participate
3370     * in the drag operation and receive the dragged content.
3371     *
3372     * @hide
3373     */
3374    public static final int DRAG_FLAG_GLOBAL = 1;
3375
3376    /**
3377     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3378     */
3379    private float mVerticalScrollFactor;
3380
3381    /**
3382     * Position of the vertical scroll bar.
3383     */
3384    private int mVerticalScrollbarPosition;
3385
3386    /**
3387     * Position the scroll bar at the default position as determined by the system.
3388     */
3389    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3390
3391    /**
3392     * Position the scroll bar along the left edge.
3393     */
3394    public static final int SCROLLBAR_POSITION_LEFT = 1;
3395
3396    /**
3397     * Position the scroll bar along the right edge.
3398     */
3399    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3400
3401    /**
3402     * Indicates that the view does not have a layer.
3403     *
3404     * @see #getLayerType()
3405     * @see #setLayerType(int, android.graphics.Paint)
3406     * @see #LAYER_TYPE_SOFTWARE
3407     * @see #LAYER_TYPE_HARDWARE
3408     */
3409    public static final int LAYER_TYPE_NONE = 0;
3410
3411    /**
3412     * <p>Indicates that the view has a software layer. A software layer is backed
3413     * by a bitmap and causes the view to be rendered using Android's software
3414     * rendering pipeline, even if hardware acceleration is enabled.</p>
3415     *
3416     * <p>Software layers have various usages:</p>
3417     * <p>When the application is not using hardware acceleration, a software layer
3418     * is useful to apply a specific color filter and/or blending mode and/or
3419     * translucency to a view and all its children.</p>
3420     * <p>When the application is using hardware acceleration, a software layer
3421     * is useful to render drawing primitives not supported by the hardware
3422     * accelerated pipeline. It can also be used to cache a complex view tree
3423     * into a texture and reduce the complexity of drawing operations. For instance,
3424     * when animating a complex view tree with a translation, a software layer can
3425     * be used to render the view tree only once.</p>
3426     * <p>Software layers should be avoided when the affected view tree updates
3427     * often. Every update will require to re-render the software layer, which can
3428     * potentially be slow (particularly when hardware acceleration is turned on
3429     * since the layer will have to be uploaded into a hardware texture after every
3430     * update.)</p>
3431     *
3432     * @see #getLayerType()
3433     * @see #setLayerType(int, android.graphics.Paint)
3434     * @see #LAYER_TYPE_NONE
3435     * @see #LAYER_TYPE_HARDWARE
3436     */
3437    public static final int LAYER_TYPE_SOFTWARE = 1;
3438
3439    /**
3440     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3441     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3442     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3443     * rendering pipeline, but only if hardware acceleration is turned on for the
3444     * view hierarchy. When hardware acceleration is turned off, hardware layers
3445     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3446     *
3447     * <p>A hardware layer is useful to apply a specific color filter and/or
3448     * blending mode and/or translucency to a view and all its children.</p>
3449     * <p>A hardware layer can be used to cache a complex view tree into a
3450     * texture and reduce the complexity of drawing operations. For instance,
3451     * when animating a complex view tree with a translation, a hardware layer can
3452     * be used to render the view tree only once.</p>
3453     * <p>A hardware layer can also be used to increase the rendering quality when
3454     * rotation transformations are applied on a view. It can also be used to
3455     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3456     *
3457     * @see #getLayerType()
3458     * @see #setLayerType(int, android.graphics.Paint)
3459     * @see #LAYER_TYPE_NONE
3460     * @see #LAYER_TYPE_SOFTWARE
3461     */
3462    public static final int LAYER_TYPE_HARDWARE = 2;
3463
3464    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3465            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3466            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3467            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3468    })
3469    int mLayerType = LAYER_TYPE_NONE;
3470    Paint mLayerPaint;
3471
3472    /**
3473     * Set to true when drawing cache is enabled and cannot be created.
3474     *
3475     * @hide
3476     */
3477    public boolean mCachingFailed;
3478    private Bitmap mDrawingCache;
3479    private Bitmap mUnscaledDrawingCache;
3480
3481    /**
3482     * RenderNode holding View properties, potentially holding a DisplayList of View content.
3483     * <p>
3484     * When non-null and valid, this is expected to contain an up-to-date copy
3485     * of the View content. Its DisplayList content is cleared on temporary detach and reset on
3486     * cleanup.
3487     */
3488    final RenderNode mRenderNode;
3489
3490    /**
3491     * Set to true when the view is sending hover accessibility events because it
3492     * is the innermost hovered view.
3493     */
3494    private boolean mSendingHoverAccessibilityEvents;
3495
3496    /**
3497     * Delegate for injecting accessibility functionality.
3498     */
3499    AccessibilityDelegate mAccessibilityDelegate;
3500
3501    /**
3502     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3503     * and add/remove objects to/from the overlay directly through the Overlay methods.
3504     */
3505    ViewOverlay mOverlay;
3506
3507    /**
3508     * The currently active parent view for receiving delegated nested scrolling events.
3509     * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared
3510     * by {@link #stopNestedScroll()} at the same point where we clear
3511     * requestDisallowInterceptTouchEvent.
3512     */
3513    private ViewParent mNestedScrollingParent;
3514
3515    /**
3516     * Consistency verifier for debugging purposes.
3517     * @hide
3518     */
3519    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3520            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3521                    new InputEventConsistencyVerifier(this, 0) : null;
3522
3523    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3524
3525    private int[] mTempNestedScrollConsumed;
3526
3527    /**
3528     * An overlay is going to draw this View instead of being drawn as part of this
3529     * View's parent. mGhostView is the View in the Overlay that must be invalidated
3530     * when this view is invalidated.
3531     */
3532    GhostView mGhostView;
3533
3534    /**
3535     * Holds pairs of adjacent attribute data: attribute name followed by its value.
3536     * @hide
3537     */
3538    @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true)
3539    public String[] mAttributes;
3540
3541    /**
3542     * Maps a Resource id to its name.
3543     */
3544    private static SparseArray<String> mAttributeMap;
3545
3546    /**
3547     * Simple constructor to use when creating a view from code.
3548     *
3549     * @param context The Context the view is running in, through which it can
3550     *        access the current theme, resources, etc.
3551     */
3552    public View(Context context) {
3553        mContext = context;
3554        mResources = context != null ? context.getResources() : null;
3555        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3556        // Set some flags defaults
3557        mPrivateFlags2 =
3558                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3559                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3560                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3561                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3562                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3563                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3564        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3565        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3566        mUserPaddingStart = UNDEFINED_PADDING;
3567        mUserPaddingEnd = UNDEFINED_PADDING;
3568        mRenderNode = RenderNode.create(getClass().getName());
3569
3570        if (!sCompatibilityDone && context != null) {
3571            final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3572
3573            // Older apps may need this compatibility hack for measurement.
3574            sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1;
3575
3576            // Older apps expect onMeasure() to always be called on a layout pass, regardless
3577            // of whether a layout was requested on that View.
3578            sIgnoreMeasureCache = targetSdkVersion < KITKAT;
3579
3580            sCompatibilityDone = true;
3581        }
3582    }
3583
3584    /**
3585     * Constructor that is called when inflating a view from XML. This is called
3586     * when a view is being constructed from an XML file, supplying attributes
3587     * that were specified in the XML file. This version uses a default style of
3588     * 0, so the only attribute values applied are those in the Context's Theme
3589     * and the given AttributeSet.
3590     *
3591     * <p>
3592     * The method onFinishInflate() will be called after all children have been
3593     * added.
3594     *
3595     * @param context The Context the view is running in, through which it can
3596     *        access the current theme, resources, etc.
3597     * @param attrs The attributes of the XML tag that is inflating the view.
3598     * @see #View(Context, AttributeSet, int)
3599     */
3600    public View(Context context, AttributeSet attrs) {
3601        this(context, attrs, 0);
3602    }
3603
3604    /**
3605     * Perform inflation from XML and apply a class-specific base style from a
3606     * theme attribute. This constructor of View allows subclasses to use their
3607     * own base style when they are inflating. For example, a Button class's
3608     * constructor would call this version of the super class constructor and
3609     * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this
3610     * allows the theme's button style to modify all of the base view attributes
3611     * (in particular its background) as well as the Button class's attributes.
3612     *
3613     * @param context The Context the view is running in, through which it can
3614     *        access the current theme, resources, etc.
3615     * @param attrs The attributes of the XML tag that is inflating the view.
3616     * @param defStyleAttr An attribute in the current theme that contains a
3617     *        reference to a style resource that supplies default values for
3618     *        the view. Can be 0 to not look for defaults.
3619     * @see #View(Context, AttributeSet)
3620     */
3621    public View(Context context, AttributeSet attrs, int defStyleAttr) {
3622        this(context, attrs, defStyleAttr, 0);
3623    }
3624
3625    /**
3626     * Perform inflation from XML and apply a class-specific base style from a
3627     * theme attribute or style resource. This constructor of View allows
3628     * subclasses to use their own base style when they are inflating.
3629     * <p>
3630     * When determining the final value of a particular attribute, there are
3631     * four inputs that come into play:
3632     * <ol>
3633     * <li>Any attribute values in the given AttributeSet.
3634     * <li>The style resource specified in the AttributeSet (named "style").
3635     * <li>The default style specified by <var>defStyleAttr</var>.
3636     * <li>The default style specified by <var>defStyleRes</var>.
3637     * <li>The base values in this theme.
3638     * </ol>
3639     * <p>
3640     * Each of these inputs is considered in-order, with the first listed taking
3641     * precedence over the following ones. In other words, if in the
3642     * AttributeSet you have supplied <code>&lt;Button * textColor="#ff000000"&gt;</code>
3643     * , then the button's text will <em>always</em> be black, regardless of
3644     * what is specified in any of the styles.
3645     *
3646     * @param context The Context the view is running in, through which it can
3647     *        access the current theme, resources, etc.
3648     * @param attrs The attributes of the XML tag that is inflating the view.
3649     * @param defStyleAttr An attribute in the current theme that contains a
3650     *        reference to a style resource that supplies default values for
3651     *        the view. Can be 0 to not look for defaults.
3652     * @param defStyleRes A resource identifier of a style resource that
3653     *        supplies default values for the view, used only if
3654     *        defStyleAttr is 0 or can not be found in the theme. Can be 0
3655     *        to not look for defaults.
3656     * @see #View(Context, AttributeSet, int)
3657     */
3658    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
3659        this(context);
3660
3661        final TypedArray a = context.obtainStyledAttributes(
3662                attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes);
3663
3664        if (mDebugViewAttributes) {
3665            saveAttributeData(attrs, a);
3666        }
3667
3668        Drawable background = null;
3669
3670        int leftPadding = -1;
3671        int topPadding = -1;
3672        int rightPadding = -1;
3673        int bottomPadding = -1;
3674        int startPadding = UNDEFINED_PADDING;
3675        int endPadding = UNDEFINED_PADDING;
3676
3677        int padding = -1;
3678
3679        int viewFlagValues = 0;
3680        int viewFlagMasks = 0;
3681
3682        boolean setScrollContainer = false;
3683
3684        int x = 0;
3685        int y = 0;
3686
3687        float tx = 0;
3688        float ty = 0;
3689        float tz = 0;
3690        float elevation = 0;
3691        float rotation = 0;
3692        float rotationX = 0;
3693        float rotationY = 0;
3694        float sx = 1f;
3695        float sy = 1f;
3696        boolean transformSet = false;
3697
3698        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3699        int overScrollMode = mOverScrollMode;
3700        boolean initializeScrollbars = false;
3701
3702        boolean startPaddingDefined = false;
3703        boolean endPaddingDefined = false;
3704        boolean leftPaddingDefined = false;
3705        boolean rightPaddingDefined = false;
3706
3707        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3708
3709        final int N = a.getIndexCount();
3710        for (int i = 0; i < N; i++) {
3711            int attr = a.getIndex(i);
3712            switch (attr) {
3713                case com.android.internal.R.styleable.View_background:
3714                    background = a.getDrawable(attr);
3715                    break;
3716                case com.android.internal.R.styleable.View_padding:
3717                    padding = a.getDimensionPixelSize(attr, -1);
3718                    mUserPaddingLeftInitial = padding;
3719                    mUserPaddingRightInitial = padding;
3720                    leftPaddingDefined = true;
3721                    rightPaddingDefined = true;
3722                    break;
3723                 case com.android.internal.R.styleable.View_paddingLeft:
3724                    leftPadding = a.getDimensionPixelSize(attr, -1);
3725                    mUserPaddingLeftInitial = leftPadding;
3726                    leftPaddingDefined = true;
3727                    break;
3728                case com.android.internal.R.styleable.View_paddingTop:
3729                    topPadding = a.getDimensionPixelSize(attr, -1);
3730                    break;
3731                case com.android.internal.R.styleable.View_paddingRight:
3732                    rightPadding = a.getDimensionPixelSize(attr, -1);
3733                    mUserPaddingRightInitial = rightPadding;
3734                    rightPaddingDefined = true;
3735                    break;
3736                case com.android.internal.R.styleable.View_paddingBottom:
3737                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3738                    break;
3739                case com.android.internal.R.styleable.View_paddingStart:
3740                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3741                    startPaddingDefined = (startPadding != UNDEFINED_PADDING);
3742                    break;
3743                case com.android.internal.R.styleable.View_paddingEnd:
3744                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3745                    endPaddingDefined = (endPadding != UNDEFINED_PADDING);
3746                    break;
3747                case com.android.internal.R.styleable.View_scrollX:
3748                    x = a.getDimensionPixelOffset(attr, 0);
3749                    break;
3750                case com.android.internal.R.styleable.View_scrollY:
3751                    y = a.getDimensionPixelOffset(attr, 0);
3752                    break;
3753                case com.android.internal.R.styleable.View_alpha:
3754                    setAlpha(a.getFloat(attr, 1f));
3755                    break;
3756                case com.android.internal.R.styleable.View_transformPivotX:
3757                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3758                    break;
3759                case com.android.internal.R.styleable.View_transformPivotY:
3760                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3761                    break;
3762                case com.android.internal.R.styleable.View_translationX:
3763                    tx = a.getDimensionPixelOffset(attr, 0);
3764                    transformSet = true;
3765                    break;
3766                case com.android.internal.R.styleable.View_translationY:
3767                    ty = a.getDimensionPixelOffset(attr, 0);
3768                    transformSet = true;
3769                    break;
3770                case com.android.internal.R.styleable.View_translationZ:
3771                    tz = a.getDimensionPixelOffset(attr, 0);
3772                    transformSet = true;
3773                    break;
3774                case com.android.internal.R.styleable.View_elevation:
3775                    elevation = a.getDimensionPixelOffset(attr, 0);
3776                    transformSet = true;
3777                    break;
3778                case com.android.internal.R.styleable.View_rotation:
3779                    rotation = a.getFloat(attr, 0);
3780                    transformSet = true;
3781                    break;
3782                case com.android.internal.R.styleable.View_rotationX:
3783                    rotationX = a.getFloat(attr, 0);
3784                    transformSet = true;
3785                    break;
3786                case com.android.internal.R.styleable.View_rotationY:
3787                    rotationY = a.getFloat(attr, 0);
3788                    transformSet = true;
3789                    break;
3790                case com.android.internal.R.styleable.View_scaleX:
3791                    sx = a.getFloat(attr, 1f);
3792                    transformSet = true;
3793                    break;
3794                case com.android.internal.R.styleable.View_scaleY:
3795                    sy = a.getFloat(attr, 1f);
3796                    transformSet = true;
3797                    break;
3798                case com.android.internal.R.styleable.View_id:
3799                    mID = a.getResourceId(attr, NO_ID);
3800                    break;
3801                case com.android.internal.R.styleable.View_tag:
3802                    mTag = a.getText(attr);
3803                    break;
3804                case com.android.internal.R.styleable.View_fitsSystemWindows:
3805                    if (a.getBoolean(attr, false)) {
3806                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3807                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3808                    }
3809                    break;
3810                case com.android.internal.R.styleable.View_focusable:
3811                    if (a.getBoolean(attr, false)) {
3812                        viewFlagValues |= FOCUSABLE;
3813                        viewFlagMasks |= FOCUSABLE_MASK;
3814                    }
3815                    break;
3816                case com.android.internal.R.styleable.View_focusableInTouchMode:
3817                    if (a.getBoolean(attr, false)) {
3818                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3819                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3820                    }
3821                    break;
3822                case com.android.internal.R.styleable.View_clickable:
3823                    if (a.getBoolean(attr, false)) {
3824                        viewFlagValues |= CLICKABLE;
3825                        viewFlagMasks |= CLICKABLE;
3826                    }
3827                    break;
3828                case com.android.internal.R.styleable.View_longClickable:
3829                    if (a.getBoolean(attr, false)) {
3830                        viewFlagValues |= LONG_CLICKABLE;
3831                        viewFlagMasks |= LONG_CLICKABLE;
3832                    }
3833                    break;
3834                case com.android.internal.R.styleable.View_saveEnabled:
3835                    if (!a.getBoolean(attr, true)) {
3836                        viewFlagValues |= SAVE_DISABLED;
3837                        viewFlagMasks |= SAVE_DISABLED_MASK;
3838                    }
3839                    break;
3840                case com.android.internal.R.styleable.View_duplicateParentState:
3841                    if (a.getBoolean(attr, false)) {
3842                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3843                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3844                    }
3845                    break;
3846                case com.android.internal.R.styleable.View_visibility:
3847                    final int visibility = a.getInt(attr, 0);
3848                    if (visibility != 0) {
3849                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3850                        viewFlagMasks |= VISIBILITY_MASK;
3851                    }
3852                    break;
3853                case com.android.internal.R.styleable.View_layoutDirection:
3854                    // Clear any layout direction flags (included resolved bits) already set
3855                    mPrivateFlags2 &=
3856                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3857                    // Set the layout direction flags depending on the value of the attribute
3858                    final int layoutDirection = a.getInt(attr, -1);
3859                    final int value = (layoutDirection != -1) ?
3860                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3861                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3862                    break;
3863                case com.android.internal.R.styleable.View_drawingCacheQuality:
3864                    final int cacheQuality = a.getInt(attr, 0);
3865                    if (cacheQuality != 0) {
3866                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3867                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3868                    }
3869                    break;
3870                case com.android.internal.R.styleable.View_contentDescription:
3871                    setContentDescription(a.getString(attr));
3872                    break;
3873                case com.android.internal.R.styleable.View_labelFor:
3874                    setLabelFor(a.getResourceId(attr, NO_ID));
3875                    break;
3876                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3877                    if (!a.getBoolean(attr, true)) {
3878                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3879                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3880                    }
3881                    break;
3882                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3883                    if (!a.getBoolean(attr, true)) {
3884                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3885                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3886                    }
3887                    break;
3888                case R.styleable.View_scrollbars:
3889                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3890                    if (scrollbars != SCROLLBARS_NONE) {
3891                        viewFlagValues |= scrollbars;
3892                        viewFlagMasks |= SCROLLBARS_MASK;
3893                        initializeScrollbars = true;
3894                    }
3895                    break;
3896                //noinspection deprecation
3897                case R.styleable.View_fadingEdge:
3898                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3899                        // Ignore the attribute starting with ICS
3900                        break;
3901                    }
3902                    // With builds < ICS, fall through and apply fading edges
3903                case R.styleable.View_requiresFadingEdge:
3904                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3905                    if (fadingEdge != FADING_EDGE_NONE) {
3906                        viewFlagValues |= fadingEdge;
3907                        viewFlagMasks |= FADING_EDGE_MASK;
3908                        initializeFadingEdgeInternal(a);
3909                    }
3910                    break;
3911                case R.styleable.View_scrollbarStyle:
3912                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3913                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3914                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3915                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3916                    }
3917                    break;
3918                case R.styleable.View_isScrollContainer:
3919                    setScrollContainer = true;
3920                    if (a.getBoolean(attr, false)) {
3921                        setScrollContainer(true);
3922                    }
3923                    break;
3924                case com.android.internal.R.styleable.View_keepScreenOn:
3925                    if (a.getBoolean(attr, false)) {
3926                        viewFlagValues |= KEEP_SCREEN_ON;
3927                        viewFlagMasks |= KEEP_SCREEN_ON;
3928                    }
3929                    break;
3930                case R.styleable.View_filterTouchesWhenObscured:
3931                    if (a.getBoolean(attr, false)) {
3932                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3933                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3934                    }
3935                    break;
3936                case R.styleable.View_nextFocusLeft:
3937                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3938                    break;
3939                case R.styleable.View_nextFocusRight:
3940                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3941                    break;
3942                case R.styleable.View_nextFocusUp:
3943                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3944                    break;
3945                case R.styleable.View_nextFocusDown:
3946                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3947                    break;
3948                case R.styleable.View_nextFocusForward:
3949                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3950                    break;
3951                case R.styleable.View_minWidth:
3952                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3953                    break;
3954                case R.styleable.View_minHeight:
3955                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3956                    break;
3957                case R.styleable.View_onClick:
3958                    if (context.isRestricted()) {
3959                        throw new IllegalStateException("The android:onClick attribute cannot "
3960                                + "be used within a restricted context");
3961                    }
3962
3963                    final String handlerName = a.getString(attr);
3964                    if (handlerName != null) {
3965                        setOnClickListener(new OnClickListener() {
3966                            private Method mHandler;
3967
3968                            public void onClick(View v) {
3969                                if (mHandler == null) {
3970                                    try {
3971                                        mHandler = getContext().getClass().getMethod(handlerName,
3972                                                View.class);
3973                                    } catch (NoSuchMethodException e) {
3974                                        int id = getId();
3975                                        String idText = id == NO_ID ? "" : " with id '"
3976                                                + getContext().getResources().getResourceEntryName(
3977                                                    id) + "'";
3978                                        throw new IllegalStateException("Could not find a method " +
3979                                                handlerName + "(View) in the activity "
3980                                                + getContext().getClass() + " for onClick handler"
3981                                                + " on view " + View.this.getClass() + idText, e);
3982                                    }
3983                                }
3984
3985                                try {
3986                                    mHandler.invoke(getContext(), View.this);
3987                                } catch (IllegalAccessException e) {
3988                                    throw new IllegalStateException("Could not execute non "
3989                                            + "public method of the activity", e);
3990                                } catch (InvocationTargetException e) {
3991                                    throw new IllegalStateException("Could not execute "
3992                                            + "method of the activity", e);
3993                                }
3994                            }
3995                        });
3996                    }
3997                    break;
3998                case R.styleable.View_overScrollMode:
3999                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
4000                    break;
4001                case R.styleable.View_verticalScrollbarPosition:
4002                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
4003                    break;
4004                case R.styleable.View_layerType:
4005                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
4006                    break;
4007                case R.styleable.View_textDirection:
4008                    // Clear any text direction flag already set
4009                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
4010                    // Set the text direction flags depending on the value of the attribute
4011                    final int textDirection = a.getInt(attr, -1);
4012                    if (textDirection != -1) {
4013                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
4014                    }
4015                    break;
4016                case R.styleable.View_textAlignment:
4017                    // Clear any text alignment flag already set
4018                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
4019                    // Set the text alignment flag depending on the value of the attribute
4020                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
4021                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
4022                    break;
4023                case R.styleable.View_importantForAccessibility:
4024                    setImportantForAccessibility(a.getInt(attr,
4025                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
4026                    break;
4027                case R.styleable.View_accessibilityLiveRegion:
4028                    setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
4029                    break;
4030                case R.styleable.View_transitionName:
4031                    setTransitionName(a.getString(attr));
4032                    break;
4033                case R.styleable.View_nestedScrollingEnabled:
4034                    setNestedScrollingEnabled(a.getBoolean(attr, false));
4035                    break;
4036                case R.styleable.View_stateListAnimator:
4037                    setStateListAnimator(AnimatorInflater.loadStateListAnimator(context,
4038                            a.getResourceId(attr, 0)));
4039                    break;
4040                case R.styleable.View_backgroundTint:
4041                    // This will get applied later during setBackground().
4042                    mBackgroundTintList = a.getColorStateList(R.styleable.View_backgroundTint);
4043                    mHasBackgroundTint = true;
4044                    break;
4045                case R.styleable.View_backgroundTintMode:
4046                    // This will get applied later during setBackground().
4047                    mBackgroundTintMode = Drawable.parseTintMode(a.getInt(
4048                            R.styleable.View_backgroundTintMode, -1), mBackgroundTintMode);
4049                    break;
4050                case R.styleable.View_outlineProvider:
4051                    setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider,
4052                            PROVIDER_BACKGROUND));
4053                    break;
4054            }
4055        }
4056
4057        setOverScrollMode(overScrollMode);
4058
4059        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
4060        // the resolved layout direction). Those cached values will be used later during padding
4061        // resolution.
4062        mUserPaddingStart = startPadding;
4063        mUserPaddingEnd = endPadding;
4064
4065        if (background != null) {
4066            setBackground(background);
4067        }
4068
4069        // setBackground above will record that padding is currently provided by the background.
4070        // If we have padding specified via xml, record that here instead and use it.
4071        mLeftPaddingDefined = leftPaddingDefined;
4072        mRightPaddingDefined = rightPaddingDefined;
4073
4074        if (padding >= 0) {
4075            leftPadding = padding;
4076            topPadding = padding;
4077            rightPadding = padding;
4078            bottomPadding = padding;
4079            mUserPaddingLeftInitial = padding;
4080            mUserPaddingRightInitial = padding;
4081        }
4082
4083        if (isRtlCompatibilityMode()) {
4084            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
4085            // left / right padding are used if defined (meaning here nothing to do). If they are not
4086            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
4087            // start / end and resolve them as left / right (layout direction is not taken into account).
4088            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4089            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4090            // defined.
4091            if (!mLeftPaddingDefined && startPaddingDefined) {
4092                leftPadding = startPadding;
4093            }
4094            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
4095            if (!mRightPaddingDefined && endPaddingDefined) {
4096                rightPadding = endPadding;
4097            }
4098            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
4099        } else {
4100            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
4101            // values defined. Otherwise, left /right values are used.
4102            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
4103            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
4104            // defined.
4105            final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;
4106
4107            if (mLeftPaddingDefined && !hasRelativePadding) {
4108                mUserPaddingLeftInitial = leftPadding;
4109            }
4110            if (mRightPaddingDefined && !hasRelativePadding) {
4111                mUserPaddingRightInitial = rightPadding;
4112            }
4113        }
4114
4115        internalSetPadding(
4116                mUserPaddingLeftInitial,
4117                topPadding >= 0 ? topPadding : mPaddingTop,
4118                mUserPaddingRightInitial,
4119                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
4120
4121        if (viewFlagMasks != 0) {
4122            setFlags(viewFlagValues, viewFlagMasks);
4123        }
4124
4125        if (initializeScrollbars) {
4126            initializeScrollbarsInternal(a);
4127        }
4128
4129        a.recycle();
4130
4131        // Needs to be called after mViewFlags is set
4132        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
4133            recomputePadding();
4134        }
4135
4136        if (x != 0 || y != 0) {
4137            scrollTo(x, y);
4138        }
4139
4140        if (transformSet) {
4141            setTranslationX(tx);
4142            setTranslationY(ty);
4143            setTranslationZ(tz);
4144            setElevation(elevation);
4145            setRotation(rotation);
4146            setRotationX(rotationX);
4147            setRotationY(rotationY);
4148            setScaleX(sx);
4149            setScaleY(sy);
4150        }
4151
4152        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
4153            setScrollContainer(true);
4154        }
4155
4156        computeOpaqueFlags();
4157    }
4158
4159    /**
4160     * Non-public constructor for use in testing
4161     */
4162    View() {
4163        mResources = null;
4164        mRenderNode = RenderNode.create(getClass().getName());
4165    }
4166
4167    private static SparseArray<String> getAttributeMap() {
4168        if (mAttributeMap == null) {
4169            mAttributeMap = new SparseArray<String>();
4170        }
4171        return mAttributeMap;
4172    }
4173
4174    private void saveAttributeData(AttributeSet attrs, TypedArray a) {
4175        int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2;
4176        mAttributes = new String[length];
4177
4178        int i = 0;
4179        if (attrs != null) {
4180            for (i = 0; i < attrs.getAttributeCount(); i += 2) {
4181                mAttributes[i] = attrs.getAttributeName(i);
4182                mAttributes[i + 1] = attrs.getAttributeValue(i);
4183            }
4184
4185        }
4186
4187        SparseArray<String> attributeMap = getAttributeMap();
4188        for (int j = 0; j < a.length(); ++j) {
4189            if (a.hasValue(j)) {
4190                try {
4191                    int resourceId = a.getResourceId(j, 0);
4192                    if (resourceId == 0) {
4193                        continue;
4194                    }
4195
4196                    String resourceName = attributeMap.get(resourceId);
4197                    if (resourceName == null) {
4198                        resourceName = a.getResources().getResourceName(resourceId);
4199                        attributeMap.put(resourceId, resourceName);
4200                    }
4201
4202                    mAttributes[i] = resourceName;
4203                    mAttributes[i + 1] = a.getText(j).toString();
4204                    i += 2;
4205                } catch (Resources.NotFoundException e) {
4206                    // if we can't get the resource name, we just ignore it
4207                }
4208            }
4209        }
4210    }
4211
4212    public String toString() {
4213        StringBuilder out = new StringBuilder(128);
4214        out.append(getClass().getName());
4215        out.append('{');
4216        out.append(Integer.toHexString(System.identityHashCode(this)));
4217        out.append(' ');
4218        switch (mViewFlags&VISIBILITY_MASK) {
4219            case VISIBLE: out.append('V'); break;
4220            case INVISIBLE: out.append('I'); break;
4221            case GONE: out.append('G'); break;
4222            default: out.append('.'); break;
4223        }
4224        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
4225        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
4226        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
4227        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
4228        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
4229        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
4230        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
4231        out.append(' ');
4232        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
4233        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
4234        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
4235        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
4236            out.append('p');
4237        } else {
4238            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
4239        }
4240        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
4241        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
4242        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
4243        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
4244        out.append(' ');
4245        out.append(mLeft);
4246        out.append(',');
4247        out.append(mTop);
4248        out.append('-');
4249        out.append(mRight);
4250        out.append(',');
4251        out.append(mBottom);
4252        final int id = getId();
4253        if (id != NO_ID) {
4254            out.append(" #");
4255            out.append(Integer.toHexString(id));
4256            final Resources r = mResources;
4257            if (Resources.resourceHasPackage(id) && r != null) {
4258                try {
4259                    String pkgname;
4260                    switch (id&0xff000000) {
4261                        case 0x7f000000:
4262                            pkgname="app";
4263                            break;
4264                        case 0x01000000:
4265                            pkgname="android";
4266                            break;
4267                        default:
4268                            pkgname = r.getResourcePackageName(id);
4269                            break;
4270                    }
4271                    String typename = r.getResourceTypeName(id);
4272                    String entryname = r.getResourceEntryName(id);
4273                    out.append(" ");
4274                    out.append(pkgname);
4275                    out.append(":");
4276                    out.append(typename);
4277                    out.append("/");
4278                    out.append(entryname);
4279                } catch (Resources.NotFoundException e) {
4280                }
4281            }
4282        }
4283        out.append("}");
4284        return out.toString();
4285    }
4286
4287    /**
4288     * <p>
4289     * Initializes the fading edges from a given set of styled attributes. This
4290     * method should be called by subclasses that need fading edges and when an
4291     * instance of these subclasses is created programmatically rather than
4292     * being inflated from XML. This method is automatically called when the XML
4293     * is inflated.
4294     * </p>
4295     *
4296     * @param a the styled attributes set to initialize the fading edges from
4297     */
4298    protected void initializeFadingEdge(TypedArray a) {
4299        // This method probably shouldn't have been included in the SDK to begin with.
4300        // It relies on 'a' having been initialized using an attribute filter array that is
4301        // not publicly available to the SDK. The old method has been renamed
4302        // to initializeFadingEdgeInternal and hidden for framework use only;
4303        // this one initializes using defaults to make it safe to call for apps.
4304
4305        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4306
4307        initializeFadingEdgeInternal(arr);
4308
4309        arr.recycle();
4310    }
4311
4312    /**
4313     * <p>
4314     * Initializes the fading edges from a given set of styled attributes. This
4315     * method should be called by subclasses that need fading edges and when an
4316     * instance of these subclasses is created programmatically rather than
4317     * being inflated from XML. This method is automatically called when the XML
4318     * is inflated.
4319     * </p>
4320     *
4321     * @param a the styled attributes set to initialize the fading edges from
4322     * @hide This is the real method; the public one is shimmed to be safe to call from apps.
4323     */
4324    protected void initializeFadingEdgeInternal(TypedArray a) {
4325        initScrollCache();
4326
4327        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
4328                R.styleable.View_fadingEdgeLength,
4329                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
4330    }
4331
4332    /**
4333     * Returns the size of the vertical faded edges used to indicate that more
4334     * content in this view is visible.
4335     *
4336     * @return The size in pixels of the vertical faded edge or 0 if vertical
4337     *         faded edges are not enabled for this view.
4338     * @attr ref android.R.styleable#View_fadingEdgeLength
4339     */
4340    public int getVerticalFadingEdgeLength() {
4341        if (isVerticalFadingEdgeEnabled()) {
4342            ScrollabilityCache cache = mScrollCache;
4343            if (cache != null) {
4344                return cache.fadingEdgeLength;
4345            }
4346        }
4347        return 0;
4348    }
4349
4350    /**
4351     * Set the size of the faded edge used to indicate that more content in this
4352     * view is available.  Will not change whether the fading edge is enabled; use
4353     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
4354     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
4355     * for the vertical or horizontal fading edges.
4356     *
4357     * @param length The size in pixels of the faded edge used to indicate that more
4358     *        content in this view is visible.
4359     */
4360    public void setFadingEdgeLength(int length) {
4361        initScrollCache();
4362        mScrollCache.fadingEdgeLength = length;
4363    }
4364
4365    /**
4366     * Returns the size of the horizontal faded edges used to indicate that more
4367     * content in this view is visible.
4368     *
4369     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
4370     *         faded edges are not enabled for this view.
4371     * @attr ref android.R.styleable#View_fadingEdgeLength
4372     */
4373    public int getHorizontalFadingEdgeLength() {
4374        if (isHorizontalFadingEdgeEnabled()) {
4375            ScrollabilityCache cache = mScrollCache;
4376            if (cache != null) {
4377                return cache.fadingEdgeLength;
4378            }
4379        }
4380        return 0;
4381    }
4382
4383    /**
4384     * Returns the width of the vertical scrollbar.
4385     *
4386     * @return The width in pixels of the vertical scrollbar or 0 if there
4387     *         is no vertical scrollbar.
4388     */
4389    public int getVerticalScrollbarWidth() {
4390        ScrollabilityCache cache = mScrollCache;
4391        if (cache != null) {
4392            ScrollBarDrawable scrollBar = cache.scrollBar;
4393            if (scrollBar != null) {
4394                int size = scrollBar.getSize(true);
4395                if (size <= 0) {
4396                    size = cache.scrollBarSize;
4397                }
4398                return size;
4399            }
4400            return 0;
4401        }
4402        return 0;
4403    }
4404
4405    /**
4406     * Returns the height of the horizontal scrollbar.
4407     *
4408     * @return The height in pixels of the horizontal scrollbar or 0 if
4409     *         there is no horizontal scrollbar.
4410     */
4411    protected int getHorizontalScrollbarHeight() {
4412        ScrollabilityCache cache = mScrollCache;
4413        if (cache != null) {
4414            ScrollBarDrawable scrollBar = cache.scrollBar;
4415            if (scrollBar != null) {
4416                int size = scrollBar.getSize(false);
4417                if (size <= 0) {
4418                    size = cache.scrollBarSize;
4419                }
4420                return size;
4421            }
4422            return 0;
4423        }
4424        return 0;
4425    }
4426
4427    /**
4428     * <p>
4429     * Initializes the scrollbars from a given set of styled attributes. This
4430     * method should be called by subclasses that need scrollbars and when an
4431     * instance of these subclasses is created programmatically rather than
4432     * being inflated from XML. This method is automatically called when the XML
4433     * is inflated.
4434     * </p>
4435     *
4436     * @param a the styled attributes set to initialize the scrollbars from
4437     */
4438    protected void initializeScrollbars(TypedArray a) {
4439        // It's not safe to use this method from apps. The parameter 'a' must have been obtained
4440        // using the View filter array which is not available to the SDK. As such, internal
4441        // framework usage now uses initializeScrollbarsInternal and we grab a default
4442        // TypedArray with the right filter instead here.
4443        TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View);
4444
4445        initializeScrollbarsInternal(arr);
4446
4447        // We ignored the method parameter. Recycle the one we actually did use.
4448        arr.recycle();
4449    }
4450
4451    /**
4452     * <p>
4453     * Initializes the scrollbars from a given set of styled attributes. This
4454     * method should be called by subclasses that need scrollbars and when an
4455     * instance of these subclasses is created programmatically rather than
4456     * being inflated from XML. This method is automatically called when the XML
4457     * is inflated.
4458     * </p>
4459     *
4460     * @param a the styled attributes set to initialize the scrollbars from
4461     * @hide
4462     */
4463    protected void initializeScrollbarsInternal(TypedArray a) {
4464        initScrollCache();
4465
4466        final ScrollabilityCache scrollabilityCache = mScrollCache;
4467
4468        if (scrollabilityCache.scrollBar == null) {
4469            scrollabilityCache.scrollBar = new ScrollBarDrawable();
4470        }
4471
4472        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
4473
4474        if (!fadeScrollbars) {
4475            scrollabilityCache.state = ScrollabilityCache.ON;
4476        }
4477        scrollabilityCache.fadeScrollBars = fadeScrollbars;
4478
4479
4480        scrollabilityCache.scrollBarFadeDuration = a.getInt(
4481                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
4482                        .getScrollBarFadeDuration());
4483        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
4484                R.styleable.View_scrollbarDefaultDelayBeforeFade,
4485                ViewConfiguration.getScrollDefaultDelay());
4486
4487
4488        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
4489                com.android.internal.R.styleable.View_scrollbarSize,
4490                ViewConfiguration.get(mContext).getScaledScrollBarSize());
4491
4492        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
4493        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
4494
4495        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4496        if (thumb != null) {
4497            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4498        }
4499
4500        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4501                false);
4502        if (alwaysDraw) {
4503            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4504        }
4505
4506        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4507        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4508
4509        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4510        if (thumb != null) {
4511            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4512        }
4513
4514        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4515                false);
4516        if (alwaysDraw) {
4517            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4518        }
4519
4520        // Apply layout direction to the new Drawables if needed
4521        final int layoutDirection = getLayoutDirection();
4522        if (track != null) {
4523            track.setLayoutDirection(layoutDirection);
4524        }
4525        if (thumb != null) {
4526            thumb.setLayoutDirection(layoutDirection);
4527        }
4528
4529        // Re-apply user/background padding so that scrollbar(s) get added
4530        resolvePadding();
4531    }
4532
4533    /**
4534     * <p>
4535     * Initalizes the scrollability cache if necessary.
4536     * </p>
4537     */
4538    private void initScrollCache() {
4539        if (mScrollCache == null) {
4540            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4541        }
4542    }
4543
4544    private ScrollabilityCache getScrollCache() {
4545        initScrollCache();
4546        return mScrollCache;
4547    }
4548
4549    /**
4550     * Set the position of the vertical scroll bar. Should be one of
4551     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4552     * {@link #SCROLLBAR_POSITION_RIGHT}.
4553     *
4554     * @param position Where the vertical scroll bar should be positioned.
4555     */
4556    public void setVerticalScrollbarPosition(int position) {
4557        if (mVerticalScrollbarPosition != position) {
4558            mVerticalScrollbarPosition = position;
4559            computeOpaqueFlags();
4560            resolvePadding();
4561        }
4562    }
4563
4564    /**
4565     * @return The position where the vertical scroll bar will show, if applicable.
4566     * @see #setVerticalScrollbarPosition(int)
4567     */
4568    public int getVerticalScrollbarPosition() {
4569        return mVerticalScrollbarPosition;
4570    }
4571
4572    ListenerInfo getListenerInfo() {
4573        if (mListenerInfo != null) {
4574            return mListenerInfo;
4575        }
4576        mListenerInfo = new ListenerInfo();
4577        return mListenerInfo;
4578    }
4579
4580    /**
4581     * Register a callback to be invoked when focus of this view changed.
4582     *
4583     * @param l The callback that will run.
4584     */
4585    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4586        getListenerInfo().mOnFocusChangeListener = l;
4587    }
4588
4589    /**
4590     * Add a listener that will be called when the bounds of the view change due to
4591     * layout processing.
4592     *
4593     * @param listener The listener that will be called when layout bounds change.
4594     */
4595    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4596        ListenerInfo li = getListenerInfo();
4597        if (li.mOnLayoutChangeListeners == null) {
4598            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4599        }
4600        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4601            li.mOnLayoutChangeListeners.add(listener);
4602        }
4603    }
4604
4605    /**
4606     * Remove a listener for layout changes.
4607     *
4608     * @param listener The listener for layout bounds change.
4609     */
4610    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4611        ListenerInfo li = mListenerInfo;
4612        if (li == null || li.mOnLayoutChangeListeners == null) {
4613            return;
4614        }
4615        li.mOnLayoutChangeListeners.remove(listener);
4616    }
4617
4618    /**
4619     * Add a listener for attach state changes.
4620     *
4621     * This listener will be called whenever this view is attached or detached
4622     * from a window. Remove the listener using
4623     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4624     *
4625     * @param listener Listener to attach
4626     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4627     */
4628    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4629        ListenerInfo li = getListenerInfo();
4630        if (li.mOnAttachStateChangeListeners == null) {
4631            li.mOnAttachStateChangeListeners
4632                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4633        }
4634        li.mOnAttachStateChangeListeners.add(listener);
4635    }
4636
4637    /**
4638     * Remove a listener for attach state changes. The listener will receive no further
4639     * notification of window attach/detach events.
4640     *
4641     * @param listener Listener to remove
4642     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4643     */
4644    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4645        ListenerInfo li = mListenerInfo;
4646        if (li == null || li.mOnAttachStateChangeListeners == null) {
4647            return;
4648        }
4649        li.mOnAttachStateChangeListeners.remove(listener);
4650    }
4651
4652    /**
4653     * Returns the focus-change callback registered for this view.
4654     *
4655     * @return The callback, or null if one is not registered.
4656     */
4657    public OnFocusChangeListener getOnFocusChangeListener() {
4658        ListenerInfo li = mListenerInfo;
4659        return li != null ? li.mOnFocusChangeListener : null;
4660    }
4661
4662    /**
4663     * Register a callback to be invoked when this view is clicked. If this view is not
4664     * clickable, it becomes clickable.
4665     *
4666     * @param l The callback that will run
4667     *
4668     * @see #setClickable(boolean)
4669     */
4670    public void setOnClickListener(OnClickListener l) {
4671        if (!isClickable()) {
4672            setClickable(true);
4673        }
4674        getListenerInfo().mOnClickListener = l;
4675    }
4676
4677    /**
4678     * Return whether this view has an attached OnClickListener.  Returns
4679     * true if there is a listener, false if there is none.
4680     */
4681    public boolean hasOnClickListeners() {
4682        ListenerInfo li = mListenerInfo;
4683        return (li != null && li.mOnClickListener != null);
4684    }
4685
4686    /**
4687     * Register a callback to be invoked when this view is clicked and held. If this view is not
4688     * long clickable, it becomes long clickable.
4689     *
4690     * @param l The callback that will run
4691     *
4692     * @see #setLongClickable(boolean)
4693     */
4694    public void setOnLongClickListener(OnLongClickListener l) {
4695        if (!isLongClickable()) {
4696            setLongClickable(true);
4697        }
4698        getListenerInfo().mOnLongClickListener = l;
4699    }
4700
4701    /**
4702     * Register a callback to be invoked when the context menu for this view is
4703     * being built. If this view is not long clickable, it becomes long clickable.
4704     *
4705     * @param l The callback that will run
4706     *
4707     */
4708    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4709        if (!isLongClickable()) {
4710            setLongClickable(true);
4711        }
4712        getListenerInfo().mOnCreateContextMenuListener = l;
4713    }
4714
4715    /**
4716     * Call this view's OnClickListener, if it is defined.  Performs all normal
4717     * actions associated with clicking: reporting accessibility event, playing
4718     * a sound, etc.
4719     *
4720     * @return True there was an assigned OnClickListener that was called, false
4721     *         otherwise is returned.
4722     */
4723    public boolean performClick() {
4724        final boolean result;
4725        final ListenerInfo li = mListenerInfo;
4726        if (li != null && li.mOnClickListener != null) {
4727            playSoundEffect(SoundEffectConstants.CLICK);
4728            li.mOnClickListener.onClick(this);
4729            result = true;
4730        } else {
4731            result = false;
4732        }
4733
4734        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4735        return result;
4736    }
4737
4738    /**
4739     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4740     * this only calls the listener, and does not do any associated clicking
4741     * actions like reporting an accessibility event.
4742     *
4743     * @return True there was an assigned OnClickListener that was called, false
4744     *         otherwise is returned.
4745     */
4746    public boolean callOnClick() {
4747        ListenerInfo li = mListenerInfo;
4748        if (li != null && li.mOnClickListener != null) {
4749            li.mOnClickListener.onClick(this);
4750            return true;
4751        }
4752        return false;
4753    }
4754
4755    /**
4756     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4757     * OnLongClickListener did not consume the event.
4758     *
4759     * @return True if one of the above receivers consumed the event, false otherwise.
4760     */
4761    public boolean performLongClick() {
4762        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4763
4764        boolean handled = false;
4765        ListenerInfo li = mListenerInfo;
4766        if (li != null && li.mOnLongClickListener != null) {
4767            handled = li.mOnLongClickListener.onLongClick(View.this);
4768        }
4769        if (!handled) {
4770            handled = showContextMenu();
4771        }
4772        if (handled) {
4773            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4774        }
4775        return handled;
4776    }
4777
4778    /**
4779     * Performs button-related actions during a touch down event.
4780     *
4781     * @param event The event.
4782     * @return True if the down was consumed.
4783     *
4784     * @hide
4785     */
4786    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4787        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4788            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4789                return true;
4790            }
4791        }
4792        return false;
4793    }
4794
4795    /**
4796     * Bring up the context menu for this view.
4797     *
4798     * @return Whether a context menu was displayed.
4799     */
4800    public boolean showContextMenu() {
4801        return getParent().showContextMenuForChild(this);
4802    }
4803
4804    /**
4805     * Bring up the context menu for this view, referring to the item under the specified point.
4806     *
4807     * @param x The referenced x coordinate.
4808     * @param y The referenced y coordinate.
4809     * @param metaState The keyboard modifiers that were pressed.
4810     * @return Whether a context menu was displayed.
4811     *
4812     * @hide
4813     */
4814    public boolean showContextMenu(float x, float y, int metaState) {
4815        return showContextMenu();
4816    }
4817
4818    /**
4819     * Start an action mode.
4820     *
4821     * @param callback Callback that will control the lifecycle of the action mode
4822     * @return The new action mode if it is started, null otherwise
4823     *
4824     * @see ActionMode
4825     */
4826    public ActionMode startActionMode(ActionMode.Callback callback) {
4827        ViewParent parent = getParent();
4828        if (parent == null) return null;
4829        return parent.startActionModeForChild(this, callback);
4830    }
4831
4832    /**
4833     * Register a callback to be invoked when a hardware key is pressed in this view.
4834     * Key presses in software input methods will generally not trigger the methods of
4835     * this listener.
4836     * @param l the key listener to attach to this view
4837     */
4838    public void setOnKeyListener(OnKeyListener l) {
4839        getListenerInfo().mOnKeyListener = l;
4840    }
4841
4842    /**
4843     * Register a callback to be invoked when a touch event is sent to this view.
4844     * @param l the touch listener to attach to this view
4845     */
4846    public void setOnTouchListener(OnTouchListener l) {
4847        getListenerInfo().mOnTouchListener = l;
4848    }
4849
4850    /**
4851     * Register a callback to be invoked when a generic motion event is sent to this view.
4852     * @param l the generic motion listener to attach to this view
4853     */
4854    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4855        getListenerInfo().mOnGenericMotionListener = l;
4856    }
4857
4858    /**
4859     * Register a callback to be invoked when a hover event is sent to this view.
4860     * @param l the hover listener to attach to this view
4861     */
4862    public void setOnHoverListener(OnHoverListener l) {
4863        getListenerInfo().mOnHoverListener = l;
4864    }
4865
4866    /**
4867     * Register a drag event listener callback object for this View. The parameter is
4868     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4869     * View, the system calls the
4870     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4871     * @param l An implementation of {@link android.view.View.OnDragListener}.
4872     */
4873    public void setOnDragListener(OnDragListener l) {
4874        getListenerInfo().mOnDragListener = l;
4875    }
4876
4877    /**
4878     * Give this view focus. This will cause
4879     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4880     *
4881     * Note: this does not check whether this {@link View} should get focus, it just
4882     * gives it focus no matter what.  It should only be called internally by framework
4883     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4884     *
4885     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4886     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4887     *        focus moved when requestFocus() is called. It may not always
4888     *        apply, in which case use the default View.FOCUS_DOWN.
4889     * @param previouslyFocusedRect The rectangle of the view that had focus
4890     *        prior in this View's coordinate system.
4891     */
4892    void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) {
4893        if (DBG) {
4894            System.out.println(this + " requestFocus()");
4895        }
4896
4897        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4898            mPrivateFlags |= PFLAG_FOCUSED;
4899
4900            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4901
4902            if (mParent != null) {
4903                mParent.requestChildFocus(this, this);
4904            }
4905
4906            if (mAttachInfo != null) {
4907                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4908            }
4909
4910            onFocusChanged(true, direction, previouslyFocusedRect);
4911            manageFocusHotspot(true, oldFocus);
4912            refreshDrawableState();
4913        }
4914    }
4915
4916    /**
4917     * Forwards focus information to the background drawable, if necessary. When
4918     * the view is gaining focus, <code>v</code> is the previous focus holder.
4919     * When the view is losing focus, <code>v</code> is the next focus holder.
4920     *
4921     * @param focused whether this view is focused
4922     * @param v previous or the next focus holder, or null if none
4923     */
4924    private void manageFocusHotspot(boolean focused, View v) {
4925        final Rect r = new Rect();
4926        if (v != null && mAttachInfo != null) {
4927            v.getHotspotBounds(r);
4928            final int[] location = mAttachInfo.mTmpLocation;
4929            getLocationOnScreen(location);
4930            r.offset(-location[0], -location[1]);
4931        } else {
4932            r.set(0, 0, mRight - mLeft, mBottom - mTop);
4933        }
4934
4935        final float x = r.exactCenterX();
4936        final float y = r.exactCenterY();
4937        drawableHotspotChanged(x, y);
4938    }
4939
4940    /**
4941     * Populates <code>outRect</code> with the hotspot bounds. By default,
4942     * the hotspot bounds are identical to the screen bounds.
4943     *
4944     * @param outRect rect to populate with hotspot bounds
4945     * @hide Only for internal use by views and widgets.
4946     */
4947    public void getHotspotBounds(Rect outRect) {
4948        final Drawable background = getBackground();
4949        if (background != null) {
4950            background.getHotspotBounds(outRect);
4951        } else {
4952            getBoundsOnScreen(outRect);
4953        }
4954    }
4955
4956    /**
4957     * Request that a rectangle of this view be visible on the screen,
4958     * scrolling if necessary just enough.
4959     *
4960     * <p>A View should call this if it maintains some notion of which part
4961     * of its content is interesting.  For example, a text editing view
4962     * should call this when its cursor moves.
4963     *
4964     * @param rectangle The rectangle.
4965     * @return Whether any parent scrolled.
4966     */
4967    public boolean requestRectangleOnScreen(Rect rectangle) {
4968        return requestRectangleOnScreen(rectangle, false);
4969    }
4970
4971    /**
4972     * Request that a rectangle of this view be visible on the screen,
4973     * scrolling if necessary just enough.
4974     *
4975     * <p>A View should call this if it maintains some notion of which part
4976     * of its content is interesting.  For example, a text editing view
4977     * should call this when its cursor moves.
4978     *
4979     * <p>When <code>immediate</code> is set to true, scrolling will not be
4980     * animated.
4981     *
4982     * @param rectangle The rectangle.
4983     * @param immediate True to forbid animated scrolling, false otherwise
4984     * @return Whether any parent scrolled.
4985     */
4986    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4987        if (mParent == null) {
4988            return false;
4989        }
4990
4991        View child = this;
4992
4993        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4994        position.set(rectangle);
4995
4996        ViewParent parent = mParent;
4997        boolean scrolled = false;
4998        while (parent != null) {
4999            rectangle.set((int) position.left, (int) position.top,
5000                    (int) position.right, (int) position.bottom);
5001
5002            scrolled |= parent.requestChildRectangleOnScreen(child,
5003                    rectangle, immediate);
5004
5005            if (!child.hasIdentityMatrix()) {
5006                child.getMatrix().mapRect(position);
5007            }
5008
5009            position.offset(child.mLeft, child.mTop);
5010
5011            if (!(parent instanceof View)) {
5012                break;
5013            }
5014
5015            View parentView = (View) parent;
5016
5017            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
5018
5019            child = parentView;
5020            parent = child.getParent();
5021        }
5022
5023        return scrolled;
5024    }
5025
5026    /**
5027     * Called when this view wants to give up focus. If focus is cleared
5028     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
5029     * <p>
5030     * <strong>Note:</strong> When a View clears focus the framework is trying
5031     * to give focus to the first focusable View from the top. Hence, if this
5032     * View is the first from the top that can take focus, then all callbacks
5033     * related to clearing focus will be invoked after wich the framework will
5034     * give focus to this view.
5035     * </p>
5036     */
5037    public void clearFocus() {
5038        if (DBG) {
5039            System.out.println(this + " clearFocus()");
5040        }
5041
5042        clearFocusInternal(null, true, true);
5043    }
5044
5045    /**
5046     * Clears focus from the view, optionally propagating the change up through
5047     * the parent hierarchy and requesting that the root view place new focus.
5048     *
5049     * @param propagate whether to propagate the change up through the parent
5050     *            hierarchy
5051     * @param refocus when propagate is true, specifies whether to request the
5052     *            root view place new focus
5053     */
5054    void clearFocusInternal(View focused, boolean propagate, boolean refocus) {
5055        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
5056            mPrivateFlags &= ~PFLAG_FOCUSED;
5057
5058            if (propagate && mParent != null) {
5059                mParent.clearChildFocus(this);
5060            }
5061
5062            onFocusChanged(false, 0, null);
5063
5064            manageFocusHotspot(false, focused);
5065            refreshDrawableState();
5066
5067            if (propagate && (!refocus || !rootViewRequestFocus())) {
5068                notifyGlobalFocusCleared(this);
5069            }
5070        }
5071    }
5072
5073    void notifyGlobalFocusCleared(View oldFocus) {
5074        if (oldFocus != null && mAttachInfo != null) {
5075            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
5076        }
5077    }
5078
5079    boolean rootViewRequestFocus() {
5080        final View root = getRootView();
5081        return root != null && root.requestFocus();
5082    }
5083
5084    /**
5085     * Called internally by the view system when a new view is getting focus.
5086     * This is what clears the old focus.
5087     * <p>
5088     * <b>NOTE:</b> The parent view's focused child must be updated manually
5089     * after calling this method. Otherwise, the view hierarchy may be left in
5090     * an inconstent state.
5091     */
5092    void unFocus(View focused) {
5093        if (DBG) {
5094            System.out.println(this + " unFocus()");
5095        }
5096
5097        clearFocusInternal(focused, false, false);
5098    }
5099
5100    /**
5101     * Returns true if this view has focus iteself, or is the ancestor of the
5102     * view that has focus.
5103     *
5104     * @return True if this view has or contains focus, false otherwise.
5105     */
5106    @ViewDebug.ExportedProperty(category = "focus")
5107    public boolean hasFocus() {
5108        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5109    }
5110
5111    /**
5112     * Returns true if this view is focusable or if it contains a reachable View
5113     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
5114     * is a View whose parents do not block descendants focus.
5115     *
5116     * Only {@link #VISIBLE} views are considered focusable.
5117     *
5118     * @return True if the view is focusable or if the view contains a focusable
5119     *         View, false otherwise.
5120     *
5121     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
5122     * @see ViewGroup#getTouchscreenBlocksFocus()
5123     */
5124    public boolean hasFocusable() {
5125        if (!isFocusableInTouchMode()) {
5126            for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
5127                final ViewGroup g = (ViewGroup) p;
5128                if (g.shouldBlockFocusForTouchscreen()) {
5129                    return false;
5130                }
5131            }
5132        }
5133        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
5134    }
5135
5136    /**
5137     * Called by the view system when the focus state of this view changes.
5138     * When the focus change event is caused by directional navigation, direction
5139     * and previouslyFocusedRect provide insight into where the focus is coming from.
5140     * When overriding, be sure to call up through to the super class so that
5141     * the standard focus handling will occur.
5142     *
5143     * @param gainFocus True if the View has focus; false otherwise.
5144     * @param direction The direction focus has moved when requestFocus()
5145     *                  is called to give this view focus. Values are
5146     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
5147     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
5148     *                  It may not always apply, in which case use the default.
5149     * @param previouslyFocusedRect The rectangle, in this view's coordinate
5150     *        system, of the previously focused view.  If applicable, this will be
5151     *        passed in as finer grained information about where the focus is coming
5152     *        from (in addition to direction).  Will be <code>null</code> otherwise.
5153     */
5154    protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction,
5155            @Nullable Rect previouslyFocusedRect) {
5156        if (gainFocus) {
5157            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
5158        } else {
5159            notifyViewAccessibilityStateChangedIfNeeded(
5160                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
5161        }
5162
5163        InputMethodManager imm = InputMethodManager.peekInstance();
5164        if (!gainFocus) {
5165            if (isPressed()) {
5166                setPressed(false);
5167            }
5168            if (imm != null && mAttachInfo != null
5169                    && mAttachInfo.mHasWindowFocus) {
5170                imm.focusOut(this);
5171            }
5172            onFocusLost();
5173        } else if (imm != null && mAttachInfo != null
5174                && mAttachInfo.mHasWindowFocus) {
5175            imm.focusIn(this);
5176        }
5177
5178        invalidate(true);
5179        ListenerInfo li = mListenerInfo;
5180        if (li != null && li.mOnFocusChangeListener != null) {
5181            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
5182        }
5183
5184        if (mAttachInfo != null) {
5185            mAttachInfo.mKeyDispatchState.reset(this);
5186        }
5187    }
5188
5189    /**
5190     * Sends an accessibility event of the given type. If accessibility is
5191     * not enabled this method has no effect. The default implementation calls
5192     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
5193     * to populate information about the event source (this View), then calls
5194     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
5195     * populate the text content of the event source including its descendants,
5196     * and last calls
5197     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
5198     * on its parent to resuest sending of the event to interested parties.
5199     * <p>
5200     * If an {@link AccessibilityDelegate} has been specified via calling
5201     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5202     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
5203     * responsible for handling this call.
5204     * </p>
5205     *
5206     * @param eventType The type of the event to send, as defined by several types from
5207     * {@link android.view.accessibility.AccessibilityEvent}, such as
5208     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
5209     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
5210     *
5211     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5212     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5213     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
5214     * @see AccessibilityDelegate
5215     */
5216    public void sendAccessibilityEvent(int eventType) {
5217        if (mAccessibilityDelegate != null) {
5218            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
5219        } else {
5220            sendAccessibilityEventInternal(eventType);
5221        }
5222    }
5223
5224    /**
5225     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
5226     * {@link AccessibilityEvent} to make an announcement which is related to some
5227     * sort of a context change for which none of the events representing UI transitions
5228     * is a good fit. For example, announcing a new page in a book. If accessibility
5229     * is not enabled this method does nothing.
5230     *
5231     * @param text The announcement text.
5232     */
5233    public void announceForAccessibility(CharSequence text) {
5234        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
5235            AccessibilityEvent event = AccessibilityEvent.obtain(
5236                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
5237            onInitializeAccessibilityEvent(event);
5238            event.getText().add(text);
5239            event.setContentDescription(null);
5240            mParent.requestSendAccessibilityEvent(this, event);
5241        }
5242    }
5243
5244    /**
5245     * @see #sendAccessibilityEvent(int)
5246     *
5247     * Note: Called from the default {@link AccessibilityDelegate}.
5248     */
5249    void sendAccessibilityEventInternal(int eventType) {
5250        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
5251            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
5252        }
5253    }
5254
5255    /**
5256     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
5257     * takes as an argument an empty {@link AccessibilityEvent} and does not
5258     * perform a check whether accessibility is enabled.
5259     * <p>
5260     * If an {@link AccessibilityDelegate} has been specified via calling
5261     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5262     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
5263     * is responsible for handling this call.
5264     * </p>
5265     *
5266     * @param event The event to send.
5267     *
5268     * @see #sendAccessibilityEvent(int)
5269     */
5270    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
5271        if (mAccessibilityDelegate != null) {
5272            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
5273        } else {
5274            sendAccessibilityEventUncheckedInternal(event);
5275        }
5276    }
5277
5278    /**
5279     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
5280     *
5281     * Note: Called from the default {@link AccessibilityDelegate}.
5282     */
5283    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
5284        if (!isShown()) {
5285            return;
5286        }
5287        onInitializeAccessibilityEvent(event);
5288        // Only a subset of accessibility events populates text content.
5289        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
5290            dispatchPopulateAccessibilityEvent(event);
5291        }
5292        // In the beginning we called #isShown(), so we know that getParent() is not null.
5293        getParent().requestSendAccessibilityEvent(this, event);
5294    }
5295
5296    /**
5297     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
5298     * to its children for adding their text content to the event. Note that the
5299     * event text is populated in a separate dispatch path since we add to the
5300     * event not only the text of the source but also the text of all its descendants.
5301     * A typical implementation will call
5302     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
5303     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5304     * on each child. Override this method if custom population of the event text
5305     * content is required.
5306     * <p>
5307     * If an {@link AccessibilityDelegate} has been specified via calling
5308     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5309     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
5310     * is responsible for handling this call.
5311     * </p>
5312     * <p>
5313     * <em>Note:</em> Accessibility events of certain types are not dispatched for
5314     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
5315     * </p>
5316     *
5317     * @param event The event.
5318     *
5319     * @return True if the event population was completed.
5320     */
5321    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
5322        if (mAccessibilityDelegate != null) {
5323            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
5324        } else {
5325            return dispatchPopulateAccessibilityEventInternal(event);
5326        }
5327    }
5328
5329    /**
5330     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5331     *
5332     * Note: Called from the default {@link AccessibilityDelegate}.
5333     */
5334    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5335        onPopulateAccessibilityEvent(event);
5336        return false;
5337    }
5338
5339    /**
5340     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
5341     * giving a chance to this View to populate the accessibility event with its
5342     * text content. While this method is free to modify event
5343     * attributes other than text content, doing so should normally be performed in
5344     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
5345     * <p>
5346     * Example: Adding formatted date string to an accessibility event in addition
5347     *          to the text added by the super implementation:
5348     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5349     *     super.onPopulateAccessibilityEvent(event);
5350     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
5351     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
5352     *         mCurrentDate.getTimeInMillis(), flags);
5353     *     event.getText().add(selectedDateUtterance);
5354     * }</pre>
5355     * <p>
5356     * If an {@link AccessibilityDelegate} has been specified via calling
5357     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5358     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
5359     * is responsible for handling this call.
5360     * </p>
5361     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5362     * information to the event, in case the default implementation has basic information to add.
5363     * </p>
5364     *
5365     * @param event The accessibility event which to populate.
5366     *
5367     * @see #sendAccessibilityEvent(int)
5368     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5369     */
5370    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
5371        if (mAccessibilityDelegate != null) {
5372            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
5373        } else {
5374            onPopulateAccessibilityEventInternal(event);
5375        }
5376    }
5377
5378    /**
5379     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
5380     *
5381     * Note: Called from the default {@link AccessibilityDelegate}.
5382     */
5383    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
5384    }
5385
5386    /**
5387     * Initializes an {@link AccessibilityEvent} with information about
5388     * this View which is the event source. In other words, the source of
5389     * an accessibility event is the view whose state change triggered firing
5390     * the event.
5391     * <p>
5392     * Example: Setting the password property of an event in addition
5393     *          to properties set by the super implementation:
5394     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5395     *     super.onInitializeAccessibilityEvent(event);
5396     *     event.setPassword(true);
5397     * }</pre>
5398     * <p>
5399     * If an {@link AccessibilityDelegate} has been specified via calling
5400     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5401     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
5402     * is responsible for handling this call.
5403     * </p>
5404     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
5405     * information to the event, in case the default implementation has basic information to add.
5406     * </p>
5407     * @param event The event to initialize.
5408     *
5409     * @see #sendAccessibilityEvent(int)
5410     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
5411     */
5412    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
5413        if (mAccessibilityDelegate != null) {
5414            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
5415        } else {
5416            onInitializeAccessibilityEventInternal(event);
5417        }
5418    }
5419
5420    /**
5421     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
5422     *
5423     * Note: Called from the default {@link AccessibilityDelegate}.
5424     */
5425    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
5426        event.setSource(this);
5427        event.setClassName(View.class.getName());
5428        event.setPackageName(getContext().getPackageName());
5429        event.setEnabled(isEnabled());
5430        event.setContentDescription(mContentDescription);
5431
5432        switch (event.getEventType()) {
5433            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
5434                ArrayList<View> focusablesTempList = (mAttachInfo != null)
5435                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
5436                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
5437                event.setItemCount(focusablesTempList.size());
5438                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
5439                if (mAttachInfo != null) {
5440                    focusablesTempList.clear();
5441                }
5442            } break;
5443            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
5444                CharSequence text = getIterableTextForAccessibility();
5445                if (text != null && text.length() > 0) {
5446                    event.setFromIndex(getAccessibilitySelectionStart());
5447                    event.setToIndex(getAccessibilitySelectionEnd());
5448                    event.setItemCount(text.length());
5449                }
5450            } break;
5451        }
5452    }
5453
5454    /**
5455     * Returns an {@link AccessibilityNodeInfo} representing this view from the
5456     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
5457     * This method is responsible for obtaining an accessibility node info from a
5458     * pool of reusable instances and calling
5459     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
5460     * initialize the former.
5461     * <p>
5462     * Note: The client is responsible for recycling the obtained instance by calling
5463     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
5464     * </p>
5465     *
5466     * @return A populated {@link AccessibilityNodeInfo}.
5467     *
5468     * @see AccessibilityNodeInfo
5469     */
5470    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
5471        if (mAccessibilityDelegate != null) {
5472            return mAccessibilityDelegate.createAccessibilityNodeInfo(this);
5473        } else {
5474            return createAccessibilityNodeInfoInternal();
5475        }
5476    }
5477
5478    /**
5479     * @see #createAccessibilityNodeInfo()
5480     */
5481    AccessibilityNodeInfo createAccessibilityNodeInfoInternal() {
5482        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
5483        if (provider != null) {
5484            return provider.createAccessibilityNodeInfo(View.NO_ID);
5485        } else {
5486            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
5487            onInitializeAccessibilityNodeInfo(info);
5488            return info;
5489        }
5490    }
5491
5492    /**
5493     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
5494     * The base implementation sets:
5495     * <ul>
5496     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
5497     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
5498     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
5499     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
5500     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
5501     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
5502     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
5503     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
5504     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
5505     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
5506     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
5507     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
5508     * </ul>
5509     * <p>
5510     * Subclasses should override this method, call the super implementation,
5511     * and set additional attributes.
5512     * </p>
5513     * <p>
5514     * If an {@link AccessibilityDelegate} has been specified via calling
5515     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5516     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
5517     * is responsible for handling this call.
5518     * </p>
5519     *
5520     * @param info The instance to initialize.
5521     */
5522    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
5523        if (mAccessibilityDelegate != null) {
5524            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
5525        } else {
5526            onInitializeAccessibilityNodeInfoInternal(info);
5527        }
5528    }
5529
5530    /**
5531     * Gets the location of this view in screen coordintates.
5532     *
5533     * @param outRect The output location
5534     * @hide
5535     */
5536    public void getBoundsOnScreen(Rect outRect) {
5537        if (mAttachInfo == null) {
5538            return;
5539        }
5540
5541        RectF position = mAttachInfo.mTmpTransformRect;
5542        position.set(0, 0, mRight - mLeft, mBottom - mTop);
5543
5544        if (!hasIdentityMatrix()) {
5545            getMatrix().mapRect(position);
5546        }
5547
5548        position.offset(mLeft, mTop);
5549
5550        ViewParent parent = mParent;
5551        while (parent instanceof View) {
5552            View parentView = (View) parent;
5553
5554            position.offset(-parentView.mScrollX, -parentView.mScrollY);
5555
5556            if (!parentView.hasIdentityMatrix()) {
5557                parentView.getMatrix().mapRect(position);
5558            }
5559
5560            position.offset(parentView.mLeft, parentView.mTop);
5561
5562            parent = parentView.mParent;
5563        }
5564
5565        if (parent instanceof ViewRootImpl) {
5566            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5567            position.offset(0, -viewRootImpl.mCurScrollY);
5568        }
5569
5570        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5571
5572        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5573                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5574    }
5575
5576    /**
5577     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5578     *
5579     * Note: Called from the default {@link AccessibilityDelegate}.
5580     */
5581    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5582        Rect bounds = mAttachInfo.mTmpInvalRect;
5583
5584        getDrawingRect(bounds);
5585        info.setBoundsInParent(bounds);
5586
5587        getBoundsOnScreen(bounds);
5588        info.setBoundsInScreen(bounds);
5589
5590        ViewParent parent = getParentForAccessibility();
5591        if (parent instanceof View) {
5592            info.setParent((View) parent);
5593        }
5594
5595        if (mID != View.NO_ID) {
5596            View rootView = getRootView();
5597            if (rootView == null) {
5598                rootView = this;
5599            }
5600            View label = rootView.findLabelForView(this, mID);
5601            if (label != null) {
5602                info.setLabeledBy(label);
5603            }
5604
5605            if ((mAttachInfo.mAccessibilityFetchFlags
5606                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5607                    && Resources.resourceHasPackage(mID)) {
5608                try {
5609                    String viewId = getResources().getResourceName(mID);
5610                    info.setViewIdResourceName(viewId);
5611                } catch (Resources.NotFoundException nfe) {
5612                    /* ignore */
5613                }
5614            }
5615        }
5616
5617        if (mLabelForId != View.NO_ID) {
5618            View rootView = getRootView();
5619            if (rootView == null) {
5620                rootView = this;
5621            }
5622            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5623            if (labeled != null) {
5624                info.setLabelFor(labeled);
5625            }
5626        }
5627
5628        info.setVisibleToUser(isVisibleToUser());
5629
5630        info.setPackageName(mContext.getPackageName());
5631        info.setClassName(View.class.getName());
5632        info.setContentDescription(getContentDescription());
5633
5634        info.setEnabled(isEnabled());
5635        info.setClickable(isClickable());
5636        info.setFocusable(isFocusable());
5637        info.setFocused(isFocused());
5638        info.setAccessibilityFocused(isAccessibilityFocused());
5639        info.setSelected(isSelected());
5640        info.setLongClickable(isLongClickable());
5641        info.setLiveRegion(getAccessibilityLiveRegion());
5642
5643        // TODO: These make sense only if we are in an AdapterView but all
5644        // views can be selected. Maybe from accessibility perspective
5645        // we should report as selectable view in an AdapterView.
5646        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5647        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5648
5649        if (isFocusable()) {
5650            if (isFocused()) {
5651                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5652            } else {
5653                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5654            }
5655        }
5656
5657        if (!isAccessibilityFocused()) {
5658            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5659        } else {
5660            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5661        }
5662
5663        if (isClickable() && isEnabled()) {
5664            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5665        }
5666
5667        if (isLongClickable() && isEnabled()) {
5668            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5669        }
5670
5671        CharSequence text = getIterableTextForAccessibility();
5672        if (text != null && text.length() > 0) {
5673            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5674
5675            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5676            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5677            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5678            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5679                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5680                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5681        }
5682    }
5683
5684    private View findLabelForView(View view, int labeledId) {
5685        if (mMatchLabelForPredicate == null) {
5686            mMatchLabelForPredicate = new MatchLabelForPredicate();
5687        }
5688        mMatchLabelForPredicate.mLabeledId = labeledId;
5689        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5690    }
5691
5692    /**
5693     * Computes whether this view is visible to the user. Such a view is
5694     * attached, visible, all its predecessors are visible, it is not clipped
5695     * entirely by its predecessors, and has an alpha greater than zero.
5696     *
5697     * @return Whether the view is visible on the screen.
5698     *
5699     * @hide
5700     */
5701    protected boolean isVisibleToUser() {
5702        return isVisibleToUser(null);
5703    }
5704
5705    /**
5706     * Computes whether the given portion of this view is visible to the user.
5707     * Such a view is attached, visible, all its predecessors are visible,
5708     * has an alpha greater than zero, and the specified portion is not
5709     * clipped entirely by its predecessors.
5710     *
5711     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5712     *                    <code>null</code>, and the entire view will be tested in this case.
5713     *                    When <code>true</code> is returned by the function, the actual visible
5714     *                    region will be stored in this parameter; that is, if boundInView is fully
5715     *                    contained within the view, no modification will be made, otherwise regions
5716     *                    outside of the visible area of the view will be clipped.
5717     *
5718     * @return Whether the specified portion of the view is visible on the screen.
5719     *
5720     * @hide
5721     */
5722    protected boolean isVisibleToUser(Rect boundInView) {
5723        if (mAttachInfo != null) {
5724            // Attached to invisible window means this view is not visible.
5725            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5726                return false;
5727            }
5728            // An invisible predecessor or one with alpha zero means
5729            // that this view is not visible to the user.
5730            Object current = this;
5731            while (current instanceof View) {
5732                View view = (View) current;
5733                // We have attach info so this view is attached and there is no
5734                // need to check whether we reach to ViewRootImpl on the way up.
5735                if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 ||
5736                        view.getVisibility() != VISIBLE) {
5737                    return false;
5738                }
5739                current = view.mParent;
5740            }
5741            // Check if the view is entirely covered by its predecessors.
5742            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5743            Point offset = mAttachInfo.mPoint;
5744            if (!getGlobalVisibleRect(visibleRect, offset)) {
5745                return false;
5746            }
5747            // Check if the visible portion intersects the rectangle of interest.
5748            if (boundInView != null) {
5749                visibleRect.offset(-offset.x, -offset.y);
5750                return boundInView.intersect(visibleRect);
5751            }
5752            return true;
5753        }
5754        return false;
5755    }
5756
5757    /**
5758     * Returns the delegate for implementing accessibility support via
5759     * composition. For more details see {@link AccessibilityDelegate}.
5760     *
5761     * @return The delegate, or null if none set.
5762     *
5763     * @hide
5764     */
5765    public AccessibilityDelegate getAccessibilityDelegate() {
5766        return mAccessibilityDelegate;
5767    }
5768
5769    /**
5770     * Sets a delegate for implementing accessibility support via composition as
5771     * opposed to inheritance. The delegate's primary use is for implementing
5772     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5773     *
5774     * @param delegate The delegate instance.
5775     *
5776     * @see AccessibilityDelegate
5777     */
5778    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5779        mAccessibilityDelegate = delegate;
5780    }
5781
5782    /**
5783     * Gets the provider for managing a virtual view hierarchy rooted at this View
5784     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5785     * that explore the window content.
5786     * <p>
5787     * If this method returns an instance, this instance is responsible for managing
5788     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5789     * View including the one representing the View itself. Similarly the returned
5790     * instance is responsible for performing accessibility actions on any virtual
5791     * view or the root view itself.
5792     * </p>
5793     * <p>
5794     * If an {@link AccessibilityDelegate} has been specified via calling
5795     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5796     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5797     * is responsible for handling this call.
5798     * </p>
5799     *
5800     * @return The provider.
5801     *
5802     * @see AccessibilityNodeProvider
5803     */
5804    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5805        if (mAccessibilityDelegate != null) {
5806            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5807        } else {
5808            return null;
5809        }
5810    }
5811
5812    /**
5813     * Gets the unique identifier of this view on the screen for accessibility purposes.
5814     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5815     *
5816     * @return The view accessibility id.
5817     *
5818     * @hide
5819     */
5820    public int getAccessibilityViewId() {
5821        if (mAccessibilityViewId == NO_ID) {
5822            mAccessibilityViewId = sNextAccessibilityViewId++;
5823        }
5824        return mAccessibilityViewId;
5825    }
5826
5827    /**
5828     * Gets the unique identifier of the window in which this View reseides.
5829     *
5830     * @return The window accessibility id.
5831     *
5832     * @hide
5833     */
5834    public int getAccessibilityWindowId() {
5835        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId
5836                : AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
5837    }
5838
5839    /**
5840     * Gets the {@link View} description. It briefly describes the view and is
5841     * primarily used for accessibility support. Set this property to enable
5842     * better accessibility support for your application. This is especially
5843     * true for views that do not have textual representation (For example,
5844     * ImageButton).
5845     *
5846     * @return The content description.
5847     *
5848     * @attr ref android.R.styleable#View_contentDescription
5849     */
5850    @ViewDebug.ExportedProperty(category = "accessibility")
5851    public CharSequence getContentDescription() {
5852        return mContentDescription;
5853    }
5854
5855    /**
5856     * Sets the {@link View} description. It briefly describes the view and is
5857     * primarily used for accessibility support. Set this property to enable
5858     * better accessibility support for your application. This is especially
5859     * true for views that do not have textual representation (For example,
5860     * ImageButton).
5861     *
5862     * @param contentDescription The content description.
5863     *
5864     * @attr ref android.R.styleable#View_contentDescription
5865     */
5866    @RemotableViewMethod
5867    public void setContentDescription(CharSequence contentDescription) {
5868        if (mContentDescription == null) {
5869            if (contentDescription == null) {
5870                return;
5871            }
5872        } else if (mContentDescription.equals(contentDescription)) {
5873            return;
5874        }
5875        mContentDescription = contentDescription;
5876        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5877        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5878            setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5879            notifySubtreeAccessibilityStateChangedIfNeeded();
5880        } else {
5881            notifyViewAccessibilityStateChangedIfNeeded(
5882                    AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION);
5883        }
5884    }
5885
5886    /**
5887     * Gets the id of a view for which this view serves as a label for
5888     * accessibility purposes.
5889     *
5890     * @return The labeled view id.
5891     */
5892    @ViewDebug.ExportedProperty(category = "accessibility")
5893    public int getLabelFor() {
5894        return mLabelForId;
5895    }
5896
5897    /**
5898     * Sets the id of a view for which this view serves as a label for
5899     * accessibility purposes.
5900     *
5901     * @param id The labeled view id.
5902     */
5903    @RemotableViewMethod
5904    public void setLabelFor(int id) {
5905        mLabelForId = id;
5906        if (mLabelForId != View.NO_ID
5907                && mID == View.NO_ID) {
5908            mID = generateViewId();
5909        }
5910    }
5911
5912    /**
5913     * Invoked whenever this view loses focus, either by losing window focus or by losing
5914     * focus within its window. This method can be used to clear any state tied to the
5915     * focus. For instance, if a button is held pressed with the trackball and the window
5916     * loses focus, this method can be used to cancel the press.
5917     *
5918     * Subclasses of View overriding this method should always call super.onFocusLost().
5919     *
5920     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5921     * @see #onWindowFocusChanged(boolean)
5922     *
5923     * @hide pending API council approval
5924     */
5925    protected void onFocusLost() {
5926        resetPressedState();
5927    }
5928
5929    private void resetPressedState() {
5930        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5931            return;
5932        }
5933
5934        if (isPressed()) {
5935            setPressed(false);
5936
5937            if (!mHasPerformedLongPress) {
5938                removeLongPressCallback();
5939            }
5940        }
5941    }
5942
5943    /**
5944     * Returns true if this view has focus
5945     *
5946     * @return True if this view has focus, false otherwise.
5947     */
5948    @ViewDebug.ExportedProperty(category = "focus")
5949    public boolean isFocused() {
5950        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5951    }
5952
5953    /**
5954     * Find the view in the hierarchy rooted at this view that currently has
5955     * focus.
5956     *
5957     * @return The view that currently has focus, or null if no focused view can
5958     *         be found.
5959     */
5960    public View findFocus() {
5961        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5962    }
5963
5964    /**
5965     * Indicates whether this view is one of the set of scrollable containers in
5966     * its window.
5967     *
5968     * @return whether this view is one of the set of scrollable containers in
5969     * its window
5970     *
5971     * @attr ref android.R.styleable#View_isScrollContainer
5972     */
5973    public boolean isScrollContainer() {
5974        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5975    }
5976
5977    /**
5978     * Change whether this view is one of the set of scrollable containers in
5979     * its window.  This will be used to determine whether the window can
5980     * resize or must pan when a soft input area is open -- scrollable
5981     * containers allow the window to use resize mode since the container
5982     * will appropriately shrink.
5983     *
5984     * @attr ref android.R.styleable#View_isScrollContainer
5985     */
5986    public void setScrollContainer(boolean isScrollContainer) {
5987        if (isScrollContainer) {
5988            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5989                mAttachInfo.mScrollContainers.add(this);
5990                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5991            }
5992            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5993        } else {
5994            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5995                mAttachInfo.mScrollContainers.remove(this);
5996            }
5997            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5998        }
5999    }
6000
6001    /**
6002     * Returns the quality of the drawing cache.
6003     *
6004     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6005     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6006     *
6007     * @see #setDrawingCacheQuality(int)
6008     * @see #setDrawingCacheEnabled(boolean)
6009     * @see #isDrawingCacheEnabled()
6010     *
6011     * @attr ref android.R.styleable#View_drawingCacheQuality
6012     */
6013    @DrawingCacheQuality
6014    public int getDrawingCacheQuality() {
6015        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
6016    }
6017
6018    /**
6019     * Set the drawing cache quality of this view. This value is used only when the
6020     * drawing cache is enabled
6021     *
6022     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
6023     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
6024     *
6025     * @see #getDrawingCacheQuality()
6026     * @see #setDrawingCacheEnabled(boolean)
6027     * @see #isDrawingCacheEnabled()
6028     *
6029     * @attr ref android.R.styleable#View_drawingCacheQuality
6030     */
6031    public void setDrawingCacheQuality(@DrawingCacheQuality int quality) {
6032        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
6033    }
6034
6035    /**
6036     * Returns whether the screen should remain on, corresponding to the current
6037     * value of {@link #KEEP_SCREEN_ON}.
6038     *
6039     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
6040     *
6041     * @see #setKeepScreenOn(boolean)
6042     *
6043     * @attr ref android.R.styleable#View_keepScreenOn
6044     */
6045    public boolean getKeepScreenOn() {
6046        return (mViewFlags & KEEP_SCREEN_ON) != 0;
6047    }
6048
6049    /**
6050     * Controls whether the screen should remain on, modifying the
6051     * value of {@link #KEEP_SCREEN_ON}.
6052     *
6053     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
6054     *
6055     * @see #getKeepScreenOn()
6056     *
6057     * @attr ref android.R.styleable#View_keepScreenOn
6058     */
6059    public void setKeepScreenOn(boolean keepScreenOn) {
6060        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
6061    }
6062
6063    /**
6064     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6065     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6066     *
6067     * @attr ref android.R.styleable#View_nextFocusLeft
6068     */
6069    public int getNextFocusLeftId() {
6070        return mNextFocusLeftId;
6071    }
6072
6073    /**
6074     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
6075     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
6076     * decide automatically.
6077     *
6078     * @attr ref android.R.styleable#View_nextFocusLeft
6079     */
6080    public void setNextFocusLeftId(int nextFocusLeftId) {
6081        mNextFocusLeftId = nextFocusLeftId;
6082    }
6083
6084    /**
6085     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6086     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6087     *
6088     * @attr ref android.R.styleable#View_nextFocusRight
6089     */
6090    public int getNextFocusRightId() {
6091        return mNextFocusRightId;
6092    }
6093
6094    /**
6095     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
6096     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
6097     * decide automatically.
6098     *
6099     * @attr ref android.R.styleable#View_nextFocusRight
6100     */
6101    public void setNextFocusRightId(int nextFocusRightId) {
6102        mNextFocusRightId = nextFocusRightId;
6103    }
6104
6105    /**
6106     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6107     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6108     *
6109     * @attr ref android.R.styleable#View_nextFocusUp
6110     */
6111    public int getNextFocusUpId() {
6112        return mNextFocusUpId;
6113    }
6114
6115    /**
6116     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
6117     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
6118     * decide automatically.
6119     *
6120     * @attr ref android.R.styleable#View_nextFocusUp
6121     */
6122    public void setNextFocusUpId(int nextFocusUpId) {
6123        mNextFocusUpId = nextFocusUpId;
6124    }
6125
6126    /**
6127     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6128     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6129     *
6130     * @attr ref android.R.styleable#View_nextFocusDown
6131     */
6132    public int getNextFocusDownId() {
6133        return mNextFocusDownId;
6134    }
6135
6136    /**
6137     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
6138     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
6139     * decide automatically.
6140     *
6141     * @attr ref android.R.styleable#View_nextFocusDown
6142     */
6143    public void setNextFocusDownId(int nextFocusDownId) {
6144        mNextFocusDownId = nextFocusDownId;
6145    }
6146
6147    /**
6148     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6149     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
6150     *
6151     * @attr ref android.R.styleable#View_nextFocusForward
6152     */
6153    public int getNextFocusForwardId() {
6154        return mNextFocusForwardId;
6155    }
6156
6157    /**
6158     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
6159     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
6160     * decide automatically.
6161     *
6162     * @attr ref android.R.styleable#View_nextFocusForward
6163     */
6164    public void setNextFocusForwardId(int nextFocusForwardId) {
6165        mNextFocusForwardId = nextFocusForwardId;
6166    }
6167
6168    /**
6169     * Returns the visibility of this view and all of its ancestors
6170     *
6171     * @return True if this view and all of its ancestors are {@link #VISIBLE}
6172     */
6173    public boolean isShown() {
6174        View current = this;
6175        //noinspection ConstantConditions
6176        do {
6177            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6178                return false;
6179            }
6180            ViewParent parent = current.mParent;
6181            if (parent == null) {
6182                return false; // We are not attached to the view root
6183            }
6184            if (!(parent instanceof View)) {
6185                return true;
6186            }
6187            current = (View) parent;
6188        } while (current != null);
6189
6190        return false;
6191    }
6192
6193    /**
6194     * Called by the view hierarchy when the content insets for a window have
6195     * changed, to allow it to adjust its content to fit within those windows.
6196     * The content insets tell you the space that the status bar, input method,
6197     * and other system windows infringe on the application's window.
6198     *
6199     * <p>You do not normally need to deal with this function, since the default
6200     * window decoration given to applications takes care of applying it to the
6201     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
6202     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
6203     * and your content can be placed under those system elements.  You can then
6204     * use this method within your view hierarchy if you have parts of your UI
6205     * which you would like to ensure are not being covered.
6206     *
6207     * <p>The default implementation of this method simply applies the content
6208     * insets to the view's padding, consuming that content (modifying the
6209     * insets to be 0), and returning true.  This behavior is off by default, but can
6210     * be enabled through {@link #setFitsSystemWindows(boolean)}.
6211     *
6212     * <p>This function's traversal down the hierarchy is depth-first.  The same content
6213     * insets object is propagated down the hierarchy, so any changes made to it will
6214     * be seen by all following views (including potentially ones above in
6215     * the hierarchy since this is a depth-first traversal).  The first view
6216     * that returns true will abort the entire traversal.
6217     *
6218     * <p>The default implementation works well for a situation where it is
6219     * used with a container that covers the entire window, allowing it to
6220     * apply the appropriate insets to its content on all edges.  If you need
6221     * a more complicated layout (such as two different views fitting system
6222     * windows, one on the top of the window, and one on the bottom),
6223     * you can override the method and handle the insets however you would like.
6224     * Note that the insets provided by the framework are always relative to the
6225     * far edges of the window, not accounting for the location of the called view
6226     * within that window.  (In fact when this method is called you do not yet know
6227     * where the layout will place the view, as it is done before layout happens.)
6228     *
6229     * <p>Note: unlike many View methods, there is no dispatch phase to this
6230     * call.  If you are overriding it in a ViewGroup and want to allow the
6231     * call to continue to your children, you must be sure to call the super
6232     * implementation.
6233     *
6234     * <p>Here is a sample layout that makes use of fitting system windows
6235     * to have controls for a video view placed inside of the window decorations
6236     * that it hides and shows.  This can be used with code like the second
6237     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
6238     *
6239     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
6240     *
6241     * @param insets Current content insets of the window.  Prior to
6242     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
6243     * the insets or else you and Android will be unhappy.
6244     *
6245     * @return {@code true} if this view applied the insets and it should not
6246     * continue propagating further down the hierarchy, {@code false} otherwise.
6247     * @see #getFitsSystemWindows()
6248     * @see #setFitsSystemWindows(boolean)
6249     * @see #setSystemUiVisibility(int)
6250     *
6251     * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply
6252     * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use
6253     * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)}
6254     * to implement handling their own insets.
6255     */
6256    protected boolean fitSystemWindows(Rect insets) {
6257        if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) {
6258            if (insets == null) {
6259                // Null insets by definition have already been consumed.
6260                // This call cannot apply insets since there are none to apply,
6261                // so return false.
6262                return false;
6263            }
6264            // If we're not in the process of dispatching the newer apply insets call,
6265            // that means we're not in the compatibility path. Dispatch into the newer
6266            // apply insets path and take things from there.
6267            try {
6268                mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS;
6269                return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed();
6270            } finally {
6271                mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS;
6272            }
6273        } else {
6274            // We're being called from the newer apply insets path.
6275            // Perform the standard fallback behavior.
6276            return fitSystemWindowsInt(insets);
6277        }
6278    }
6279
6280    private boolean fitSystemWindowsInt(Rect insets) {
6281        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
6282            mUserPaddingStart = UNDEFINED_PADDING;
6283            mUserPaddingEnd = UNDEFINED_PADDING;
6284            Rect localInsets = sThreadLocal.get();
6285            if (localInsets == null) {
6286                localInsets = new Rect();
6287                sThreadLocal.set(localInsets);
6288            }
6289            boolean res = computeFitSystemWindows(insets, localInsets);
6290            mUserPaddingLeftInitial = localInsets.left;
6291            mUserPaddingRightInitial = localInsets.right;
6292            internalSetPadding(localInsets.left, localInsets.top,
6293                    localInsets.right, localInsets.bottom);
6294            return res;
6295        }
6296        return false;
6297    }
6298
6299    /**
6300     * Called when the view should apply {@link WindowInsets} according to its internal policy.
6301     *
6302     * <p>This method should be overridden by views that wish to apply a policy different from or
6303     * in addition to the default behavior. Clients that wish to force a view subtree
6304     * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p>
6305     *
6306     * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set
6307     * it will be called during dispatch instead of this method. The listener may optionally
6308     * call this method from its own implementation if it wishes to apply the view's default
6309     * insets policy in addition to its own.</p>
6310     *
6311     * <p>Implementations of this method should either return the insets parameter unchanged
6312     * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed
6313     * that this view applied itself. This allows new inset types added in future platform
6314     * versions to pass through existing implementations unchanged without being erroneously
6315     * consumed.</p>
6316     *
6317     * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows}
6318     * property is set then the view will consume the system window insets and apply them
6319     * as padding for the view.</p>
6320     *
6321     * @param insets Insets to apply
6322     * @return The supplied insets with any applied insets consumed
6323     */
6324    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
6325        if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) {
6326            // We weren't called from within a direct call to fitSystemWindows,
6327            // call into it as a fallback in case we're in a class that overrides it
6328            // and has logic to perform.
6329            if (fitSystemWindows(insets.getSystemWindowInsets())) {
6330                return insets.consumeSystemWindowInsets();
6331            }
6332        } else {
6333            // We were called from within a direct call to fitSystemWindows.
6334            if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {
6335                return insets.consumeSystemWindowInsets();
6336            }
6337        }
6338        return insets;
6339    }
6340
6341    /**
6342     * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying
6343     * window insets to this view. The listener's
6344     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
6345     * method will be called instead of the view's
6346     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
6347     *
6348     * @param listener Listener to set
6349     *
6350     * @see #onApplyWindowInsets(WindowInsets)
6351     */
6352    public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {
6353        getListenerInfo().mOnApplyWindowInsetsListener = listener;
6354    }
6355
6356    /**
6357     * Request to apply the given window insets to this view or another view in its subtree.
6358     *
6359     * <p>This method should be called by clients wishing to apply insets corresponding to areas
6360     * obscured by window decorations or overlays. This can include the status and navigation bars,
6361     * action bars, input methods and more. New inset categories may be added in the future.
6362     * The method returns the insets provided minus any that were applied by this view or its
6363     * children.</p>
6364     *
6365     * <p>Clients wishing to provide custom behavior should override the
6366     * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a
6367     * {@link OnApplyWindowInsetsListener} via the
6368     * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener}
6369     * method.</p>
6370     *
6371     * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method.
6372     * </p>
6373     *
6374     * @param insets Insets to apply
6375     * @return The provided insets minus the insets that were consumed
6376     */
6377    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
6378        try {
6379            mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
6380            if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
6381                return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
6382            } else {
6383                return onApplyWindowInsets(insets);
6384            }
6385        } finally {
6386            mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
6387        }
6388    }
6389
6390    /**
6391     * @hide Compute the insets that should be consumed by this view and the ones
6392     * that should propagate to those under it.
6393     */
6394    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
6395        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
6396                || mAttachInfo == null
6397                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
6398                        && !mAttachInfo.mOverscanRequested)) {
6399            outLocalInsets.set(inoutInsets);
6400            inoutInsets.set(0, 0, 0, 0);
6401            return true;
6402        } else {
6403            // The application wants to take care of fitting system window for
6404            // the content...  however we still need to take care of any overscan here.
6405            final Rect overscan = mAttachInfo.mOverscanInsets;
6406            outLocalInsets.set(overscan);
6407            inoutInsets.left -= overscan.left;
6408            inoutInsets.top -= overscan.top;
6409            inoutInsets.right -= overscan.right;
6410            inoutInsets.bottom -= overscan.bottom;
6411            return false;
6412        }
6413    }
6414
6415    /**
6416     * Sets whether or not this view should account for system screen decorations
6417     * such as the status bar and inset its content; that is, controlling whether
6418     * the default implementation of {@link #fitSystemWindows(Rect)} will be
6419     * executed.  See that method for more details.
6420     *
6421     * <p>Note that if you are providing your own implementation of
6422     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
6423     * flag to true -- your implementation will be overriding the default
6424     * implementation that checks this flag.
6425     *
6426     * @param fitSystemWindows If true, then the default implementation of
6427     * {@link #fitSystemWindows(Rect)} will be executed.
6428     *
6429     * @attr ref android.R.styleable#View_fitsSystemWindows
6430     * @see #getFitsSystemWindows()
6431     * @see #fitSystemWindows(Rect)
6432     * @see #setSystemUiVisibility(int)
6433     */
6434    public void setFitsSystemWindows(boolean fitSystemWindows) {
6435        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
6436    }
6437
6438    /**
6439     * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method
6440     * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)}
6441     * will be executed.
6442     *
6443     * @return {@code true} if the default implementation of
6444     * {@link #fitSystemWindows(Rect)} will be executed.
6445     *
6446     * @attr ref android.R.styleable#View_fitsSystemWindows
6447     * @see #setFitsSystemWindows(boolean)
6448     * @see #fitSystemWindows(Rect)
6449     * @see #setSystemUiVisibility(int)
6450     */
6451    public boolean getFitsSystemWindows() {
6452        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
6453    }
6454
6455    /** @hide */
6456    public boolean fitsSystemWindows() {
6457        return getFitsSystemWindows();
6458    }
6459
6460    /**
6461     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
6462     * @deprecated Use {@link #requestApplyInsets()} for newer platform versions.
6463     */
6464    public void requestFitSystemWindows() {
6465        if (mParent != null) {
6466            mParent.requestFitSystemWindows();
6467        }
6468    }
6469
6470    /**
6471     * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed.
6472     */
6473    public void requestApplyInsets() {
6474        requestFitSystemWindows();
6475    }
6476
6477    /**
6478     * For use by PhoneWindow to make its own system window fitting optional.
6479     * @hide
6480     */
6481    public void makeOptionalFitsSystemWindows() {
6482        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
6483    }
6484
6485    /**
6486     * Returns the visibility status for this view.
6487     *
6488     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6489     * @attr ref android.R.styleable#View_visibility
6490     */
6491    @ViewDebug.ExportedProperty(mapping = {
6492        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
6493        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
6494        @ViewDebug.IntToString(from = GONE,      to = "GONE")
6495    })
6496    @Visibility
6497    public int getVisibility() {
6498        return mViewFlags & VISIBILITY_MASK;
6499    }
6500
6501    /**
6502     * Set the enabled state of this view.
6503     *
6504     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
6505     * @attr ref android.R.styleable#View_visibility
6506     */
6507    @RemotableViewMethod
6508    public void setVisibility(@Visibility int visibility) {
6509        setFlags(visibility, VISIBILITY_MASK);
6510        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
6511    }
6512
6513    /**
6514     * Returns the enabled status for this view. The interpretation of the
6515     * enabled state varies by subclass.
6516     *
6517     * @return True if this view is enabled, false otherwise.
6518     */
6519    @ViewDebug.ExportedProperty
6520    public boolean isEnabled() {
6521        return (mViewFlags & ENABLED_MASK) == ENABLED;
6522    }
6523
6524    /**
6525     * Set the enabled state of this view. The interpretation of the enabled
6526     * state varies by subclass.
6527     *
6528     * @param enabled True if this view is enabled, false otherwise.
6529     */
6530    @RemotableViewMethod
6531    public void setEnabled(boolean enabled) {
6532        if (enabled == isEnabled()) return;
6533
6534        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
6535
6536        /*
6537         * The View most likely has to change its appearance, so refresh
6538         * the drawable state.
6539         */
6540        refreshDrawableState();
6541
6542        // Invalidate too, since the default behavior for views is to be
6543        // be drawn at 50% alpha rather than to change the drawable.
6544        invalidate(true);
6545
6546        if (!enabled) {
6547            cancelPendingInputEvents();
6548        }
6549    }
6550
6551    /**
6552     * Set whether this view can receive the focus.
6553     *
6554     * Setting this to false will also ensure that this view is not focusable
6555     * in touch mode.
6556     *
6557     * @param focusable If true, this view can receive the focus.
6558     *
6559     * @see #setFocusableInTouchMode(boolean)
6560     * @attr ref android.R.styleable#View_focusable
6561     */
6562    public void setFocusable(boolean focusable) {
6563        if (!focusable) {
6564            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
6565        }
6566        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
6567    }
6568
6569    /**
6570     * Set whether this view can receive focus while in touch mode.
6571     *
6572     * Setting this to true will also ensure that this view is focusable.
6573     *
6574     * @param focusableInTouchMode If true, this view can receive the focus while
6575     *   in touch mode.
6576     *
6577     * @see #setFocusable(boolean)
6578     * @attr ref android.R.styleable#View_focusableInTouchMode
6579     */
6580    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
6581        // Focusable in touch mode should always be set before the focusable flag
6582        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
6583        // which, in touch mode, will not successfully request focus on this view
6584        // because the focusable in touch mode flag is not set
6585        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
6586        if (focusableInTouchMode) {
6587            setFlags(FOCUSABLE, FOCUSABLE_MASK);
6588        }
6589    }
6590
6591    /**
6592     * Set whether this view should have sound effects enabled for events such as
6593     * clicking and touching.
6594     *
6595     * <p>You may wish to disable sound effects for a view if you already play sounds,
6596     * for instance, a dial key that plays dtmf tones.
6597     *
6598     * @param soundEffectsEnabled whether sound effects are enabled for this view.
6599     * @see #isSoundEffectsEnabled()
6600     * @see #playSoundEffect(int)
6601     * @attr ref android.R.styleable#View_soundEffectsEnabled
6602     */
6603    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
6604        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
6605    }
6606
6607    /**
6608     * @return whether this view should have sound effects enabled for events such as
6609     *     clicking and touching.
6610     *
6611     * @see #setSoundEffectsEnabled(boolean)
6612     * @see #playSoundEffect(int)
6613     * @attr ref android.R.styleable#View_soundEffectsEnabled
6614     */
6615    @ViewDebug.ExportedProperty
6616    public boolean isSoundEffectsEnabled() {
6617        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
6618    }
6619
6620    /**
6621     * Set whether this view should have haptic feedback for events such as
6622     * long presses.
6623     *
6624     * <p>You may wish to disable haptic feedback if your view already controls
6625     * its own haptic feedback.
6626     *
6627     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
6628     * @see #isHapticFeedbackEnabled()
6629     * @see #performHapticFeedback(int)
6630     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6631     */
6632    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
6633        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
6634    }
6635
6636    /**
6637     * @return whether this view should have haptic feedback enabled for events
6638     * long presses.
6639     *
6640     * @see #setHapticFeedbackEnabled(boolean)
6641     * @see #performHapticFeedback(int)
6642     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
6643     */
6644    @ViewDebug.ExportedProperty
6645    public boolean isHapticFeedbackEnabled() {
6646        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
6647    }
6648
6649    /**
6650     * Returns the layout direction for this view.
6651     *
6652     * @return One of {@link #LAYOUT_DIRECTION_LTR},
6653     *   {@link #LAYOUT_DIRECTION_RTL},
6654     *   {@link #LAYOUT_DIRECTION_INHERIT} or
6655     *   {@link #LAYOUT_DIRECTION_LOCALE}.
6656     *
6657     * @attr ref android.R.styleable#View_layoutDirection
6658     *
6659     * @hide
6660     */
6661    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6662        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
6663        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
6664        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
6665        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
6666    })
6667    @LayoutDir
6668    public int getRawLayoutDirection() {
6669        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
6670    }
6671
6672    /**
6673     * Set the layout direction for this view. This will propagate a reset of layout direction
6674     * resolution to the view's children and resolve layout direction for this view.
6675     *
6676     * @param layoutDirection the layout direction to set. Should be one of:
6677     *
6678     * {@link #LAYOUT_DIRECTION_LTR},
6679     * {@link #LAYOUT_DIRECTION_RTL},
6680     * {@link #LAYOUT_DIRECTION_INHERIT},
6681     * {@link #LAYOUT_DIRECTION_LOCALE}.
6682     *
6683     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
6684     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
6685     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
6686     *
6687     * @attr ref android.R.styleable#View_layoutDirection
6688     */
6689    @RemotableViewMethod
6690    public void setLayoutDirection(@LayoutDir int layoutDirection) {
6691        if (getRawLayoutDirection() != layoutDirection) {
6692            // Reset the current layout direction and the resolved one
6693            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
6694            resetRtlProperties();
6695            // Set the new layout direction (filtered)
6696            mPrivateFlags2 |=
6697                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
6698            // We need to resolve all RTL properties as they all depend on layout direction
6699            resolveRtlPropertiesIfNeeded();
6700            requestLayout();
6701            invalidate(true);
6702        }
6703    }
6704
6705    /**
6706     * Returns the resolved layout direction for this view.
6707     *
6708     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6709     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6710     *
6711     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6712     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6713     *
6714     * @attr ref android.R.styleable#View_layoutDirection
6715     */
6716    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6717        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6718        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6719    })
6720    @ResolvedLayoutDir
6721    public int getLayoutDirection() {
6722        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6723        if (targetSdkVersion < JELLY_BEAN_MR1) {
6724            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6725            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6726        }
6727        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6728                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6729    }
6730
6731    /**
6732     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6733     * layout attribute and/or the inherited value from the parent
6734     *
6735     * @return true if the layout is right-to-left.
6736     *
6737     * @hide
6738     */
6739    @ViewDebug.ExportedProperty(category = "layout")
6740    public boolean isLayoutRtl() {
6741        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6742    }
6743
6744    /**
6745     * Indicates whether the view is currently tracking transient state that the
6746     * app should not need to concern itself with saving and restoring, but that
6747     * the framework should take special note to preserve when possible.
6748     *
6749     * <p>A view with transient state cannot be trivially rebound from an external
6750     * data source, such as an adapter binding item views in a list. This may be
6751     * because the view is performing an animation, tracking user selection
6752     * of content, or similar.</p>
6753     *
6754     * @return true if the view has transient state
6755     */
6756    @ViewDebug.ExportedProperty(category = "layout")
6757    public boolean hasTransientState() {
6758        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6759    }
6760
6761    /**
6762     * Set whether this view is currently tracking transient state that the
6763     * framework should attempt to preserve when possible. This flag is reference counted,
6764     * so every call to setHasTransientState(true) should be paired with a later call
6765     * to setHasTransientState(false).
6766     *
6767     * <p>A view with transient state cannot be trivially rebound from an external
6768     * data source, such as an adapter binding item views in a list. This may be
6769     * because the view is performing an animation, tracking user selection
6770     * of content, or similar.</p>
6771     *
6772     * @param hasTransientState true if this view has transient state
6773     */
6774    public void setHasTransientState(boolean hasTransientState) {
6775        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6776                mTransientStateCount - 1;
6777        if (mTransientStateCount < 0) {
6778            mTransientStateCount = 0;
6779            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6780                    "unmatched pair of setHasTransientState calls");
6781        } else if ((hasTransientState && mTransientStateCount == 1) ||
6782                (!hasTransientState && mTransientStateCount == 0)) {
6783            // update flag if we've just incremented up from 0 or decremented down to 0
6784            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6785                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6786            if (mParent != null) {
6787                try {
6788                    mParent.childHasTransientStateChanged(this, hasTransientState);
6789                } catch (AbstractMethodError e) {
6790                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6791                            " does not fully implement ViewParent", e);
6792                }
6793            }
6794        }
6795    }
6796
6797    /**
6798     * Returns true if this view is currently attached to a window.
6799     */
6800    public boolean isAttachedToWindow() {
6801        return mAttachInfo != null;
6802    }
6803
6804    /**
6805     * Returns true if this view has been through at least one layout since it
6806     * was last attached to or detached from a window.
6807     */
6808    public boolean isLaidOut() {
6809        return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT;
6810    }
6811
6812    /**
6813     * If this view doesn't do any drawing on its own, set this flag to
6814     * allow further optimizations. By default, this flag is not set on
6815     * View, but could be set on some View subclasses such as ViewGroup.
6816     *
6817     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6818     * you should clear this flag.
6819     *
6820     * @param willNotDraw whether or not this View draw on its own
6821     */
6822    public void setWillNotDraw(boolean willNotDraw) {
6823        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6824    }
6825
6826    /**
6827     * Returns whether or not this View draws on its own.
6828     *
6829     * @return true if this view has nothing to draw, false otherwise
6830     */
6831    @ViewDebug.ExportedProperty(category = "drawing")
6832    public boolean willNotDraw() {
6833        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6834    }
6835
6836    /**
6837     * When a View's drawing cache is enabled, drawing is redirected to an
6838     * offscreen bitmap. Some views, like an ImageView, must be able to
6839     * bypass this mechanism if they already draw a single bitmap, to avoid
6840     * unnecessary usage of the memory.
6841     *
6842     * @param willNotCacheDrawing true if this view does not cache its
6843     *        drawing, false otherwise
6844     */
6845    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6846        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6847    }
6848
6849    /**
6850     * Returns whether or not this View can cache its drawing or not.
6851     *
6852     * @return true if this view does not cache its drawing, false otherwise
6853     */
6854    @ViewDebug.ExportedProperty(category = "drawing")
6855    public boolean willNotCacheDrawing() {
6856        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6857    }
6858
6859    /**
6860     * Indicates whether this view reacts to click events or not.
6861     *
6862     * @return true if the view is clickable, false otherwise
6863     *
6864     * @see #setClickable(boolean)
6865     * @attr ref android.R.styleable#View_clickable
6866     */
6867    @ViewDebug.ExportedProperty
6868    public boolean isClickable() {
6869        return (mViewFlags & CLICKABLE) == CLICKABLE;
6870    }
6871
6872    /**
6873     * Enables or disables click events for this view. When a view
6874     * is clickable it will change its state to "pressed" on every click.
6875     * Subclasses should set the view clickable to visually react to
6876     * user's clicks.
6877     *
6878     * @param clickable true to make the view clickable, false otherwise
6879     *
6880     * @see #isClickable()
6881     * @attr ref android.R.styleable#View_clickable
6882     */
6883    public void setClickable(boolean clickable) {
6884        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6885    }
6886
6887    /**
6888     * Indicates whether this view reacts to long click events or not.
6889     *
6890     * @return true if the view is long clickable, false otherwise
6891     *
6892     * @see #setLongClickable(boolean)
6893     * @attr ref android.R.styleable#View_longClickable
6894     */
6895    public boolean isLongClickable() {
6896        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6897    }
6898
6899    /**
6900     * Enables or disables long click events for this view. When a view is long
6901     * clickable it reacts to the user holding down the button for a longer
6902     * duration than a tap. This event can either launch the listener or a
6903     * context menu.
6904     *
6905     * @param longClickable true to make the view long clickable, false otherwise
6906     * @see #isLongClickable()
6907     * @attr ref android.R.styleable#View_longClickable
6908     */
6909    public void setLongClickable(boolean longClickable) {
6910        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6911    }
6912
6913    /**
6914     * Sets the pressed state for this view and provides a touch coordinate for
6915     * animation hinting.
6916     *
6917     * @param pressed Pass true to set the View's internal state to "pressed",
6918     *            or false to reverts the View's internal state from a
6919     *            previously set "pressed" state.
6920     * @param x The x coordinate of the touch that caused the press
6921     * @param y The y coordinate of the touch that caused the press
6922     */
6923    private void setPressed(boolean pressed, float x, float y) {
6924        if (pressed) {
6925            drawableHotspotChanged(x, y);
6926        }
6927
6928        setPressed(pressed);
6929    }
6930
6931    /**
6932     * Sets the pressed state for this view.
6933     *
6934     * @see #isClickable()
6935     * @see #setClickable(boolean)
6936     *
6937     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6938     *        the View's internal state from a previously set "pressed" state.
6939     */
6940    public void setPressed(boolean pressed) {
6941        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6942
6943        if (pressed) {
6944            mPrivateFlags |= PFLAG_PRESSED;
6945        } else {
6946            mPrivateFlags &= ~PFLAG_PRESSED;
6947        }
6948
6949        if (needsRefresh) {
6950            refreshDrawableState();
6951        }
6952        dispatchSetPressed(pressed);
6953    }
6954
6955    /**
6956     * Dispatch setPressed to all of this View's children.
6957     *
6958     * @see #setPressed(boolean)
6959     *
6960     * @param pressed The new pressed state
6961     */
6962    protected void dispatchSetPressed(boolean pressed) {
6963    }
6964
6965    /**
6966     * Indicates whether the view is currently in pressed state. Unless
6967     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6968     * the pressed state.
6969     *
6970     * @see #setPressed(boolean)
6971     * @see #isClickable()
6972     * @see #setClickable(boolean)
6973     *
6974     * @return true if the view is currently pressed, false otherwise
6975     */
6976    @ViewDebug.ExportedProperty
6977    public boolean isPressed() {
6978        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6979    }
6980
6981    /**
6982     * Indicates whether this view will save its state (that is,
6983     * whether its {@link #onSaveInstanceState} method will be called).
6984     *
6985     * @return Returns true if the view state saving is enabled, else false.
6986     *
6987     * @see #setSaveEnabled(boolean)
6988     * @attr ref android.R.styleable#View_saveEnabled
6989     */
6990    public boolean isSaveEnabled() {
6991        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6992    }
6993
6994    /**
6995     * Controls whether the saving of this view's state is
6996     * enabled (that is, whether its {@link #onSaveInstanceState} method
6997     * will be called).  Note that even if freezing is enabled, the
6998     * view still must have an id assigned to it (via {@link #setId(int)})
6999     * for its state to be saved.  This flag can only disable the
7000     * saving of this view; any child views may still have their state saved.
7001     *
7002     * @param enabled Set to false to <em>disable</em> state saving, or true
7003     * (the default) to allow it.
7004     *
7005     * @see #isSaveEnabled()
7006     * @see #setId(int)
7007     * @see #onSaveInstanceState()
7008     * @attr ref android.R.styleable#View_saveEnabled
7009     */
7010    public void setSaveEnabled(boolean enabled) {
7011        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
7012    }
7013
7014    /**
7015     * Gets whether the framework should discard touches when the view's
7016     * window is obscured by another visible window.
7017     * Refer to the {@link View} security documentation for more details.
7018     *
7019     * @return True if touch filtering is enabled.
7020     *
7021     * @see #setFilterTouchesWhenObscured(boolean)
7022     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7023     */
7024    @ViewDebug.ExportedProperty
7025    public boolean getFilterTouchesWhenObscured() {
7026        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
7027    }
7028
7029    /**
7030     * Sets whether the framework should discard touches when the view's
7031     * window is obscured by another visible window.
7032     * Refer to the {@link View} security documentation for more details.
7033     *
7034     * @param enabled True if touch filtering should be enabled.
7035     *
7036     * @see #getFilterTouchesWhenObscured
7037     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
7038     */
7039    public void setFilterTouchesWhenObscured(boolean enabled) {
7040        setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0,
7041                FILTER_TOUCHES_WHEN_OBSCURED);
7042    }
7043
7044    /**
7045     * Indicates whether the entire hierarchy under this view will save its
7046     * state when a state saving traversal occurs from its parent.  The default
7047     * is true; if false, these views will not be saved unless
7048     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7049     *
7050     * @return Returns true if the view state saving from parent is enabled, else false.
7051     *
7052     * @see #setSaveFromParentEnabled(boolean)
7053     */
7054    public boolean isSaveFromParentEnabled() {
7055        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
7056    }
7057
7058    /**
7059     * Controls whether the entire hierarchy under this view will save its
7060     * state when a state saving traversal occurs from its parent.  The default
7061     * is true; if false, these views will not be saved unless
7062     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
7063     *
7064     * @param enabled Set to false to <em>disable</em> state saving, or true
7065     * (the default) to allow it.
7066     *
7067     * @see #isSaveFromParentEnabled()
7068     * @see #setId(int)
7069     * @see #onSaveInstanceState()
7070     */
7071    public void setSaveFromParentEnabled(boolean enabled) {
7072        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
7073    }
7074
7075
7076    /**
7077     * Returns whether this View is able to take focus.
7078     *
7079     * @return True if this view can take focus, or false otherwise.
7080     * @attr ref android.R.styleable#View_focusable
7081     */
7082    @ViewDebug.ExportedProperty(category = "focus")
7083    public final boolean isFocusable() {
7084        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
7085    }
7086
7087    /**
7088     * When a view is focusable, it may not want to take focus when in touch mode.
7089     * For example, a button would like focus when the user is navigating via a D-pad
7090     * so that the user can click on it, but once the user starts touching the screen,
7091     * the button shouldn't take focus
7092     * @return Whether the view is focusable in touch mode.
7093     * @attr ref android.R.styleable#View_focusableInTouchMode
7094     */
7095    @ViewDebug.ExportedProperty
7096    public final boolean isFocusableInTouchMode() {
7097        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
7098    }
7099
7100    /**
7101     * Find the nearest view in the specified direction that can take focus.
7102     * This does not actually give focus to that view.
7103     *
7104     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7105     *
7106     * @return The nearest focusable in the specified direction, or null if none
7107     *         can be found.
7108     */
7109    public View focusSearch(@FocusRealDirection int direction) {
7110        if (mParent != null) {
7111            return mParent.focusSearch(this, direction);
7112        } else {
7113            return null;
7114        }
7115    }
7116
7117    /**
7118     * This method is the last chance for the focused view and its ancestors to
7119     * respond to an arrow key. This is called when the focused view did not
7120     * consume the key internally, nor could the view system find a new view in
7121     * the requested direction to give focus to.
7122     *
7123     * @param focused The currently focused view.
7124     * @param direction The direction focus wants to move. One of FOCUS_UP,
7125     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
7126     * @return True if the this view consumed this unhandled move.
7127     */
7128    public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) {
7129        return false;
7130    }
7131
7132    /**
7133     * If a user manually specified the next view id for a particular direction,
7134     * use the root to look up the view.
7135     * @param root The root view of the hierarchy containing this view.
7136     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
7137     * or FOCUS_BACKWARD.
7138     * @return The user specified next view, or null if there is none.
7139     */
7140    View findUserSetNextFocus(View root, @FocusDirection int direction) {
7141        switch (direction) {
7142            case FOCUS_LEFT:
7143                if (mNextFocusLeftId == View.NO_ID) return null;
7144                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
7145            case FOCUS_RIGHT:
7146                if (mNextFocusRightId == View.NO_ID) return null;
7147                return findViewInsideOutShouldExist(root, mNextFocusRightId);
7148            case FOCUS_UP:
7149                if (mNextFocusUpId == View.NO_ID) return null;
7150                return findViewInsideOutShouldExist(root, mNextFocusUpId);
7151            case FOCUS_DOWN:
7152                if (mNextFocusDownId == View.NO_ID) return null;
7153                return findViewInsideOutShouldExist(root, mNextFocusDownId);
7154            case FOCUS_FORWARD:
7155                if (mNextFocusForwardId == View.NO_ID) return null;
7156                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
7157            case FOCUS_BACKWARD: {
7158                if (mID == View.NO_ID) return null;
7159                final int id = mID;
7160                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
7161                    @Override
7162                    public boolean apply(View t) {
7163                        return t.mNextFocusForwardId == id;
7164                    }
7165                });
7166            }
7167        }
7168        return null;
7169    }
7170
7171    private View findViewInsideOutShouldExist(View root, int id) {
7172        if (mMatchIdPredicate == null) {
7173            mMatchIdPredicate = new MatchIdPredicate();
7174        }
7175        mMatchIdPredicate.mId = id;
7176        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
7177        if (result == null) {
7178            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
7179        }
7180        return result;
7181    }
7182
7183    /**
7184     * Find and return all focusable views that are descendants of this view,
7185     * possibly including this view if it is focusable itself.
7186     *
7187     * @param direction The direction of the focus
7188     * @return A list of focusable views
7189     */
7190    public ArrayList<View> getFocusables(@FocusDirection int direction) {
7191        ArrayList<View> result = new ArrayList<View>(24);
7192        addFocusables(result, direction);
7193        return result;
7194    }
7195
7196    /**
7197     * Add any focusable views that are descendants of this view (possibly
7198     * including this view if it is focusable itself) to views.  If we are in touch mode,
7199     * only add views that are also focusable in touch mode.
7200     *
7201     * @param views Focusable views found so far
7202     * @param direction The direction of the focus
7203     */
7204    public void addFocusables(ArrayList<View> views, @FocusDirection int direction) {
7205        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
7206    }
7207
7208    /**
7209     * Adds any focusable views that are descendants of this view (possibly
7210     * including this view if it is focusable itself) to views. This method
7211     * adds all focusable views regardless if we are in touch mode or
7212     * only views focusable in touch mode if we are in touch mode or
7213     * only views that can take accessibility focus if accessibility is enabeld
7214     * depending on the focusable mode paramater.
7215     *
7216     * @param views Focusable views found so far or null if all we are interested is
7217     *        the number of focusables.
7218     * @param direction The direction of the focus.
7219     * @param focusableMode The type of focusables to be added.
7220     *
7221     * @see #FOCUSABLES_ALL
7222     * @see #FOCUSABLES_TOUCH_MODE
7223     */
7224    public void addFocusables(ArrayList<View> views, @FocusDirection int direction,
7225            @FocusableMode int focusableMode) {
7226        if (views == null) {
7227            return;
7228        }
7229        if (!isFocusable()) {
7230            return;
7231        }
7232        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
7233                && isInTouchMode() && !isFocusableInTouchMode()) {
7234            return;
7235        }
7236        views.add(this);
7237    }
7238
7239    /**
7240     * Finds the Views that contain given text. The containment is case insensitive.
7241     * The search is performed by either the text that the View renders or the content
7242     * description that describes the view for accessibility purposes and the view does
7243     * not render or both. Clients can specify how the search is to be performed via
7244     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
7245     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
7246     *
7247     * @param outViews The output list of matching Views.
7248     * @param searched The text to match against.
7249     *
7250     * @see #FIND_VIEWS_WITH_TEXT
7251     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
7252     * @see #setContentDescription(CharSequence)
7253     */
7254    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched,
7255            @FindViewFlags int flags) {
7256        if (getAccessibilityNodeProvider() != null) {
7257            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
7258                outViews.add(this);
7259            }
7260        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
7261                && (searched != null && searched.length() > 0)
7262                && (mContentDescription != null && mContentDescription.length() > 0)) {
7263            String searchedLowerCase = searched.toString().toLowerCase();
7264            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
7265            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
7266                outViews.add(this);
7267            }
7268        }
7269    }
7270
7271    /**
7272     * Find and return all touchable views that are descendants of this view,
7273     * possibly including this view if it is touchable itself.
7274     *
7275     * @return A list of touchable views
7276     */
7277    public ArrayList<View> getTouchables() {
7278        ArrayList<View> result = new ArrayList<View>();
7279        addTouchables(result);
7280        return result;
7281    }
7282
7283    /**
7284     * Add any touchable views that are descendants of this view (possibly
7285     * including this view if it is touchable itself) to views.
7286     *
7287     * @param views Touchable views found so far
7288     */
7289    public void addTouchables(ArrayList<View> views) {
7290        final int viewFlags = mViewFlags;
7291
7292        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
7293                && (viewFlags & ENABLED_MASK) == ENABLED) {
7294            views.add(this);
7295        }
7296    }
7297
7298    /**
7299     * Returns whether this View is accessibility focused.
7300     *
7301     * @return True if this View is accessibility focused.
7302     */
7303    public boolean isAccessibilityFocused() {
7304        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
7305    }
7306
7307    /**
7308     * Call this to try to give accessibility focus to this view.
7309     *
7310     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
7311     * returns false or the view is no visible or the view already has accessibility
7312     * focus.
7313     *
7314     * See also {@link #focusSearch(int)}, which is what you call to say that you
7315     * have focus, and you want your parent to look for the next one.
7316     *
7317     * @return Whether this view actually took accessibility focus.
7318     *
7319     * @hide
7320     */
7321    public boolean requestAccessibilityFocus() {
7322        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
7323        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
7324            return false;
7325        }
7326        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7327            return false;
7328        }
7329        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
7330            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
7331            ViewRootImpl viewRootImpl = getViewRootImpl();
7332            if (viewRootImpl != null) {
7333                viewRootImpl.setAccessibilityFocus(this, null);
7334            }
7335            invalidate();
7336            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
7337            return true;
7338        }
7339        return false;
7340    }
7341
7342    /**
7343     * Call this to try to clear accessibility focus of this view.
7344     *
7345     * See also {@link #focusSearch(int)}, which is what you call to say that you
7346     * have focus, and you want your parent to look for the next one.
7347     *
7348     * @hide
7349     */
7350    public void clearAccessibilityFocus() {
7351        clearAccessibilityFocusNoCallbacks();
7352        // Clear the global reference of accessibility focus if this
7353        // view or any of its descendants had accessibility focus.
7354        ViewRootImpl viewRootImpl = getViewRootImpl();
7355        if (viewRootImpl != null) {
7356            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
7357            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
7358                viewRootImpl.setAccessibilityFocus(null, null);
7359            }
7360        }
7361    }
7362
7363    private void sendAccessibilityHoverEvent(int eventType) {
7364        // Since we are not delivering to a client accessibility events from not
7365        // important views (unless the clinet request that) we need to fire the
7366        // event from the deepest view exposed to the client. As a consequence if
7367        // the user crosses a not exposed view the client will see enter and exit
7368        // of the exposed predecessor followed by and enter and exit of that same
7369        // predecessor when entering and exiting the not exposed descendant. This
7370        // is fine since the client has a clear idea which view is hovered at the
7371        // price of a couple more events being sent. This is a simple and
7372        // working solution.
7373        View source = this;
7374        while (true) {
7375            if (source.includeForAccessibility()) {
7376                source.sendAccessibilityEvent(eventType);
7377                return;
7378            }
7379            ViewParent parent = source.getParent();
7380            if (parent instanceof View) {
7381                source = (View) parent;
7382            } else {
7383                return;
7384            }
7385        }
7386    }
7387
7388    /**
7389     * Clears accessibility focus without calling any callback methods
7390     * normally invoked in {@link #clearAccessibilityFocus()}. This method
7391     * is used for clearing accessibility focus when giving this focus to
7392     * another view.
7393     */
7394    void clearAccessibilityFocusNoCallbacks() {
7395        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
7396            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
7397            invalidate();
7398            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
7399        }
7400    }
7401
7402    /**
7403     * Call this to try to give focus to a specific view or to one of its
7404     * descendants.
7405     *
7406     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7407     * false), or if it is focusable and it is not focusable in touch mode
7408     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7409     *
7410     * See also {@link #focusSearch(int)}, which is what you call to say that you
7411     * have focus, and you want your parent to look for the next one.
7412     *
7413     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
7414     * {@link #FOCUS_DOWN} and <code>null</code>.
7415     *
7416     * @return Whether this view or one of its descendants actually took focus.
7417     */
7418    public final boolean requestFocus() {
7419        return requestFocus(View.FOCUS_DOWN);
7420    }
7421
7422    /**
7423     * Call this to try to give focus to a specific view or to one of its
7424     * descendants and give it a hint about what direction focus is heading.
7425     *
7426     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7427     * false), or if it is focusable and it is not focusable in touch mode
7428     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7429     *
7430     * See also {@link #focusSearch(int)}, which is what you call to say that you
7431     * have focus, and you want your parent to look for the next one.
7432     *
7433     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
7434     * <code>null</code> set for the previously focused rectangle.
7435     *
7436     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7437     * @return Whether this view or one of its descendants actually took focus.
7438     */
7439    public final boolean requestFocus(int direction) {
7440        return requestFocus(direction, null);
7441    }
7442
7443    /**
7444     * Call this to try to give focus to a specific view or to one of its descendants
7445     * and give it hints about the direction and a specific rectangle that the focus
7446     * is coming from.  The rectangle can help give larger views a finer grained hint
7447     * about where focus is coming from, and therefore, where to show selection, or
7448     * forward focus change internally.
7449     *
7450     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
7451     * false), or if it is focusable and it is not focusable in touch mode
7452     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
7453     *
7454     * A View will not take focus if it is not visible.
7455     *
7456     * A View will not take focus if one of its parents has
7457     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
7458     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
7459     *
7460     * See also {@link #focusSearch(int)}, which is what you call to say that you
7461     * have focus, and you want your parent to look for the next one.
7462     *
7463     * You may wish to override this method if your custom {@link View} has an internal
7464     * {@link View} that it wishes to forward the request to.
7465     *
7466     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
7467     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
7468     *        to give a finer grained hint about where focus is coming from.  May be null
7469     *        if there is no hint.
7470     * @return Whether this view or one of its descendants actually took focus.
7471     */
7472    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
7473        return requestFocusNoSearch(direction, previouslyFocusedRect);
7474    }
7475
7476    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
7477        // need to be focusable
7478        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
7479                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
7480            return false;
7481        }
7482
7483        // need to be focusable in touch mode if in touch mode
7484        if (isInTouchMode() &&
7485            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
7486               return false;
7487        }
7488
7489        // need to not have any parents blocking us
7490        if (hasAncestorThatBlocksDescendantFocus()) {
7491            return false;
7492        }
7493
7494        handleFocusGainInternal(direction, previouslyFocusedRect);
7495        return true;
7496    }
7497
7498    /**
7499     * Call this to try to give focus to a specific view or to one of its descendants. This is a
7500     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
7501     * touch mode to request focus when they are touched.
7502     *
7503     * @return Whether this view or one of its descendants actually took focus.
7504     *
7505     * @see #isInTouchMode()
7506     *
7507     */
7508    public final boolean requestFocusFromTouch() {
7509        // Leave touch mode if we need to
7510        if (isInTouchMode()) {
7511            ViewRootImpl viewRoot = getViewRootImpl();
7512            if (viewRoot != null) {
7513                viewRoot.ensureTouchMode(false);
7514            }
7515        }
7516        return requestFocus(View.FOCUS_DOWN);
7517    }
7518
7519    /**
7520     * @return Whether any ancestor of this view blocks descendant focus.
7521     */
7522    private boolean hasAncestorThatBlocksDescendantFocus() {
7523        final boolean focusableInTouchMode = isFocusableInTouchMode();
7524        ViewParent ancestor = mParent;
7525        while (ancestor instanceof ViewGroup) {
7526            final ViewGroup vgAncestor = (ViewGroup) ancestor;
7527            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS
7528                    || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) {
7529                return true;
7530            } else {
7531                ancestor = vgAncestor.getParent();
7532            }
7533        }
7534        return false;
7535    }
7536
7537    /**
7538     * Gets the mode for determining whether this View is important for accessibility
7539     * which is if it fires accessibility events and if it is reported to
7540     * accessibility services that query the screen.
7541     *
7542     * @return The mode for determining whether a View is important for accessibility.
7543     *
7544     * @attr ref android.R.styleable#View_importantForAccessibility
7545     *
7546     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7547     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7548     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7549     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7550     */
7551    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
7552            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
7553            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
7554            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"),
7555            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS,
7556                    to = "noHideDescendants")
7557        })
7558    public int getImportantForAccessibility() {
7559        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7560                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7561    }
7562
7563    /**
7564     * Sets the live region mode for this view. This indicates to accessibility
7565     * services whether they should automatically notify the user about changes
7566     * to the view's content description or text, or to the content descriptions
7567     * or text of the view's children (where applicable).
7568     * <p>
7569     * For example, in a login screen with a TextView that displays an "incorrect
7570     * password" notification, that view should be marked as a live region with
7571     * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7572     * <p>
7573     * To disable change notifications for this view, use
7574     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region
7575     * mode for most views.
7576     * <p>
7577     * To indicate that the user should be notified of changes, use
7578     * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}.
7579     * <p>
7580     * If the view's changes should interrupt ongoing speech and notify the user
7581     * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}.
7582     *
7583     * @param mode The live region mode for this view, one of:
7584     *        <ul>
7585     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE}
7586     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE}
7587     *        <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}
7588     *        </ul>
7589     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7590     */
7591    public void setAccessibilityLiveRegion(int mode) {
7592        if (mode != getAccessibilityLiveRegion()) {
7593            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7594            mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT)
7595                    & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK;
7596            notifyViewAccessibilityStateChangedIfNeeded(
7597                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7598        }
7599    }
7600
7601    /**
7602     * Gets the live region mode for this View.
7603     *
7604     * @return The live region mode for the view.
7605     *
7606     * @attr ref android.R.styleable#View_accessibilityLiveRegion
7607     *
7608     * @see #setAccessibilityLiveRegion(int)
7609     */
7610    public int getAccessibilityLiveRegion() {
7611        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK)
7612                >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT;
7613    }
7614
7615    /**
7616     * Sets how to determine whether this view is important for accessibility
7617     * which is if it fires accessibility events and if it is reported to
7618     * accessibility services that query the screen.
7619     *
7620     * @param mode How to determine whether this view is important for accessibility.
7621     *
7622     * @attr ref android.R.styleable#View_importantForAccessibility
7623     *
7624     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
7625     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
7626     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
7627     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
7628     */
7629    public void setImportantForAccessibility(int mode) {
7630        final int oldMode = getImportantForAccessibility();
7631        if (mode != oldMode) {
7632            // If we're moving between AUTO and another state, we might not need
7633            // to send a subtree changed notification. We'll store the computed
7634            // importance, since we'll need to check it later to make sure.
7635            final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO
7636                    || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO;
7637            final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility();
7638            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7639            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
7640                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
7641            if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) {
7642                notifySubtreeAccessibilityStateChangedIfNeeded();
7643            } else {
7644                notifyViewAccessibilityStateChangedIfNeeded(
7645                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7646            }
7647        }
7648    }
7649
7650    /**
7651     * Computes whether this view should be exposed for accessibility. In
7652     * general, views that are interactive or provide information are exposed
7653     * while views that serve only as containers are hidden.
7654     * <p>
7655     * If an ancestor of this view has importance
7656     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method
7657     * returns <code>false</code>.
7658     * <p>
7659     * Otherwise, the value is computed according to the view's
7660     * {@link #getImportantForAccessibility()} value:
7661     * <ol>
7662     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or
7663     * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false
7664     * </code>
7665     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code>
7666     * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if
7667     * view satisfies any of the following:
7668     * <ul>
7669     * <li>Is actionable, e.g. {@link #isClickable()},
7670     * {@link #isLongClickable()}, or {@link #isFocusable()}
7671     * <li>Has an {@link AccessibilityDelegate}
7672     * <li>Has an interaction listener, e.g. {@link OnTouchListener},
7673     * {@link OnKeyListener}, etc.
7674     * <li>Is an accessibility live region, e.g.
7675     * {@link #getAccessibilityLiveRegion()} is not
7676     * {@link #ACCESSIBILITY_LIVE_REGION_NONE}.
7677     * </ul>
7678     * </ol>
7679     *
7680     * @return Whether the view is exposed for accessibility.
7681     * @see #setImportantForAccessibility(int)
7682     * @see #getImportantForAccessibility()
7683     */
7684    public boolean isImportantForAccessibility() {
7685        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
7686                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
7687        if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO
7688                || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7689            return false;
7690        }
7691
7692        // Check parent mode to ensure we're not hidden.
7693        ViewParent parent = mParent;
7694        while (parent instanceof View) {
7695            if (((View) parent).getImportantForAccessibility()
7696                    == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
7697                return false;
7698            }
7699            parent = parent.getParent();
7700        }
7701
7702        return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility()
7703                || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null
7704                || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE;
7705    }
7706
7707    /**
7708     * Gets the parent for accessibility purposes. Note that the parent for
7709     * accessibility is not necessary the immediate parent. It is the first
7710     * predecessor that is important for accessibility.
7711     *
7712     * @return The parent for accessibility purposes.
7713     */
7714    public ViewParent getParentForAccessibility() {
7715        if (mParent instanceof View) {
7716            View parentView = (View) mParent;
7717            if (parentView.includeForAccessibility()) {
7718                return mParent;
7719            } else {
7720                return mParent.getParentForAccessibility();
7721            }
7722        }
7723        return null;
7724    }
7725
7726    /**
7727     * Adds the children of a given View for accessibility. Since some Views are
7728     * not important for accessibility the children for accessibility are not
7729     * necessarily direct children of the view, rather they are the first level of
7730     * descendants important for accessibility.
7731     *
7732     * @param children The list of children for accessibility.
7733     */
7734    public void addChildrenForAccessibility(ArrayList<View> children) {
7735
7736    }
7737
7738    /**
7739     * Whether to regard this view for accessibility. A view is regarded for
7740     * accessibility if it is important for accessibility or the querying
7741     * accessibility service has explicitly requested that view not
7742     * important for accessibility are regarded.
7743     *
7744     * @return Whether to regard the view for accessibility.
7745     *
7746     * @hide
7747     */
7748    public boolean includeForAccessibility() {
7749        if (mAttachInfo != null) {
7750            return (mAttachInfo.mAccessibilityFetchFlags
7751                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
7752                    || isImportantForAccessibility();
7753        }
7754        return false;
7755    }
7756
7757    /**
7758     * Returns whether the View is considered actionable from
7759     * accessibility perspective. Such view are important for
7760     * accessibility.
7761     *
7762     * @return True if the view is actionable for accessibility.
7763     *
7764     * @hide
7765     */
7766    public boolean isActionableForAccessibility() {
7767        return (isClickable() || isLongClickable() || isFocusable());
7768    }
7769
7770    /**
7771     * Returns whether the View has registered callbacks which makes it
7772     * important for accessibility.
7773     *
7774     * @return True if the view is actionable for accessibility.
7775     */
7776    private boolean hasListenersForAccessibility() {
7777        ListenerInfo info = getListenerInfo();
7778        return mTouchDelegate != null || info.mOnKeyListener != null
7779                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
7780                || info.mOnHoverListener != null || info.mOnDragListener != null;
7781    }
7782
7783    /**
7784     * Notifies that the accessibility state of this view changed. The change
7785     * is local to this view and does not represent structural changes such
7786     * as children and parent. For example, the view became focusable. The
7787     * notification is at at most once every
7788     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7789     * to avoid unnecessary load to the system. Also once a view has a pending
7790     * notification this method is a NOP until the notification has been sent.
7791     *
7792     * @hide
7793     */
7794    public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) {
7795        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7796            return;
7797        }
7798        if (mSendViewStateChangedAccessibilityEvent == null) {
7799            mSendViewStateChangedAccessibilityEvent =
7800                    new SendViewStateChangedAccessibilityEvent();
7801        }
7802        mSendViewStateChangedAccessibilityEvent.runOrPost(changeType);
7803    }
7804
7805    /**
7806     * Notifies that the accessibility state of this view changed. The change
7807     * is *not* local to this view and does represent structural changes such
7808     * as children and parent. For example, the view size changed. The
7809     * notification is at at most once every
7810     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
7811     * to avoid unnecessary load to the system. Also once a view has a pending
7812     * notification this method is a NOP until the notification has been sent.
7813     *
7814     * @hide
7815     */
7816    public void notifySubtreeAccessibilityStateChangedIfNeeded() {
7817        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
7818            return;
7819        }
7820        if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) {
7821            mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7822            if (mParent != null) {
7823                try {
7824                    mParent.notifySubtreeAccessibilityStateChanged(
7825                            this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
7826                } catch (AbstractMethodError e) {
7827                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
7828                            " does not fully implement ViewParent", e);
7829                }
7830            }
7831        }
7832    }
7833
7834    /**
7835     * Reset the flag indicating the accessibility state of the subtree rooted
7836     * at this view changed.
7837     */
7838    void resetSubtreeAccessibilityStateChanged() {
7839        mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED;
7840    }
7841
7842    /**
7843     * Performs the specified accessibility action on the view. For
7844     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
7845     * <p>
7846     * If an {@link AccessibilityDelegate} has been specified via calling
7847     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
7848     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
7849     * is responsible for handling this call.
7850     * </p>
7851     *
7852     * @param action The action to perform.
7853     * @param arguments Optional action arguments.
7854     * @return Whether the action was performed.
7855     */
7856    public boolean performAccessibilityAction(int action, Bundle arguments) {
7857      if (mAccessibilityDelegate != null) {
7858          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7859      } else {
7860          return performAccessibilityActionInternal(action, arguments);
7861      }
7862    }
7863
7864   /**
7865    * @see #performAccessibilityAction(int, Bundle)
7866    *
7867    * Note: Called from the default {@link AccessibilityDelegate}.
7868    */
7869    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7870        switch (action) {
7871            case AccessibilityNodeInfo.ACTION_CLICK: {
7872                if (isClickable()) {
7873                    performClick();
7874                    return true;
7875                }
7876            } break;
7877            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7878                if (isLongClickable()) {
7879                    performLongClick();
7880                    return true;
7881                }
7882            } break;
7883            case AccessibilityNodeInfo.ACTION_FOCUS: {
7884                if (!hasFocus()) {
7885                    // Get out of touch mode since accessibility
7886                    // wants to move focus around.
7887                    getViewRootImpl().ensureTouchMode(false);
7888                    return requestFocus();
7889                }
7890            } break;
7891            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7892                if (hasFocus()) {
7893                    clearFocus();
7894                    return !isFocused();
7895                }
7896            } break;
7897            case AccessibilityNodeInfo.ACTION_SELECT: {
7898                if (!isSelected()) {
7899                    setSelected(true);
7900                    return isSelected();
7901                }
7902            } break;
7903            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7904                if (isSelected()) {
7905                    setSelected(false);
7906                    return !isSelected();
7907                }
7908            } break;
7909            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7910                if (!isAccessibilityFocused()) {
7911                    return requestAccessibilityFocus();
7912                }
7913            } break;
7914            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7915                if (isAccessibilityFocused()) {
7916                    clearAccessibilityFocus();
7917                    return true;
7918                }
7919            } break;
7920            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7921                if (arguments != null) {
7922                    final int granularity = arguments.getInt(
7923                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7924                    final boolean extendSelection = arguments.getBoolean(
7925                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7926                    return traverseAtGranularity(granularity, true, extendSelection);
7927                }
7928            } break;
7929            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7930                if (arguments != null) {
7931                    final int granularity = arguments.getInt(
7932                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7933                    final boolean extendSelection = arguments.getBoolean(
7934                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7935                    return traverseAtGranularity(granularity, false, extendSelection);
7936                }
7937            } break;
7938            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7939                CharSequence text = getIterableTextForAccessibility();
7940                if (text == null) {
7941                    return false;
7942                }
7943                final int start = (arguments != null) ? arguments.getInt(
7944                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7945                final int end = (arguments != null) ? arguments.getInt(
7946                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7947                // Only cursor position can be specified (selection length == 0)
7948                if ((getAccessibilitySelectionStart() != start
7949                        || getAccessibilitySelectionEnd() != end)
7950                        && (start == end)) {
7951                    setAccessibilitySelection(start, end);
7952                    notifyViewAccessibilityStateChangedIfNeeded(
7953                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
7954                    return true;
7955                }
7956            } break;
7957        }
7958        return false;
7959    }
7960
7961    private boolean traverseAtGranularity(int granularity, boolean forward,
7962            boolean extendSelection) {
7963        CharSequence text = getIterableTextForAccessibility();
7964        if (text == null || text.length() == 0) {
7965            return false;
7966        }
7967        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7968        if (iterator == null) {
7969            return false;
7970        }
7971        int current = getAccessibilitySelectionEnd();
7972        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7973            current = forward ? 0 : text.length();
7974        }
7975        final int[] range = forward ? iterator.following(current) : iterator.preceding(current);
7976        if (range == null) {
7977            return false;
7978        }
7979        final int segmentStart = range[0];
7980        final int segmentEnd = range[1];
7981        int selectionStart;
7982        int selectionEnd;
7983        if (extendSelection && isAccessibilitySelectionExtendable()) {
7984            selectionStart = getAccessibilitySelectionStart();
7985            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7986                selectionStart = forward ? segmentStart : segmentEnd;
7987            }
7988            selectionEnd = forward ? segmentEnd : segmentStart;
7989        } else {
7990            selectionStart = selectionEnd= forward ? segmentEnd : segmentStart;
7991        }
7992        setAccessibilitySelection(selectionStart, selectionEnd);
7993        final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
7994                : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY;
7995        sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd);
7996        return true;
7997    }
7998
7999    /**
8000     * Gets the text reported for accessibility purposes.
8001     *
8002     * @return The accessibility text.
8003     *
8004     * @hide
8005     */
8006    public CharSequence getIterableTextForAccessibility() {
8007        return getContentDescription();
8008    }
8009
8010    /**
8011     * Gets whether accessibility selection can be extended.
8012     *
8013     * @return If selection is extensible.
8014     *
8015     * @hide
8016     */
8017    public boolean isAccessibilitySelectionExtendable() {
8018        return false;
8019    }
8020
8021    /**
8022     * @hide
8023     */
8024    public int getAccessibilitySelectionStart() {
8025        return mAccessibilityCursorPosition;
8026    }
8027
8028    /**
8029     * @hide
8030     */
8031    public int getAccessibilitySelectionEnd() {
8032        return getAccessibilitySelectionStart();
8033    }
8034
8035    /**
8036     * @hide
8037     */
8038    public void setAccessibilitySelection(int start, int end) {
8039        if (start ==  end && end == mAccessibilityCursorPosition) {
8040            return;
8041        }
8042        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
8043            mAccessibilityCursorPosition = start;
8044        } else {
8045            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
8046        }
8047        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
8048    }
8049
8050    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
8051            int fromIndex, int toIndex) {
8052        if (mParent == null) {
8053            return;
8054        }
8055        AccessibilityEvent event = AccessibilityEvent.obtain(
8056                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
8057        onInitializeAccessibilityEvent(event);
8058        onPopulateAccessibilityEvent(event);
8059        event.setFromIndex(fromIndex);
8060        event.setToIndex(toIndex);
8061        event.setAction(action);
8062        event.setMovementGranularity(granularity);
8063        mParent.requestSendAccessibilityEvent(this, event);
8064    }
8065
8066    /**
8067     * @hide
8068     */
8069    public TextSegmentIterator getIteratorForGranularity(int granularity) {
8070        switch (granularity) {
8071            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
8072                CharSequence text = getIterableTextForAccessibility();
8073                if (text != null && text.length() > 0) {
8074                    CharacterTextSegmentIterator iterator =
8075                        CharacterTextSegmentIterator.getInstance(
8076                                mContext.getResources().getConfiguration().locale);
8077                    iterator.initialize(text.toString());
8078                    return iterator;
8079                }
8080            } break;
8081            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
8082                CharSequence text = getIterableTextForAccessibility();
8083                if (text != null && text.length() > 0) {
8084                    WordTextSegmentIterator iterator =
8085                        WordTextSegmentIterator.getInstance(
8086                                mContext.getResources().getConfiguration().locale);
8087                    iterator.initialize(text.toString());
8088                    return iterator;
8089                }
8090            } break;
8091            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
8092                CharSequence text = getIterableTextForAccessibility();
8093                if (text != null && text.length() > 0) {
8094                    ParagraphTextSegmentIterator iterator =
8095                        ParagraphTextSegmentIterator.getInstance();
8096                    iterator.initialize(text.toString());
8097                    return iterator;
8098                }
8099            } break;
8100        }
8101        return null;
8102    }
8103
8104    /**
8105     * @hide
8106     */
8107    public void dispatchStartTemporaryDetach() {
8108        onStartTemporaryDetach();
8109    }
8110
8111    /**
8112     * This is called when a container is going to temporarily detach a child, with
8113     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
8114     * It will either be followed by {@link #onFinishTemporaryDetach()} or
8115     * {@link #onDetachedFromWindow()} when the container is done.
8116     */
8117    public void onStartTemporaryDetach() {
8118        removeUnsetPressCallback();
8119        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
8120    }
8121
8122    /**
8123     * @hide
8124     */
8125    public void dispatchFinishTemporaryDetach() {
8126        onFinishTemporaryDetach();
8127    }
8128
8129    /**
8130     * Called after {@link #onStartTemporaryDetach} when the container is done
8131     * changing the view.
8132     */
8133    public void onFinishTemporaryDetach() {
8134    }
8135
8136    /**
8137     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
8138     * for this view's window.  Returns null if the view is not currently attached
8139     * to the window.  Normally you will not need to use this directly, but
8140     * just use the standard high-level event callbacks like
8141     * {@link #onKeyDown(int, KeyEvent)}.
8142     */
8143    public KeyEvent.DispatcherState getKeyDispatcherState() {
8144        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
8145    }
8146
8147    /**
8148     * Dispatch a key event before it is processed by any input method
8149     * associated with the view hierarchy.  This can be used to intercept
8150     * key events in special situations before the IME consumes them; a
8151     * typical example would be handling the BACK key to update the application's
8152     * UI instead of allowing the IME to see it and close itself.
8153     *
8154     * @param event The key event to be dispatched.
8155     * @return True if the event was handled, false otherwise.
8156     */
8157    public boolean dispatchKeyEventPreIme(KeyEvent event) {
8158        return onKeyPreIme(event.getKeyCode(), event);
8159    }
8160
8161    /**
8162     * Dispatch a key event to the next view on the focus path. This path runs
8163     * from the top of the view tree down to the currently focused view. If this
8164     * view has focus, it will dispatch to itself. Otherwise it will dispatch
8165     * the next node down the focus path. This method also fires any key
8166     * listeners.
8167     *
8168     * @param event The key event to be dispatched.
8169     * @return True if the event was handled, false otherwise.
8170     */
8171    public boolean dispatchKeyEvent(KeyEvent event) {
8172        if (mInputEventConsistencyVerifier != null) {
8173            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
8174        }
8175
8176        // Give any attached key listener a first crack at the event.
8177        //noinspection SimplifiableIfStatement
8178        ListenerInfo li = mListenerInfo;
8179        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
8180                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
8181            return true;
8182        }
8183
8184        if (event.dispatch(this, mAttachInfo != null
8185                ? mAttachInfo.mKeyDispatchState : null, this)) {
8186            return true;
8187        }
8188
8189        if (mInputEventConsistencyVerifier != null) {
8190            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8191        }
8192        return false;
8193    }
8194
8195    /**
8196     * Dispatches a key shortcut event.
8197     *
8198     * @param event The key event to be dispatched.
8199     * @return True if the event was handled by the view, false otherwise.
8200     */
8201    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
8202        return onKeyShortcut(event.getKeyCode(), event);
8203    }
8204
8205    /**
8206     * Pass the touch screen motion event down to the target view, or this
8207     * view if it is the target.
8208     *
8209     * @param event The motion event to be dispatched.
8210     * @return True if the event was handled by the view, false otherwise.
8211     */
8212    public boolean dispatchTouchEvent(MotionEvent event) {
8213        boolean result = false;
8214
8215        if (mInputEventConsistencyVerifier != null) {
8216            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
8217        }
8218
8219        final int actionMasked = event.getActionMasked();
8220        if (actionMasked == MotionEvent.ACTION_DOWN) {
8221            // Defensive cleanup for new gesture
8222            stopNestedScroll();
8223        }
8224
8225        if (onFilterTouchEventForSecurity(event)) {
8226            //noinspection SimplifiableIfStatement
8227            ListenerInfo li = mListenerInfo;
8228            if (li != null && li.mOnTouchListener != null
8229                    && (mViewFlags & ENABLED_MASK) == ENABLED
8230                    && li.mOnTouchListener.onTouch(this, event)) {
8231                result = true;
8232            }
8233
8234            if (!result && onTouchEvent(event)) {
8235                result = true;
8236            }
8237        }
8238
8239        if (!result && mInputEventConsistencyVerifier != null) {
8240            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8241        }
8242
8243        // Clean up after nested scrolls if this is the end of a gesture;
8244        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
8245        // of the gesture.
8246        if (actionMasked == MotionEvent.ACTION_UP ||
8247                actionMasked == MotionEvent.ACTION_CANCEL ||
8248                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
8249            stopNestedScroll();
8250        }
8251
8252        return result;
8253    }
8254
8255    /**
8256     * Filter the touch event to apply security policies.
8257     *
8258     * @param event The motion event to be filtered.
8259     * @return True if the event should be dispatched, false if the event should be dropped.
8260     *
8261     * @see #getFilterTouchesWhenObscured
8262     */
8263    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
8264        //noinspection RedundantIfStatement
8265        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
8266                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
8267            // Window is obscured, drop this touch.
8268            return false;
8269        }
8270        return true;
8271    }
8272
8273    /**
8274     * Pass a trackball motion event down to the focused view.
8275     *
8276     * @param event The motion event to be dispatched.
8277     * @return True if the event was handled by the view, false otherwise.
8278     */
8279    public boolean dispatchTrackballEvent(MotionEvent event) {
8280        if (mInputEventConsistencyVerifier != null) {
8281            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
8282        }
8283
8284        return onTrackballEvent(event);
8285    }
8286
8287    /**
8288     * Dispatch a generic motion event.
8289     * <p>
8290     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8291     * are delivered to the view under the pointer.  All other generic motion events are
8292     * delivered to the focused view.  Hover events are handled specially and are delivered
8293     * to {@link #onHoverEvent(MotionEvent)}.
8294     * </p>
8295     *
8296     * @param event The motion event to be dispatched.
8297     * @return True if the event was handled by the view, false otherwise.
8298     */
8299    public boolean dispatchGenericMotionEvent(MotionEvent event) {
8300        if (mInputEventConsistencyVerifier != null) {
8301            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
8302        }
8303
8304        final int source = event.getSource();
8305        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
8306            final int action = event.getAction();
8307            if (action == MotionEvent.ACTION_HOVER_ENTER
8308                    || action == MotionEvent.ACTION_HOVER_MOVE
8309                    || action == MotionEvent.ACTION_HOVER_EXIT) {
8310                if (dispatchHoverEvent(event)) {
8311                    return true;
8312                }
8313            } else if (dispatchGenericPointerEvent(event)) {
8314                return true;
8315            }
8316        } else if (dispatchGenericFocusedEvent(event)) {
8317            return true;
8318        }
8319
8320        if (dispatchGenericMotionEventInternal(event)) {
8321            return true;
8322        }
8323
8324        if (mInputEventConsistencyVerifier != null) {
8325            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8326        }
8327        return false;
8328    }
8329
8330    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
8331        //noinspection SimplifiableIfStatement
8332        ListenerInfo li = mListenerInfo;
8333        if (li != null && li.mOnGenericMotionListener != null
8334                && (mViewFlags & ENABLED_MASK) == ENABLED
8335                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
8336            return true;
8337        }
8338
8339        if (onGenericMotionEvent(event)) {
8340            return true;
8341        }
8342
8343        if (mInputEventConsistencyVerifier != null) {
8344            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
8345        }
8346        return false;
8347    }
8348
8349    /**
8350     * Dispatch a hover event.
8351     * <p>
8352     * Do not call this method directly.
8353     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8354     * </p>
8355     *
8356     * @param event The motion event to be dispatched.
8357     * @return True if the event was handled by the view, false otherwise.
8358     */
8359    protected boolean dispatchHoverEvent(MotionEvent event) {
8360        ListenerInfo li = mListenerInfo;
8361        //noinspection SimplifiableIfStatement
8362        if (li != null && li.mOnHoverListener != null
8363                && (mViewFlags & ENABLED_MASK) == ENABLED
8364                && li.mOnHoverListener.onHover(this, event)) {
8365            return true;
8366        }
8367
8368        return onHoverEvent(event);
8369    }
8370
8371    /**
8372     * Returns true if the view has a child to which it has recently sent
8373     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
8374     * it does not have a hovered child, then it must be the innermost hovered view.
8375     * @hide
8376     */
8377    protected boolean hasHoveredChild() {
8378        return false;
8379    }
8380
8381    /**
8382     * Dispatch a generic motion event to the view under the first pointer.
8383     * <p>
8384     * Do not call this method directly.
8385     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8386     * </p>
8387     *
8388     * @param event The motion event to be dispatched.
8389     * @return True if the event was handled by the view, false otherwise.
8390     */
8391    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
8392        return false;
8393    }
8394
8395    /**
8396     * Dispatch a generic motion event to the currently focused view.
8397     * <p>
8398     * Do not call this method directly.
8399     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
8400     * </p>
8401     *
8402     * @param event The motion event to be dispatched.
8403     * @return True if the event was handled by the view, false otherwise.
8404     */
8405    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
8406        return false;
8407    }
8408
8409    /**
8410     * Dispatch a pointer event.
8411     * <p>
8412     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
8413     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
8414     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
8415     * and should not be expected to handle other pointing device features.
8416     * </p>
8417     *
8418     * @param event The motion event to be dispatched.
8419     * @return True if the event was handled by the view, false otherwise.
8420     * @hide
8421     */
8422    public final boolean dispatchPointerEvent(MotionEvent event) {
8423        if (event.isTouchEvent()) {
8424            return dispatchTouchEvent(event);
8425        } else {
8426            return dispatchGenericMotionEvent(event);
8427        }
8428    }
8429
8430    /**
8431     * Called when the window containing this view gains or loses window focus.
8432     * ViewGroups should override to route to their children.
8433     *
8434     * @param hasFocus True if the window containing this view now has focus,
8435     *        false otherwise.
8436     */
8437    public void dispatchWindowFocusChanged(boolean hasFocus) {
8438        onWindowFocusChanged(hasFocus);
8439    }
8440
8441    /**
8442     * Called when the window containing this view gains or loses focus.  Note
8443     * that this is separate from view focus: to receive key events, both
8444     * your view and its window must have focus.  If a window is displayed
8445     * on top of yours that takes input focus, then your own window will lose
8446     * focus but the view focus will remain unchanged.
8447     *
8448     * @param hasWindowFocus True if the window containing this view now has
8449     *        focus, false otherwise.
8450     */
8451    public void onWindowFocusChanged(boolean hasWindowFocus) {
8452        InputMethodManager imm = InputMethodManager.peekInstance();
8453        if (!hasWindowFocus) {
8454            if (isPressed()) {
8455                setPressed(false);
8456            }
8457            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8458                imm.focusOut(this);
8459            }
8460            removeLongPressCallback();
8461            removeTapCallback();
8462            onFocusLost();
8463        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
8464            imm.focusIn(this);
8465        }
8466        refreshDrawableState();
8467    }
8468
8469    /**
8470     * Returns true if this view is in a window that currently has window focus.
8471     * Note that this is not the same as the view itself having focus.
8472     *
8473     * @return True if this view is in a window that currently has window focus.
8474     */
8475    public boolean hasWindowFocus() {
8476        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
8477    }
8478
8479    /**
8480     * Dispatch a view visibility change down the view hierarchy.
8481     * ViewGroups should override to route to their children.
8482     * @param changedView The view whose visibility changed. Could be 'this' or
8483     * an ancestor view.
8484     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8485     * {@link #INVISIBLE} or {@link #GONE}.
8486     */
8487    protected void dispatchVisibilityChanged(@NonNull View changedView,
8488            @Visibility int visibility) {
8489        onVisibilityChanged(changedView, visibility);
8490    }
8491
8492    /**
8493     * Called when the visibility of the view or an ancestor of the view is changed.
8494     * @param changedView The view whose visibility changed. Could be 'this' or
8495     * an ancestor view.
8496     * @param visibility The new visibility of changedView: {@link #VISIBLE},
8497     * {@link #INVISIBLE} or {@link #GONE}.
8498     */
8499    protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) {
8500        if (visibility == VISIBLE) {
8501            if (mAttachInfo != null) {
8502                initialAwakenScrollBars();
8503            } else {
8504                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
8505            }
8506        }
8507    }
8508
8509    /**
8510     * Dispatch a hint about whether this view is displayed. For instance, when
8511     * a View moves out of the screen, it might receives a display hint indicating
8512     * the view is not displayed. Applications should not <em>rely</em> on this hint
8513     * as there is no guarantee that they will receive one.
8514     *
8515     * @param hint A hint about whether or not this view is displayed:
8516     * {@link #VISIBLE} or {@link #INVISIBLE}.
8517     */
8518    public void dispatchDisplayHint(@Visibility int hint) {
8519        onDisplayHint(hint);
8520    }
8521
8522    /**
8523     * Gives this view a hint about whether is displayed or not. For instance, when
8524     * a View moves out of the screen, it might receives a display hint indicating
8525     * the view is not displayed. Applications should not <em>rely</em> on this hint
8526     * as there is no guarantee that they will receive one.
8527     *
8528     * @param hint A hint about whether or not this view is displayed:
8529     * {@link #VISIBLE} or {@link #INVISIBLE}.
8530     */
8531    protected void onDisplayHint(@Visibility int hint) {
8532    }
8533
8534    /**
8535     * Dispatch a window visibility change down the view hierarchy.
8536     * ViewGroups should override to route to their children.
8537     *
8538     * @param visibility The new visibility of the window.
8539     *
8540     * @see #onWindowVisibilityChanged(int)
8541     */
8542    public void dispatchWindowVisibilityChanged(@Visibility int visibility) {
8543        onWindowVisibilityChanged(visibility);
8544    }
8545
8546    /**
8547     * Called when the window containing has change its visibility
8548     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
8549     * that this tells you whether or not your window is being made visible
8550     * to the window manager; this does <em>not</em> tell you whether or not
8551     * your window is obscured by other windows on the screen, even if it
8552     * is itself visible.
8553     *
8554     * @param visibility The new visibility of the window.
8555     */
8556    protected void onWindowVisibilityChanged(@Visibility int visibility) {
8557        if (visibility == VISIBLE) {
8558            initialAwakenScrollBars();
8559        }
8560    }
8561
8562    /**
8563     * Returns the current visibility of the window this view is attached to
8564     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
8565     *
8566     * @return Returns the current visibility of the view's window.
8567     */
8568    @Visibility
8569    public int getWindowVisibility() {
8570        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
8571    }
8572
8573    /**
8574     * Retrieve the overall visible display size in which the window this view is
8575     * attached to has been positioned in.  This takes into account screen
8576     * decorations above the window, for both cases where the window itself
8577     * is being position inside of them or the window is being placed under
8578     * then and covered insets are used for the window to position its content
8579     * inside.  In effect, this tells you the available area where content can
8580     * be placed and remain visible to users.
8581     *
8582     * <p>This function requires an IPC back to the window manager to retrieve
8583     * the requested information, so should not be used in performance critical
8584     * code like drawing.
8585     *
8586     * @param outRect Filled in with the visible display frame.  If the view
8587     * is not attached to a window, this is simply the raw display size.
8588     */
8589    public void getWindowVisibleDisplayFrame(Rect outRect) {
8590        if (mAttachInfo != null) {
8591            try {
8592                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
8593            } catch (RemoteException e) {
8594                return;
8595            }
8596            // XXX This is really broken, and probably all needs to be done
8597            // in the window manager, and we need to know more about whether
8598            // we want the area behind or in front of the IME.
8599            final Rect insets = mAttachInfo.mVisibleInsets;
8600            outRect.left += insets.left;
8601            outRect.top += insets.top;
8602            outRect.right -= insets.right;
8603            outRect.bottom -= insets.bottom;
8604            return;
8605        }
8606        // The view is not attached to a display so we don't have a context.
8607        // Make a best guess about the display size.
8608        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
8609        d.getRectSize(outRect);
8610    }
8611
8612    /**
8613     * Dispatch a notification about a resource configuration change down
8614     * the view hierarchy.
8615     * ViewGroups should override to route to their children.
8616     *
8617     * @param newConfig The new resource configuration.
8618     *
8619     * @see #onConfigurationChanged(android.content.res.Configuration)
8620     */
8621    public void dispatchConfigurationChanged(Configuration newConfig) {
8622        onConfigurationChanged(newConfig);
8623    }
8624
8625    /**
8626     * Called when the current configuration of the resources being used
8627     * by the application have changed.  You can use this to decide when
8628     * to reload resources that can changed based on orientation and other
8629     * configuration characterstics.  You only need to use this if you are
8630     * not relying on the normal {@link android.app.Activity} mechanism of
8631     * recreating the activity instance upon a configuration change.
8632     *
8633     * @param newConfig The new resource configuration.
8634     */
8635    protected void onConfigurationChanged(Configuration newConfig) {
8636    }
8637
8638    /**
8639     * Private function to aggregate all per-view attributes in to the view
8640     * root.
8641     */
8642    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8643        performCollectViewAttributes(attachInfo, visibility);
8644    }
8645
8646    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
8647        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
8648            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
8649                attachInfo.mKeepScreenOn = true;
8650            }
8651            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
8652            ListenerInfo li = mListenerInfo;
8653            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
8654                attachInfo.mHasSystemUiListeners = true;
8655            }
8656        }
8657    }
8658
8659    void needGlobalAttributesUpdate(boolean force) {
8660        final AttachInfo ai = mAttachInfo;
8661        if (ai != null && !ai.mRecomputeGlobalAttributes) {
8662            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
8663                    || ai.mHasSystemUiListeners) {
8664                ai.mRecomputeGlobalAttributes = true;
8665            }
8666        }
8667    }
8668
8669    /**
8670     * Returns whether the device is currently in touch mode.  Touch mode is entered
8671     * once the user begins interacting with the device by touch, and affects various
8672     * things like whether focus is always visible to the user.
8673     *
8674     * @return Whether the device is in touch mode.
8675     */
8676    @ViewDebug.ExportedProperty
8677    public boolean isInTouchMode() {
8678        if (mAttachInfo != null) {
8679            return mAttachInfo.mInTouchMode;
8680        } else {
8681            return ViewRootImpl.isInTouchMode();
8682        }
8683    }
8684
8685    /**
8686     * Returns the context the view is running in, through which it can
8687     * access the current theme, resources, etc.
8688     *
8689     * @return The view's Context.
8690     */
8691    @ViewDebug.CapturedViewProperty
8692    public final Context getContext() {
8693        return mContext;
8694    }
8695
8696    /**
8697     * Handle a key event before it is processed by any input method
8698     * associated with the view hierarchy.  This can be used to intercept
8699     * key events in special situations before the IME consumes them; a
8700     * typical example would be handling the BACK key to update the application's
8701     * UI instead of allowing the IME to see it and close itself.
8702     *
8703     * @param keyCode The value in event.getKeyCode().
8704     * @param event Description of the key event.
8705     * @return If you handled the event, return true. If you want to allow the
8706     *         event to be handled by the next receiver, return false.
8707     */
8708    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
8709        return false;
8710    }
8711
8712    /**
8713     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
8714     * KeyEvent.Callback.onKeyDown()}: perform press of the view
8715     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
8716     * is released, if the view is enabled and clickable.
8717     *
8718     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8719     * although some may elect to do so in some situations. Do not rely on this to
8720     * catch software key presses.
8721     *
8722     * @param keyCode A key code that represents the button pressed, from
8723     *                {@link android.view.KeyEvent}.
8724     * @param event   The KeyEvent object that defines the button action.
8725     */
8726    public boolean onKeyDown(int keyCode, KeyEvent event) {
8727        boolean result = false;
8728
8729        if (KeyEvent.isConfirmKey(keyCode)) {
8730            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8731                return true;
8732            }
8733            // Long clickable items don't necessarily have to be clickable
8734            if (((mViewFlags & CLICKABLE) == CLICKABLE ||
8735                    (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
8736                    (event.getRepeatCount() == 0)) {
8737                setPressed(true);
8738                checkForLongClick(0);
8739                return true;
8740            }
8741        }
8742        return result;
8743    }
8744
8745    /**
8746     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
8747     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
8748     * the event).
8749     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8750     * although some may elect to do so in some situations. Do not rely on this to
8751     * catch software key presses.
8752     */
8753    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
8754        return false;
8755    }
8756
8757    /**
8758     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
8759     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
8760     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
8761     * {@link KeyEvent#KEYCODE_ENTER} is released.
8762     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8763     * although some may elect to do so in some situations. Do not rely on this to
8764     * catch software key presses.
8765     *
8766     * @param keyCode A key code that represents the button pressed, from
8767     *                {@link android.view.KeyEvent}.
8768     * @param event   The KeyEvent object that defines the button action.
8769     */
8770    public boolean onKeyUp(int keyCode, KeyEvent event) {
8771        if (KeyEvent.isConfirmKey(keyCode)) {
8772            if ((mViewFlags & ENABLED_MASK) == DISABLED) {
8773                return true;
8774            }
8775            if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
8776                setPressed(false);
8777
8778                if (!mHasPerformedLongPress) {
8779                    // This is a tap, so remove the longpress check
8780                    removeLongPressCallback();
8781                    return performClick();
8782                }
8783            }
8784        }
8785        return false;
8786    }
8787
8788    /**
8789     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
8790     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
8791     * the event).
8792     * <p>Key presses in software keyboards will generally NOT trigger this listener,
8793     * although some may elect to do so in some situations. Do not rely on this to
8794     * catch software key presses.
8795     *
8796     * @param keyCode     A key code that represents the button pressed, from
8797     *                    {@link android.view.KeyEvent}.
8798     * @param repeatCount The number of times the action was made.
8799     * @param event       The KeyEvent object that defines the button action.
8800     */
8801    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
8802        return false;
8803    }
8804
8805    /**
8806     * Called on the focused view when a key shortcut event is not handled.
8807     * Override this method to implement local key shortcuts for the View.
8808     * Key shortcuts can also be implemented by setting the
8809     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
8810     *
8811     * @param keyCode The value in event.getKeyCode().
8812     * @param event Description of the key event.
8813     * @return If you handled the event, return true. If you want to allow the
8814     *         event to be handled by the next receiver, return false.
8815     */
8816    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
8817        return false;
8818    }
8819
8820    /**
8821     * Check whether the called view is a text editor, in which case it
8822     * would make sense to automatically display a soft input window for
8823     * it.  Subclasses should override this if they implement
8824     * {@link #onCreateInputConnection(EditorInfo)} to return true if
8825     * a call on that method would return a non-null InputConnection, and
8826     * they are really a first-class editor that the user would normally
8827     * start typing on when the go into a window containing your view.
8828     *
8829     * <p>The default implementation always returns false.  This does
8830     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
8831     * will not be called or the user can not otherwise perform edits on your
8832     * view; it is just a hint to the system that this is not the primary
8833     * purpose of this view.
8834     *
8835     * @return Returns true if this view is a text editor, else false.
8836     */
8837    public boolean onCheckIsTextEditor() {
8838        return false;
8839    }
8840
8841    /**
8842     * Create a new InputConnection for an InputMethod to interact
8843     * with the view.  The default implementation returns null, since it doesn't
8844     * support input methods.  You can override this to implement such support.
8845     * This is only needed for views that take focus and text input.
8846     *
8847     * <p>When implementing this, you probably also want to implement
8848     * {@link #onCheckIsTextEditor()} to indicate you will return a
8849     * non-null InputConnection.</p>
8850     *
8851     * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo}
8852     * object correctly and in its entirety, so that the connected IME can rely
8853     * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart}
8854     * and  {@link android.view.inputmethod.EditorInfo#initialSelEnd} members
8855     * must be filled in with the correct cursor position for IMEs to work correctly
8856     * with your application.</p>
8857     *
8858     * @param outAttrs Fill in with attribute information about the connection.
8859     */
8860    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8861        return null;
8862    }
8863
8864    /**
8865     * Called by the {@link android.view.inputmethod.InputMethodManager}
8866     * when a view who is not the current
8867     * input connection target is trying to make a call on the manager.  The
8868     * default implementation returns false; you can override this to return
8869     * true for certain views if you are performing InputConnection proxying
8870     * to them.
8871     * @param view The View that is making the InputMethodManager call.
8872     * @return Return true to allow the call, false to reject.
8873     */
8874    public boolean checkInputConnectionProxy(View view) {
8875        return false;
8876    }
8877
8878    /**
8879     * Show the context menu for this view. It is not safe to hold on to the
8880     * menu after returning from this method.
8881     *
8882     * You should normally not overload this method. Overload
8883     * {@link #onCreateContextMenu(ContextMenu)} or define an
8884     * {@link OnCreateContextMenuListener} to add items to the context menu.
8885     *
8886     * @param menu The context menu to populate
8887     */
8888    public void createContextMenu(ContextMenu menu) {
8889        ContextMenuInfo menuInfo = getContextMenuInfo();
8890
8891        // Sets the current menu info so all items added to menu will have
8892        // my extra info set.
8893        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8894
8895        onCreateContextMenu(menu);
8896        ListenerInfo li = mListenerInfo;
8897        if (li != null && li.mOnCreateContextMenuListener != null) {
8898            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8899        }
8900
8901        // Clear the extra information so subsequent items that aren't mine don't
8902        // have my extra info.
8903        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8904
8905        if (mParent != null) {
8906            mParent.createContextMenu(menu);
8907        }
8908    }
8909
8910    /**
8911     * Views should implement this if they have extra information to associate
8912     * with the context menu. The return result is supplied as a parameter to
8913     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8914     * callback.
8915     *
8916     * @return Extra information about the item for which the context menu
8917     *         should be shown. This information will vary across different
8918     *         subclasses of View.
8919     */
8920    protected ContextMenuInfo getContextMenuInfo() {
8921        return null;
8922    }
8923
8924    /**
8925     * Views should implement this if the view itself is going to add items to
8926     * the context menu.
8927     *
8928     * @param menu the context menu to populate
8929     */
8930    protected void onCreateContextMenu(ContextMenu menu) {
8931    }
8932
8933    /**
8934     * Implement this method to handle trackball motion events.  The
8935     * <em>relative</em> movement of the trackball since the last event
8936     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8937     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8938     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8939     * they will often be fractional values, representing the more fine-grained
8940     * movement information available from a trackball).
8941     *
8942     * @param event The motion event.
8943     * @return True if the event was handled, false otherwise.
8944     */
8945    public boolean onTrackballEvent(MotionEvent event) {
8946        return false;
8947    }
8948
8949    /**
8950     * Implement this method to handle generic motion events.
8951     * <p>
8952     * Generic motion events describe joystick movements, mouse hovers, track pad
8953     * touches, scroll wheel movements and other input events.  The
8954     * {@link MotionEvent#getSource() source} of the motion event specifies
8955     * the class of input that was received.  Implementations of this method
8956     * must examine the bits in the source before processing the event.
8957     * The following code example shows how this is done.
8958     * </p><p>
8959     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8960     * are delivered to the view under the pointer.  All other generic motion events are
8961     * delivered to the focused view.
8962     * </p>
8963     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8964     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8965     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8966     *             // process the joystick movement...
8967     *             return true;
8968     *         }
8969     *     }
8970     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8971     *         switch (event.getAction()) {
8972     *             case MotionEvent.ACTION_HOVER_MOVE:
8973     *                 // process the mouse hover movement...
8974     *                 return true;
8975     *             case MotionEvent.ACTION_SCROLL:
8976     *                 // process the scroll wheel movement...
8977     *                 return true;
8978     *         }
8979     *     }
8980     *     return super.onGenericMotionEvent(event);
8981     * }</pre>
8982     *
8983     * @param event The generic motion event being processed.
8984     * @return True if the event was handled, false otherwise.
8985     */
8986    public boolean onGenericMotionEvent(MotionEvent event) {
8987        return false;
8988    }
8989
8990    /**
8991     * Implement this method to handle hover events.
8992     * <p>
8993     * This method is called whenever a pointer is hovering into, over, or out of the
8994     * bounds of a view and the view is not currently being touched.
8995     * Hover events are represented as pointer events with action
8996     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8997     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8998     * </p>
8999     * <ul>
9000     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
9001     * when the pointer enters the bounds of the view.</li>
9002     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
9003     * when the pointer has already entered the bounds of the view and has moved.</li>
9004     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
9005     * when the pointer has exited the bounds of the view or when the pointer is
9006     * about to go down due to a button click, tap, or similar user action that
9007     * causes the view to be touched.</li>
9008     * </ul>
9009     * <p>
9010     * The view should implement this method to return true to indicate that it is
9011     * handling the hover event, such as by changing its drawable state.
9012     * </p><p>
9013     * The default implementation calls {@link #setHovered} to update the hovered state
9014     * of the view when a hover enter or hover exit event is received, if the view
9015     * is enabled and is clickable.  The default implementation also sends hover
9016     * accessibility events.
9017     * </p>
9018     *
9019     * @param event The motion event that describes the hover.
9020     * @return True if the view handled the hover event.
9021     *
9022     * @see #isHovered
9023     * @see #setHovered
9024     * @see #onHoverChanged
9025     */
9026    public boolean onHoverEvent(MotionEvent event) {
9027        // The root view may receive hover (or touch) events that are outside the bounds of
9028        // the window.  This code ensures that we only send accessibility events for
9029        // hovers that are actually within the bounds of the root view.
9030        final int action = event.getActionMasked();
9031        if (!mSendingHoverAccessibilityEvents) {
9032            if ((action == MotionEvent.ACTION_HOVER_ENTER
9033                    || action == MotionEvent.ACTION_HOVER_MOVE)
9034                    && !hasHoveredChild()
9035                    && pointInView(event.getX(), event.getY())) {
9036                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
9037                mSendingHoverAccessibilityEvents = true;
9038            }
9039        } else {
9040            if (action == MotionEvent.ACTION_HOVER_EXIT
9041                    || (action == MotionEvent.ACTION_MOVE
9042                            && !pointInView(event.getX(), event.getY()))) {
9043                mSendingHoverAccessibilityEvents = false;
9044                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
9045            }
9046        }
9047
9048        if (isHoverable()) {
9049            switch (action) {
9050                case MotionEvent.ACTION_HOVER_ENTER:
9051                    setHovered(true);
9052                    break;
9053                case MotionEvent.ACTION_HOVER_EXIT:
9054                    setHovered(false);
9055                    break;
9056            }
9057
9058            // Dispatch the event to onGenericMotionEvent before returning true.
9059            // This is to provide compatibility with existing applications that
9060            // handled HOVER_MOVE events in onGenericMotionEvent and that would
9061            // break because of the new default handling for hoverable views
9062            // in onHoverEvent.
9063            // Note that onGenericMotionEvent will be called by default when
9064            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
9065            dispatchGenericMotionEventInternal(event);
9066            // The event was already handled by calling setHovered(), so always
9067            // return true.
9068            return true;
9069        }
9070
9071        return false;
9072    }
9073
9074    /**
9075     * Returns true if the view should handle {@link #onHoverEvent}
9076     * by calling {@link #setHovered} to change its hovered state.
9077     *
9078     * @return True if the view is hoverable.
9079     */
9080    private boolean isHoverable() {
9081        final int viewFlags = mViewFlags;
9082        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9083            return false;
9084        }
9085
9086        return (viewFlags & CLICKABLE) == CLICKABLE
9087                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
9088    }
9089
9090    /**
9091     * Returns true if the view is currently hovered.
9092     *
9093     * @return True if the view is currently hovered.
9094     *
9095     * @see #setHovered
9096     * @see #onHoverChanged
9097     */
9098    @ViewDebug.ExportedProperty
9099    public boolean isHovered() {
9100        return (mPrivateFlags & PFLAG_HOVERED) != 0;
9101    }
9102
9103    /**
9104     * Sets whether the view is currently hovered.
9105     * <p>
9106     * Calling this method also changes the drawable state of the view.  This
9107     * enables the view to react to hover by using different drawable resources
9108     * to change its appearance.
9109     * </p><p>
9110     * The {@link #onHoverChanged} method is called when the hovered state changes.
9111     * </p>
9112     *
9113     * @param hovered True if the view is hovered.
9114     *
9115     * @see #isHovered
9116     * @see #onHoverChanged
9117     */
9118    public void setHovered(boolean hovered) {
9119        if (hovered) {
9120            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
9121                mPrivateFlags |= PFLAG_HOVERED;
9122                refreshDrawableState();
9123                onHoverChanged(true);
9124            }
9125        } else {
9126            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
9127                mPrivateFlags &= ~PFLAG_HOVERED;
9128                refreshDrawableState();
9129                onHoverChanged(false);
9130            }
9131        }
9132    }
9133
9134    /**
9135     * Implement this method to handle hover state changes.
9136     * <p>
9137     * This method is called whenever the hover state changes as a result of a
9138     * call to {@link #setHovered}.
9139     * </p>
9140     *
9141     * @param hovered The current hover state, as returned by {@link #isHovered}.
9142     *
9143     * @see #isHovered
9144     * @see #setHovered
9145     */
9146    public void onHoverChanged(boolean hovered) {
9147    }
9148
9149    /**
9150     * Implement this method to handle touch screen motion events.
9151     * <p>
9152     * If this method is used to detect click actions, it is recommended that
9153     * the actions be performed by implementing and calling
9154     * {@link #performClick()}. This will ensure consistent system behavior,
9155     * including:
9156     * <ul>
9157     * <li>obeying click sound preferences
9158     * <li>dispatching OnClickListener calls
9159     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
9160     * accessibility features are enabled
9161     * </ul>
9162     *
9163     * @param event The motion event.
9164     * @return True if the event was handled, false otherwise.
9165     */
9166    public boolean onTouchEvent(MotionEvent event) {
9167        final float x = event.getX();
9168        final float y = event.getY();
9169        final int viewFlags = mViewFlags;
9170
9171        if ((viewFlags & ENABLED_MASK) == DISABLED) {
9172            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
9173                setPressed(false);
9174            }
9175            // A disabled view that is clickable still consumes the touch
9176            // events, it just doesn't respond to them.
9177            return (((viewFlags & CLICKABLE) == CLICKABLE ||
9178                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
9179        }
9180
9181        if (mTouchDelegate != null) {
9182            if (mTouchDelegate.onTouchEvent(event)) {
9183                return true;
9184            }
9185        }
9186
9187        if (((viewFlags & CLICKABLE) == CLICKABLE ||
9188                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
9189            switch (event.getAction()) {
9190                case MotionEvent.ACTION_UP:
9191                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
9192                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
9193                        // take focus if we don't have it already and we should in
9194                        // touch mode.
9195                        boolean focusTaken = false;
9196                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
9197                            focusTaken = requestFocus();
9198                        }
9199
9200                        if (prepressed) {
9201                            // The button is being released before we actually
9202                            // showed it as pressed.  Make it show the pressed
9203                            // state now (before scheduling the click) to ensure
9204                            // the user sees it.
9205                            setPressed(true, x, y);
9206                       }
9207
9208                        if (!mHasPerformedLongPress) {
9209                            // This is a tap, so remove the longpress check
9210                            removeLongPressCallback();
9211
9212                            // Only perform take click actions if we were in the pressed state
9213                            if (!focusTaken) {
9214                                // Use a Runnable and post this rather than calling
9215                                // performClick directly. This lets other visual state
9216                                // of the view update before click actions start.
9217                                if (mPerformClick == null) {
9218                                    mPerformClick = new PerformClick();
9219                                }
9220                                if (!post(mPerformClick)) {
9221                                    performClick();
9222                                }
9223                            }
9224                        }
9225
9226                        if (mUnsetPressedState == null) {
9227                            mUnsetPressedState = new UnsetPressedState();
9228                        }
9229
9230                        if (prepressed) {
9231                            postDelayed(mUnsetPressedState,
9232                                    ViewConfiguration.getPressedStateDuration());
9233                        } else if (!post(mUnsetPressedState)) {
9234                            // If the post failed, unpress right now
9235                            mUnsetPressedState.run();
9236                        }
9237
9238                        removeTapCallback();
9239                    }
9240                    break;
9241
9242                case MotionEvent.ACTION_DOWN:
9243                    mHasPerformedLongPress = false;
9244
9245                    if (performButtonActionOnTouchDown(event)) {
9246                        break;
9247                    }
9248
9249                    // Walk up the hierarchy to determine if we're inside a scrolling container.
9250                    boolean isInScrollingContainer = isInScrollingContainer();
9251
9252                    // For views inside a scrolling container, delay the pressed feedback for
9253                    // a short period in case this is a scroll.
9254                    if (isInScrollingContainer) {
9255                        mPrivateFlags |= PFLAG_PREPRESSED;
9256                        if (mPendingCheckForTap == null) {
9257                            mPendingCheckForTap = new CheckForTap();
9258                        }
9259                        mPendingCheckForTap.x = event.getX();
9260                        mPendingCheckForTap.y = event.getY();
9261                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
9262                    } else {
9263                        // Not inside a scrolling container, so show the feedback right away
9264                        setPressed(true, x, y);
9265                        checkForLongClick(0);
9266                    }
9267                    break;
9268
9269                case MotionEvent.ACTION_CANCEL:
9270                    setPressed(false);
9271                    removeTapCallback();
9272                    removeLongPressCallback();
9273                    break;
9274
9275                case MotionEvent.ACTION_MOVE:
9276                    drawableHotspotChanged(x, y);
9277
9278                    // Be lenient about moving outside of buttons
9279                    if (!pointInView(x, y, mTouchSlop)) {
9280                        // Outside button
9281                        removeTapCallback();
9282                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
9283                            // Remove any future long press/tap checks
9284                            removeLongPressCallback();
9285
9286                            setPressed(false);
9287                        }
9288                    }
9289                    break;
9290            }
9291
9292            return true;
9293        }
9294
9295        return false;
9296    }
9297
9298    /**
9299     * @hide
9300     */
9301    public boolean isInScrollingContainer() {
9302        ViewParent p = getParent();
9303        while (p != null && p instanceof ViewGroup) {
9304            if (((ViewGroup) p).shouldDelayChildPressedState()) {
9305                return true;
9306            }
9307            p = p.getParent();
9308        }
9309        return false;
9310    }
9311
9312    /**
9313     * Remove the longpress detection timer.
9314     */
9315    private void removeLongPressCallback() {
9316        if (mPendingCheckForLongPress != null) {
9317          removeCallbacks(mPendingCheckForLongPress);
9318        }
9319    }
9320
9321    /**
9322     * Remove the pending click action
9323     */
9324    private void removePerformClickCallback() {
9325        if (mPerformClick != null) {
9326            removeCallbacks(mPerformClick);
9327        }
9328    }
9329
9330    /**
9331     * Remove the prepress detection timer.
9332     */
9333    private void removeUnsetPressCallback() {
9334        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
9335            setPressed(false);
9336            removeCallbacks(mUnsetPressedState);
9337        }
9338    }
9339
9340    /**
9341     * Remove the tap detection timer.
9342     */
9343    private void removeTapCallback() {
9344        if (mPendingCheckForTap != null) {
9345            mPrivateFlags &= ~PFLAG_PREPRESSED;
9346            removeCallbacks(mPendingCheckForTap);
9347        }
9348    }
9349
9350    /**
9351     * Cancels a pending long press.  Your subclass can use this if you
9352     * want the context menu to come up if the user presses and holds
9353     * at the same place, but you don't want it to come up if they press
9354     * and then move around enough to cause scrolling.
9355     */
9356    public void cancelLongPress() {
9357        removeLongPressCallback();
9358
9359        /*
9360         * The prepressed state handled by the tap callback is a display
9361         * construct, but the tap callback will post a long press callback
9362         * less its own timeout. Remove it here.
9363         */
9364        removeTapCallback();
9365    }
9366
9367    /**
9368     * Remove the pending callback for sending a
9369     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
9370     */
9371    private void removeSendViewScrolledAccessibilityEventCallback() {
9372        if (mSendViewScrolledAccessibilityEvent != null) {
9373            removeCallbacks(mSendViewScrolledAccessibilityEvent);
9374            mSendViewScrolledAccessibilityEvent.mIsPending = false;
9375        }
9376    }
9377
9378    /**
9379     * Sets the TouchDelegate for this View.
9380     */
9381    public void setTouchDelegate(TouchDelegate delegate) {
9382        mTouchDelegate = delegate;
9383    }
9384
9385    /**
9386     * Gets the TouchDelegate for this View.
9387     */
9388    public TouchDelegate getTouchDelegate() {
9389        return mTouchDelegate;
9390    }
9391
9392    /**
9393     * Request unbuffered dispatch of the given stream of MotionEvents to this View.
9394     *
9395     * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input
9396     * system not batch {@link MotionEvent}s but instead deliver them as soon as they're
9397     * available. This method should only be called for touch events.
9398     *
9399     * <p class="note">This api is not intended for most applications. Buffered dispatch
9400     * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent
9401     * streams will not improve your input latency. Side effects include: increased latency,
9402     * jittery scrolls and inability to take advantage of system resampling. Talk to your input
9403     * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for
9404     * you.</p>
9405     */
9406    public final void requestUnbufferedDispatch(MotionEvent event) {
9407        final int action = event.getAction();
9408        if (mAttachInfo == null
9409                || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE
9410                || !event.isTouchEvent()) {
9411            return;
9412        }
9413        mAttachInfo.mUnbufferedDispatchRequested = true;
9414    }
9415
9416    /**
9417     * Set flags controlling behavior of this view.
9418     *
9419     * @param flags Constant indicating the value which should be set
9420     * @param mask Constant indicating the bit range that should be changed
9421     */
9422    void setFlags(int flags, int mask) {
9423        final boolean accessibilityEnabled =
9424                AccessibilityManager.getInstance(mContext).isEnabled();
9425        final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility();
9426
9427        int old = mViewFlags;
9428        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
9429
9430        int changed = mViewFlags ^ old;
9431        if (changed == 0) {
9432            return;
9433        }
9434        int privateFlags = mPrivateFlags;
9435
9436        /* Check if the FOCUSABLE bit has changed */
9437        if (((changed & FOCUSABLE_MASK) != 0) &&
9438                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
9439            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
9440                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
9441                /* Give up focus if we are no longer focusable */
9442                clearFocus();
9443            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
9444                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
9445                /*
9446                 * Tell the view system that we are now available to take focus
9447                 * if no one else already has it.
9448                 */
9449                if (mParent != null) mParent.focusableViewAvailable(this);
9450            }
9451        }
9452
9453        final int newVisibility = flags & VISIBILITY_MASK;
9454        if (newVisibility == VISIBLE) {
9455            if ((changed & VISIBILITY_MASK) != 0) {
9456                /*
9457                 * If this view is becoming visible, invalidate it in case it changed while
9458                 * it was not visible. Marking it drawn ensures that the invalidation will
9459                 * go through.
9460                 */
9461                mPrivateFlags |= PFLAG_DRAWN;
9462                invalidate(true);
9463
9464                needGlobalAttributesUpdate(true);
9465
9466                // a view becoming visible is worth notifying the parent
9467                // about in case nothing has focus.  even if this specific view
9468                // isn't focusable, it may contain something that is, so let
9469                // the root view try to give this focus if nothing else does.
9470                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
9471                    mParent.focusableViewAvailable(this);
9472                }
9473            }
9474        }
9475
9476        /* Check if the GONE bit has changed */
9477        if ((changed & GONE) != 0) {
9478            needGlobalAttributesUpdate(false);
9479            requestLayout();
9480
9481            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
9482                if (hasFocus()) clearFocus();
9483                clearAccessibilityFocus();
9484                destroyDrawingCache();
9485                if (mParent instanceof View) {
9486                    // GONE views noop invalidation, so invalidate the parent
9487                    ((View) mParent).invalidate(true);
9488                }
9489                // Mark the view drawn to ensure that it gets invalidated properly the next
9490                // time it is visible and gets invalidated
9491                mPrivateFlags |= PFLAG_DRAWN;
9492            }
9493            if (mAttachInfo != null) {
9494                mAttachInfo.mViewVisibilityChanged = true;
9495            }
9496        }
9497
9498        /* Check if the VISIBLE bit has changed */
9499        if ((changed & INVISIBLE) != 0) {
9500            needGlobalAttributesUpdate(false);
9501            /*
9502             * If this view is becoming invisible, set the DRAWN flag so that
9503             * the next invalidate() will not be skipped.
9504             */
9505            mPrivateFlags |= PFLAG_DRAWN;
9506
9507            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
9508                // root view becoming invisible shouldn't clear focus and accessibility focus
9509                if (getRootView() != this) {
9510                    if (hasFocus()) clearFocus();
9511                    clearAccessibilityFocus();
9512                }
9513            }
9514            if (mAttachInfo != null) {
9515                mAttachInfo.mViewVisibilityChanged = true;
9516            }
9517        }
9518
9519        if ((changed & VISIBILITY_MASK) != 0) {
9520            // If the view is invisible, cleanup its display list to free up resources
9521            if (newVisibility != VISIBLE && mAttachInfo != null) {
9522                cleanupDraw();
9523            }
9524
9525            if (mParent instanceof ViewGroup) {
9526                ((ViewGroup) mParent).onChildVisibilityChanged(this,
9527                        (changed & VISIBILITY_MASK), newVisibility);
9528                ((View) mParent).invalidate(true);
9529            } else if (mParent != null) {
9530                mParent.invalidateChild(this, null);
9531            }
9532            dispatchVisibilityChanged(this, newVisibility);
9533
9534            notifySubtreeAccessibilityStateChangedIfNeeded();
9535        }
9536
9537        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
9538            destroyDrawingCache();
9539        }
9540
9541        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
9542            destroyDrawingCache();
9543            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9544            invalidateParentCaches();
9545        }
9546
9547        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
9548            destroyDrawingCache();
9549            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
9550        }
9551
9552        if ((changed & DRAW_MASK) != 0) {
9553            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
9554                if (mBackground != null) {
9555                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9556                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
9557                } else {
9558                    mPrivateFlags |= PFLAG_SKIP_DRAW;
9559                }
9560            } else {
9561                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
9562            }
9563            requestLayout();
9564            invalidate(true);
9565        }
9566
9567        if ((changed & KEEP_SCREEN_ON) != 0) {
9568            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
9569                mParent.recomputeViewAttributes(this);
9570            }
9571        }
9572
9573        if (accessibilityEnabled) {
9574            if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
9575                    || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
9576                if (oldIncludeForAccessibility != includeForAccessibility()) {
9577                    notifySubtreeAccessibilityStateChangedIfNeeded();
9578                } else {
9579                    notifyViewAccessibilityStateChangedIfNeeded(
9580                            AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9581                }
9582            } else if ((changed & ENABLED_MASK) != 0) {
9583                notifyViewAccessibilityStateChangedIfNeeded(
9584                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
9585            }
9586        }
9587    }
9588
9589    /**
9590     * Change the view's z order in the tree, so it's on top of other sibling
9591     * views. This ordering change may affect layout, if the parent container
9592     * uses an order-dependent layout scheme (e.g., LinearLayout). Prior
9593     * to {@link android.os.Build.VERSION_CODES#KITKAT} this
9594     * method should be followed by calls to {@link #requestLayout()} and
9595     * {@link View#invalidate()} on the view's parent to force the parent to redraw
9596     * with the new child ordering.
9597     *
9598     * @see ViewGroup#bringChildToFront(View)
9599     */
9600    public void bringToFront() {
9601        if (mParent != null) {
9602            mParent.bringChildToFront(this);
9603        }
9604    }
9605
9606    /**
9607     * This is called in response to an internal scroll in this view (i.e., the
9608     * view scrolled its own contents). This is typically as a result of
9609     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
9610     * called.
9611     *
9612     * @param l Current horizontal scroll origin.
9613     * @param t Current vertical scroll origin.
9614     * @param oldl Previous horizontal scroll origin.
9615     * @param oldt Previous vertical scroll origin.
9616     */
9617    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
9618        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
9619            postSendViewScrolledAccessibilityEventCallback();
9620        }
9621
9622        mBackgroundSizeChanged = true;
9623
9624        final AttachInfo ai = mAttachInfo;
9625        if (ai != null) {
9626            ai.mViewScrollChanged = true;
9627        }
9628    }
9629
9630    /**
9631     * Interface definition for a callback to be invoked when the layout bounds of a view
9632     * changes due to layout processing.
9633     */
9634    public interface OnLayoutChangeListener {
9635        /**
9636         * Called when the layout bounds of a view changes due to layout processing.
9637         *
9638         * @param v The view whose bounds have changed.
9639         * @param left The new value of the view's left property.
9640         * @param top The new value of the view's top property.
9641         * @param right The new value of the view's right property.
9642         * @param bottom The new value of the view's bottom property.
9643         * @param oldLeft The previous value of the view's left property.
9644         * @param oldTop The previous value of the view's top property.
9645         * @param oldRight The previous value of the view's right property.
9646         * @param oldBottom The previous value of the view's bottom property.
9647         */
9648        void onLayoutChange(View v, int left, int top, int right, int bottom,
9649            int oldLeft, int oldTop, int oldRight, int oldBottom);
9650    }
9651
9652    /**
9653     * This is called during layout when the size of this view has changed. If
9654     * you were just added to the view hierarchy, you're called with the old
9655     * values of 0.
9656     *
9657     * @param w Current width of this view.
9658     * @param h Current height of this view.
9659     * @param oldw Old width of this view.
9660     * @param oldh Old height of this view.
9661     */
9662    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
9663    }
9664
9665    /**
9666     * Called by draw to draw the child views. This may be overridden
9667     * by derived classes to gain control just before its children are drawn
9668     * (but after its own view has been drawn).
9669     * @param canvas the canvas on which to draw the view
9670     */
9671    protected void dispatchDraw(Canvas canvas) {
9672
9673    }
9674
9675    /**
9676     * Gets the parent of this view. Note that the parent is a
9677     * ViewParent and not necessarily a View.
9678     *
9679     * @return Parent of this view.
9680     */
9681    public final ViewParent getParent() {
9682        return mParent;
9683    }
9684
9685    /**
9686     * Set the horizontal scrolled position of your view. This will cause a call to
9687     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9688     * invalidated.
9689     * @param value the x position to scroll to
9690     */
9691    public void setScrollX(int value) {
9692        scrollTo(value, mScrollY);
9693    }
9694
9695    /**
9696     * Set the vertical scrolled position of your view. This will cause a call to
9697     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9698     * invalidated.
9699     * @param value the y position to scroll to
9700     */
9701    public void setScrollY(int value) {
9702        scrollTo(mScrollX, value);
9703    }
9704
9705    /**
9706     * Return the scrolled left position of this view. This is the left edge of
9707     * the displayed part of your view. You do not need to draw any pixels
9708     * farther left, since those are outside of the frame of your view on
9709     * screen.
9710     *
9711     * @return The left edge of the displayed part of your view, in pixels.
9712     */
9713    public final int getScrollX() {
9714        return mScrollX;
9715    }
9716
9717    /**
9718     * Return the scrolled top position of this view. This is the top edge of
9719     * the displayed part of your view. You do not need to draw any pixels above
9720     * it, since those are outside of the frame of your view on screen.
9721     *
9722     * @return The top edge of the displayed part of your view, in pixels.
9723     */
9724    public final int getScrollY() {
9725        return mScrollY;
9726    }
9727
9728    /**
9729     * Return the width of the your view.
9730     *
9731     * @return The width of your view, in pixels.
9732     */
9733    @ViewDebug.ExportedProperty(category = "layout")
9734    public final int getWidth() {
9735        return mRight - mLeft;
9736    }
9737
9738    /**
9739     * Return the height of your view.
9740     *
9741     * @return The height of your view, in pixels.
9742     */
9743    @ViewDebug.ExportedProperty(category = "layout")
9744    public final int getHeight() {
9745        return mBottom - mTop;
9746    }
9747
9748    /**
9749     * Return the visible drawing bounds of your view. Fills in the output
9750     * rectangle with the values from getScrollX(), getScrollY(),
9751     * getWidth(), and getHeight(). These bounds do not account for any
9752     * transformation properties currently set on the view, such as
9753     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
9754     *
9755     * @param outRect The (scrolled) drawing bounds of the view.
9756     */
9757    public void getDrawingRect(Rect outRect) {
9758        outRect.left = mScrollX;
9759        outRect.top = mScrollY;
9760        outRect.right = mScrollX + (mRight - mLeft);
9761        outRect.bottom = mScrollY + (mBottom - mTop);
9762    }
9763
9764    /**
9765     * Like {@link #getMeasuredWidthAndState()}, but only returns the
9766     * raw width component (that is the result is masked by
9767     * {@link #MEASURED_SIZE_MASK}).
9768     *
9769     * @return The raw measured width of this view.
9770     */
9771    public final int getMeasuredWidth() {
9772        return mMeasuredWidth & MEASURED_SIZE_MASK;
9773    }
9774
9775    /**
9776     * Return the full width measurement information for this view as computed
9777     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9778     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9779     * This should be used during measurement and layout calculations only. Use
9780     * {@link #getWidth()} to see how wide a view is after layout.
9781     *
9782     * @return The measured width of this view as a bit mask.
9783     */
9784    public final int getMeasuredWidthAndState() {
9785        return mMeasuredWidth;
9786    }
9787
9788    /**
9789     * Like {@link #getMeasuredHeightAndState()}, but only returns the
9790     * raw width component (that is the result is masked by
9791     * {@link #MEASURED_SIZE_MASK}).
9792     *
9793     * @return The raw measured height of this view.
9794     */
9795    public final int getMeasuredHeight() {
9796        return mMeasuredHeight & MEASURED_SIZE_MASK;
9797    }
9798
9799    /**
9800     * Return the full height measurement information for this view as computed
9801     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
9802     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
9803     * This should be used during measurement and layout calculations only. Use
9804     * {@link #getHeight()} to see how wide a view is after layout.
9805     *
9806     * @return The measured width of this view as a bit mask.
9807     */
9808    public final int getMeasuredHeightAndState() {
9809        return mMeasuredHeight;
9810    }
9811
9812    /**
9813     * Return only the state bits of {@link #getMeasuredWidthAndState()}
9814     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
9815     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
9816     * and the height component is at the shifted bits
9817     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
9818     */
9819    public final int getMeasuredState() {
9820        return (mMeasuredWidth&MEASURED_STATE_MASK)
9821                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
9822                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
9823    }
9824
9825    /**
9826     * The transform matrix of this view, which is calculated based on the current
9827     * rotation, scale, and pivot properties.
9828     *
9829     * @see #getRotation()
9830     * @see #getScaleX()
9831     * @see #getScaleY()
9832     * @see #getPivotX()
9833     * @see #getPivotY()
9834     * @return The current transform matrix for the view
9835     */
9836    public Matrix getMatrix() {
9837        ensureTransformationInfo();
9838        final Matrix matrix = mTransformationInfo.mMatrix;
9839        mRenderNode.getMatrix(matrix);
9840        return matrix;
9841    }
9842
9843    /**
9844     * Returns true if the transform matrix is the identity matrix.
9845     * Recomputes the matrix if necessary.
9846     *
9847     * @return True if the transform matrix is the identity matrix, false otherwise.
9848     */
9849    final boolean hasIdentityMatrix() {
9850        return mRenderNode.hasIdentityMatrix();
9851    }
9852
9853    void ensureTransformationInfo() {
9854        if (mTransformationInfo == null) {
9855            mTransformationInfo = new TransformationInfo();
9856        }
9857    }
9858
9859   /**
9860     * Utility method to retrieve the inverse of the current mMatrix property.
9861     * We cache the matrix to avoid recalculating it when transform properties
9862     * have not changed.
9863     *
9864     * @return The inverse of the current matrix of this view.
9865     * @hide
9866     */
9867    public final Matrix getInverseMatrix() {
9868        ensureTransformationInfo();
9869        if (mTransformationInfo.mInverseMatrix == null) {
9870            mTransformationInfo.mInverseMatrix = new Matrix();
9871        }
9872        final Matrix matrix = mTransformationInfo.mInverseMatrix;
9873        mRenderNode.getInverseMatrix(matrix);
9874        return matrix;
9875    }
9876
9877    /**
9878     * Gets the distance along the Z axis from the camera to this view.
9879     *
9880     * @see #setCameraDistance(float)
9881     *
9882     * @return The distance along the Z axis.
9883     */
9884    public float getCameraDistance() {
9885        final float dpi = mResources.getDisplayMetrics().densityDpi;
9886        return -(mRenderNode.getCameraDistance() * dpi);
9887    }
9888
9889    /**
9890     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9891     * views are drawn) from the camera to this view. The camera's distance
9892     * affects 3D transformations, for instance rotations around the X and Y
9893     * axis. If the rotationX or rotationY properties are changed and this view is
9894     * large (more than half the size of the screen), it is recommended to always
9895     * use a camera distance that's greater than the height (X axis rotation) or
9896     * the width (Y axis rotation) of this view.</p>
9897     *
9898     * <p>The distance of the camera from the view plane can have an affect on the
9899     * perspective distortion of the view when it is rotated around the x or y axis.
9900     * For example, a large distance will result in a large viewing angle, and there
9901     * will not be much perspective distortion of the view as it rotates. A short
9902     * distance may cause much more perspective distortion upon rotation, and can
9903     * also result in some drawing artifacts if the rotated view ends up partially
9904     * behind the camera (which is why the recommendation is to use a distance at
9905     * least as far as the size of the view, if the view is to be rotated.)</p>
9906     *
9907     * <p>The distance is expressed in "depth pixels." The default distance depends
9908     * on the screen density. For instance, on a medium density display, the
9909     * default distance is 1280. On a high density display, the default distance
9910     * is 1920.</p>
9911     *
9912     * <p>If you want to specify a distance that leads to visually consistent
9913     * results across various densities, use the following formula:</p>
9914     * <pre>
9915     * float scale = context.getResources().getDisplayMetrics().density;
9916     * view.setCameraDistance(distance * scale);
9917     * </pre>
9918     *
9919     * <p>The density scale factor of a high density display is 1.5,
9920     * and 1920 = 1280 * 1.5.</p>
9921     *
9922     * @param distance The distance in "depth pixels", if negative the opposite
9923     *        value is used
9924     *
9925     * @see #setRotationX(float)
9926     * @see #setRotationY(float)
9927     */
9928    public void setCameraDistance(float distance) {
9929        final float dpi = mResources.getDisplayMetrics().densityDpi;
9930
9931        invalidateViewProperty(true, false);
9932        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
9933        invalidateViewProperty(false, false);
9934
9935        invalidateParentIfNeededAndWasQuickRejected();
9936    }
9937
9938    /**
9939     * The degrees that the view is rotated around the pivot point.
9940     *
9941     * @see #setRotation(float)
9942     * @see #getPivotX()
9943     * @see #getPivotY()
9944     *
9945     * @return The degrees of rotation.
9946     */
9947    @ViewDebug.ExportedProperty(category = "drawing")
9948    public float getRotation() {
9949        return mRenderNode.getRotation();
9950    }
9951
9952    /**
9953     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9954     * result in clockwise rotation.
9955     *
9956     * @param rotation The degrees of rotation.
9957     *
9958     * @see #getRotation()
9959     * @see #getPivotX()
9960     * @see #getPivotY()
9961     * @see #setRotationX(float)
9962     * @see #setRotationY(float)
9963     *
9964     * @attr ref android.R.styleable#View_rotation
9965     */
9966    public void setRotation(float rotation) {
9967        if (rotation != getRotation()) {
9968            // Double-invalidation is necessary to capture view's old and new areas
9969            invalidateViewProperty(true, false);
9970            mRenderNode.setRotation(rotation);
9971            invalidateViewProperty(false, true);
9972
9973            invalidateParentIfNeededAndWasQuickRejected();
9974            notifySubtreeAccessibilityStateChangedIfNeeded();
9975        }
9976    }
9977
9978    /**
9979     * The degrees that the view is rotated around the vertical axis through the pivot point.
9980     *
9981     * @see #getPivotX()
9982     * @see #getPivotY()
9983     * @see #setRotationY(float)
9984     *
9985     * @return The degrees of Y rotation.
9986     */
9987    @ViewDebug.ExportedProperty(category = "drawing")
9988    public float getRotationY() {
9989        return mRenderNode.getRotationY();
9990    }
9991
9992    /**
9993     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9994     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9995     * down the y axis.
9996     *
9997     * When rotating large views, it is recommended to adjust the camera distance
9998     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9999     *
10000     * @param rotationY The degrees of Y rotation.
10001     *
10002     * @see #getRotationY()
10003     * @see #getPivotX()
10004     * @see #getPivotY()
10005     * @see #setRotation(float)
10006     * @see #setRotationX(float)
10007     * @see #setCameraDistance(float)
10008     *
10009     * @attr ref android.R.styleable#View_rotationY
10010     */
10011    public void setRotationY(float rotationY) {
10012        if (rotationY != getRotationY()) {
10013            invalidateViewProperty(true, false);
10014            mRenderNode.setRotationY(rotationY);
10015            invalidateViewProperty(false, true);
10016
10017            invalidateParentIfNeededAndWasQuickRejected();
10018            notifySubtreeAccessibilityStateChangedIfNeeded();
10019        }
10020    }
10021
10022    /**
10023     * The degrees that the view is rotated around the horizontal axis through the pivot point.
10024     *
10025     * @see #getPivotX()
10026     * @see #getPivotY()
10027     * @see #setRotationX(float)
10028     *
10029     * @return The degrees of X rotation.
10030     */
10031    @ViewDebug.ExportedProperty(category = "drawing")
10032    public float getRotationX() {
10033        return mRenderNode.getRotationX();
10034    }
10035
10036    /**
10037     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
10038     * Increasing values result in clockwise rotation from the viewpoint of looking down the
10039     * x axis.
10040     *
10041     * When rotating large views, it is recommended to adjust the camera distance
10042     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
10043     *
10044     * @param rotationX The degrees of X rotation.
10045     *
10046     * @see #getRotationX()
10047     * @see #getPivotX()
10048     * @see #getPivotY()
10049     * @see #setRotation(float)
10050     * @see #setRotationY(float)
10051     * @see #setCameraDistance(float)
10052     *
10053     * @attr ref android.R.styleable#View_rotationX
10054     */
10055    public void setRotationX(float rotationX) {
10056        if (rotationX != getRotationX()) {
10057            invalidateViewProperty(true, false);
10058            mRenderNode.setRotationX(rotationX);
10059            invalidateViewProperty(false, true);
10060
10061            invalidateParentIfNeededAndWasQuickRejected();
10062            notifySubtreeAccessibilityStateChangedIfNeeded();
10063        }
10064    }
10065
10066    /**
10067     * The amount that the view is scaled in x around the pivot point, as a proportion of
10068     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
10069     *
10070     * <p>By default, this is 1.0f.
10071     *
10072     * @see #getPivotX()
10073     * @see #getPivotY()
10074     * @return The scaling factor.
10075     */
10076    @ViewDebug.ExportedProperty(category = "drawing")
10077    public float getScaleX() {
10078        return mRenderNode.getScaleX();
10079    }
10080
10081    /**
10082     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
10083     * the view's unscaled width. A value of 1 means that no scaling is applied.
10084     *
10085     * @param scaleX The scaling factor.
10086     * @see #getPivotX()
10087     * @see #getPivotY()
10088     *
10089     * @attr ref android.R.styleable#View_scaleX
10090     */
10091    public void setScaleX(float scaleX) {
10092        if (scaleX != getScaleX()) {
10093            invalidateViewProperty(true, false);
10094            mRenderNode.setScaleX(scaleX);
10095            invalidateViewProperty(false, true);
10096
10097            invalidateParentIfNeededAndWasQuickRejected();
10098            notifySubtreeAccessibilityStateChangedIfNeeded();
10099        }
10100    }
10101
10102    /**
10103     * The amount that the view is scaled in y around the pivot point, as a proportion of
10104     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
10105     *
10106     * <p>By default, this is 1.0f.
10107     *
10108     * @see #getPivotX()
10109     * @see #getPivotY()
10110     * @return The scaling factor.
10111     */
10112    @ViewDebug.ExportedProperty(category = "drawing")
10113    public float getScaleY() {
10114        return mRenderNode.getScaleY();
10115    }
10116
10117    /**
10118     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
10119     * the view's unscaled width. A value of 1 means that no scaling is applied.
10120     *
10121     * @param scaleY The scaling factor.
10122     * @see #getPivotX()
10123     * @see #getPivotY()
10124     *
10125     * @attr ref android.R.styleable#View_scaleY
10126     */
10127    public void setScaleY(float scaleY) {
10128        if (scaleY != getScaleY()) {
10129            invalidateViewProperty(true, false);
10130            mRenderNode.setScaleY(scaleY);
10131            invalidateViewProperty(false, true);
10132
10133            invalidateParentIfNeededAndWasQuickRejected();
10134            notifySubtreeAccessibilityStateChangedIfNeeded();
10135        }
10136    }
10137
10138    /**
10139     * The x location of the point around which the view is {@link #setRotation(float) rotated}
10140     * and {@link #setScaleX(float) scaled}.
10141     *
10142     * @see #getRotation()
10143     * @see #getScaleX()
10144     * @see #getScaleY()
10145     * @see #getPivotY()
10146     * @return The x location of the pivot point.
10147     *
10148     * @attr ref android.R.styleable#View_transformPivotX
10149     */
10150    @ViewDebug.ExportedProperty(category = "drawing")
10151    public float getPivotX() {
10152        return mRenderNode.getPivotX();
10153    }
10154
10155    /**
10156     * Sets the x location of the point around which the view is
10157     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
10158     * By default, the pivot point is centered on the object.
10159     * Setting this property disables this behavior and causes the view to use only the
10160     * explicitly set pivotX and pivotY values.
10161     *
10162     * @param pivotX The x location of the pivot point.
10163     * @see #getRotation()
10164     * @see #getScaleX()
10165     * @see #getScaleY()
10166     * @see #getPivotY()
10167     *
10168     * @attr ref android.R.styleable#View_transformPivotX
10169     */
10170    public void setPivotX(float pivotX) {
10171        if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) {
10172            invalidateViewProperty(true, false);
10173            mRenderNode.setPivotX(pivotX);
10174            invalidateViewProperty(false, true);
10175
10176            invalidateParentIfNeededAndWasQuickRejected();
10177        }
10178    }
10179
10180    /**
10181     * The y location of the point around which the view is {@link #setRotation(float) rotated}
10182     * and {@link #setScaleY(float) scaled}.
10183     *
10184     * @see #getRotation()
10185     * @see #getScaleX()
10186     * @see #getScaleY()
10187     * @see #getPivotY()
10188     * @return The y location of the pivot point.
10189     *
10190     * @attr ref android.R.styleable#View_transformPivotY
10191     */
10192    @ViewDebug.ExportedProperty(category = "drawing")
10193    public float getPivotY() {
10194        return mRenderNode.getPivotY();
10195    }
10196
10197    /**
10198     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
10199     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
10200     * Setting this property disables this behavior and causes the view to use only the
10201     * explicitly set pivotX and pivotY values.
10202     *
10203     * @param pivotY The y location of the pivot point.
10204     * @see #getRotation()
10205     * @see #getScaleX()
10206     * @see #getScaleY()
10207     * @see #getPivotY()
10208     *
10209     * @attr ref android.R.styleable#View_transformPivotY
10210     */
10211    public void setPivotY(float pivotY) {
10212        if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) {
10213            invalidateViewProperty(true, false);
10214            mRenderNode.setPivotY(pivotY);
10215            invalidateViewProperty(false, true);
10216
10217            invalidateParentIfNeededAndWasQuickRejected();
10218        }
10219    }
10220
10221    /**
10222     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
10223     * completely transparent and 1 means the view is completely opaque.
10224     *
10225     * <p>By default this is 1.0f.
10226     * @return The opacity of the view.
10227     */
10228    @ViewDebug.ExportedProperty(category = "drawing")
10229    public float getAlpha() {
10230        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
10231    }
10232
10233    /**
10234     * Returns whether this View has content which overlaps.
10235     *
10236     * <p>This function, intended to be overridden by specific View types, is an optimization when
10237     * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to
10238     * an offscreen buffer and then composited into place, which can be expensive. If the view has
10239     * no overlapping rendering, the view can draw each primitive with the appropriate alpha value
10240     * directly. An example of overlapping rendering is a TextView with a background image, such as
10241     * a Button. An example of non-overlapping rendering is a TextView with no background, or an
10242     * ImageView with only the foreground image. The default implementation returns true; subclasses
10243     * should override if they have cases which can be optimized.</p>
10244     *
10245     * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas}
10246     * necessitates that a View return true if it uses the methods internally without passing the
10247     * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p>
10248     *
10249     * @return true if the content in this view might overlap, false otherwise.
10250     */
10251    public boolean hasOverlappingRendering() {
10252        return true;
10253    }
10254
10255    /**
10256     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
10257     * completely transparent and 1 means the view is completely opaque.</p>
10258     *
10259     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
10260     * performance implications, especially for large views. It is best to use the alpha property
10261     * sparingly and transiently, as in the case of fading animations.</p>
10262     *
10263     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
10264     * strongly recommended for performance reasons to either override
10265     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
10266     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
10267     *
10268     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
10269     * responsible for applying the opacity itself.</p>
10270     *
10271     * <p>Note that if the view is backed by a
10272     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
10273     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
10274     * 1.0 will supercede the alpha of the layer paint.</p>
10275     *
10276     * @param alpha The opacity of the view.
10277     *
10278     * @see #hasOverlappingRendering()
10279     * @see #setLayerType(int, android.graphics.Paint)
10280     *
10281     * @attr ref android.R.styleable#View_alpha
10282     */
10283    public void setAlpha(float alpha) {
10284        ensureTransformationInfo();
10285        if (mTransformationInfo.mAlpha != alpha) {
10286            mTransformationInfo.mAlpha = alpha;
10287            if (onSetAlpha((int) (alpha * 255))) {
10288                mPrivateFlags |= PFLAG_ALPHA_SET;
10289                // subclass is handling alpha - don't optimize rendering cache invalidation
10290                invalidateParentCaches();
10291                invalidate(true);
10292            } else {
10293                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10294                invalidateViewProperty(true, false);
10295                mRenderNode.setAlpha(getFinalAlpha());
10296                notifyViewAccessibilityStateChangedIfNeeded(
10297                        AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
10298            }
10299        }
10300    }
10301
10302    /**
10303     * Faster version of setAlpha() which performs the same steps except there are
10304     * no calls to invalidate(). The caller of this function should perform proper invalidation
10305     * on the parent and this object. The return value indicates whether the subclass handles
10306     * alpha (the return value for onSetAlpha()).
10307     *
10308     * @param alpha The new value for the alpha property
10309     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
10310     *         the new value for the alpha property is different from the old value
10311     */
10312    boolean setAlphaNoInvalidation(float alpha) {
10313        ensureTransformationInfo();
10314        if (mTransformationInfo.mAlpha != alpha) {
10315            mTransformationInfo.mAlpha = alpha;
10316            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
10317            if (subclassHandlesAlpha) {
10318                mPrivateFlags |= PFLAG_ALPHA_SET;
10319                return true;
10320            } else {
10321                mPrivateFlags &= ~PFLAG_ALPHA_SET;
10322                mRenderNode.setAlpha(getFinalAlpha());
10323            }
10324        }
10325        return false;
10326    }
10327
10328    /**
10329     * This property is hidden and intended only for use by the Fade transition, which
10330     * animates it to produce a visual translucency that does not side-effect (or get
10331     * affected by) the real alpha property. This value is composited with the other
10332     * alpha value (and the AlphaAnimation value, when that is present) to produce
10333     * a final visual translucency result, which is what is passed into the DisplayList.
10334     *
10335     * @hide
10336     */
10337    public void setTransitionAlpha(float alpha) {
10338        ensureTransformationInfo();
10339        if (mTransformationInfo.mTransitionAlpha != alpha) {
10340            mTransformationInfo.mTransitionAlpha = alpha;
10341            mPrivateFlags &= ~PFLAG_ALPHA_SET;
10342            invalidateViewProperty(true, false);
10343            mRenderNode.setAlpha(getFinalAlpha());
10344        }
10345    }
10346
10347    /**
10348     * Calculates the visual alpha of this view, which is a combination of the actual
10349     * alpha value and the transitionAlpha value (if set).
10350     */
10351    private float getFinalAlpha() {
10352        if (mTransformationInfo != null) {
10353            return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
10354        }
10355        return 1;
10356    }
10357
10358    /**
10359     * This property is hidden and intended only for use by the Fade transition, which
10360     * animates it to produce a visual translucency that does not side-effect (or get
10361     * affected by) the real alpha property. This value is composited with the other
10362     * alpha value (and the AlphaAnimation value, when that is present) to produce
10363     * a final visual translucency result, which is what is passed into the DisplayList.
10364     *
10365     * @hide
10366     */
10367    @ViewDebug.ExportedProperty(category = "drawing")
10368    public float getTransitionAlpha() {
10369        return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1;
10370    }
10371
10372    /**
10373     * Top position of this view relative to its parent.
10374     *
10375     * @return The top of this view, in pixels.
10376     */
10377    @ViewDebug.CapturedViewProperty
10378    public final int getTop() {
10379        return mTop;
10380    }
10381
10382    /**
10383     * Sets the top position of this view relative to its parent. This method is meant to be called
10384     * by the layout system and should not generally be called otherwise, because the property
10385     * may be changed at any time by the layout.
10386     *
10387     * @param top The top of this view, in pixels.
10388     */
10389    public final void setTop(int top) {
10390        if (top != mTop) {
10391            final boolean matrixIsIdentity = hasIdentityMatrix();
10392            if (matrixIsIdentity) {
10393                if (mAttachInfo != null) {
10394                    int minTop;
10395                    int yLoc;
10396                    if (top < mTop) {
10397                        minTop = top;
10398                        yLoc = top - mTop;
10399                    } else {
10400                        minTop = mTop;
10401                        yLoc = 0;
10402                    }
10403                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
10404                }
10405            } else {
10406                // Double-invalidation is necessary to capture view's old and new areas
10407                invalidate(true);
10408            }
10409
10410            int width = mRight - mLeft;
10411            int oldHeight = mBottom - mTop;
10412
10413            mTop = top;
10414            mRenderNode.setTop(mTop);
10415
10416            sizeChange(width, mBottom - mTop, width, oldHeight);
10417
10418            if (!matrixIsIdentity) {
10419                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10420                invalidate(true);
10421            }
10422            mBackgroundSizeChanged = true;
10423            invalidateParentIfNeeded();
10424            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10425                // View was rejected last time it was drawn by its parent; this may have changed
10426                invalidateParentIfNeeded();
10427            }
10428        }
10429    }
10430
10431    /**
10432     * Bottom position of this view relative to its parent.
10433     *
10434     * @return The bottom of this view, in pixels.
10435     */
10436    @ViewDebug.CapturedViewProperty
10437    public final int getBottom() {
10438        return mBottom;
10439    }
10440
10441    /**
10442     * True if this view has changed since the last time being drawn.
10443     *
10444     * @return The dirty state of this view.
10445     */
10446    public boolean isDirty() {
10447        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
10448    }
10449
10450    /**
10451     * Sets the bottom position of this view relative to its parent. This method is meant to be
10452     * called by the layout system and should not generally be called otherwise, because the
10453     * property may be changed at any time by the layout.
10454     *
10455     * @param bottom The bottom of this view, in pixels.
10456     */
10457    public final void setBottom(int bottom) {
10458        if (bottom != mBottom) {
10459            final boolean matrixIsIdentity = hasIdentityMatrix();
10460            if (matrixIsIdentity) {
10461                if (mAttachInfo != null) {
10462                    int maxBottom;
10463                    if (bottom < mBottom) {
10464                        maxBottom = mBottom;
10465                    } else {
10466                        maxBottom = bottom;
10467                    }
10468                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
10469                }
10470            } else {
10471                // Double-invalidation is necessary to capture view's old and new areas
10472                invalidate(true);
10473            }
10474
10475            int width = mRight - mLeft;
10476            int oldHeight = mBottom - mTop;
10477
10478            mBottom = bottom;
10479            mRenderNode.setBottom(mBottom);
10480
10481            sizeChange(width, mBottom - mTop, width, oldHeight);
10482
10483            if (!matrixIsIdentity) {
10484                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10485                invalidate(true);
10486            }
10487            mBackgroundSizeChanged = true;
10488            invalidateParentIfNeeded();
10489            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10490                // View was rejected last time it was drawn by its parent; this may have changed
10491                invalidateParentIfNeeded();
10492            }
10493        }
10494    }
10495
10496    /**
10497     * Left position of this view relative to its parent.
10498     *
10499     * @return The left edge of this view, in pixels.
10500     */
10501    @ViewDebug.CapturedViewProperty
10502    public final int getLeft() {
10503        return mLeft;
10504    }
10505
10506    /**
10507     * Sets the left position of this view relative to its parent. This method is meant to be called
10508     * by the layout system and should not generally be called otherwise, because the property
10509     * may be changed at any time by the layout.
10510     *
10511     * @param left The left of this view, in pixels.
10512     */
10513    public final void setLeft(int left) {
10514        if (left != mLeft) {
10515            final boolean matrixIsIdentity = hasIdentityMatrix();
10516            if (matrixIsIdentity) {
10517                if (mAttachInfo != null) {
10518                    int minLeft;
10519                    int xLoc;
10520                    if (left < mLeft) {
10521                        minLeft = left;
10522                        xLoc = left - mLeft;
10523                    } else {
10524                        minLeft = mLeft;
10525                        xLoc = 0;
10526                    }
10527                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
10528                }
10529            } else {
10530                // Double-invalidation is necessary to capture view's old and new areas
10531                invalidate(true);
10532            }
10533
10534            int oldWidth = mRight - mLeft;
10535            int height = mBottom - mTop;
10536
10537            mLeft = left;
10538            mRenderNode.setLeft(left);
10539
10540            sizeChange(mRight - mLeft, height, oldWidth, height);
10541
10542            if (!matrixIsIdentity) {
10543                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10544                invalidate(true);
10545            }
10546            mBackgroundSizeChanged = true;
10547            invalidateParentIfNeeded();
10548            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10549                // View was rejected last time it was drawn by its parent; this may have changed
10550                invalidateParentIfNeeded();
10551            }
10552        }
10553    }
10554
10555    /**
10556     * Right position of this view relative to its parent.
10557     *
10558     * @return The right edge of this view, in pixels.
10559     */
10560    @ViewDebug.CapturedViewProperty
10561    public final int getRight() {
10562        return mRight;
10563    }
10564
10565    /**
10566     * Sets the right position of this view relative to its parent. This method is meant to be called
10567     * by the layout system and should not generally be called otherwise, because the property
10568     * may be changed at any time by the layout.
10569     *
10570     * @param right The right of this view, in pixels.
10571     */
10572    public final void setRight(int right) {
10573        if (right != mRight) {
10574            final boolean matrixIsIdentity = hasIdentityMatrix();
10575            if (matrixIsIdentity) {
10576                if (mAttachInfo != null) {
10577                    int maxRight;
10578                    if (right < mRight) {
10579                        maxRight = mRight;
10580                    } else {
10581                        maxRight = right;
10582                    }
10583                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
10584                }
10585            } else {
10586                // Double-invalidation is necessary to capture view's old and new areas
10587                invalidate(true);
10588            }
10589
10590            int oldWidth = mRight - mLeft;
10591            int height = mBottom - mTop;
10592
10593            mRight = right;
10594            mRenderNode.setRight(mRight);
10595
10596            sizeChange(mRight - mLeft, height, oldWidth, height);
10597
10598            if (!matrixIsIdentity) {
10599                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10600                invalidate(true);
10601            }
10602            mBackgroundSizeChanged = true;
10603            invalidateParentIfNeeded();
10604            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
10605                // View was rejected last time it was drawn by its parent; this may have changed
10606                invalidateParentIfNeeded();
10607            }
10608        }
10609    }
10610
10611    /**
10612     * The visual x position of this view, in pixels. This is equivalent to the
10613     * {@link #setTranslationX(float) translationX} property plus the current
10614     * {@link #getLeft() left} property.
10615     *
10616     * @return The visual x position of this view, in pixels.
10617     */
10618    @ViewDebug.ExportedProperty(category = "drawing")
10619    public float getX() {
10620        return mLeft + getTranslationX();
10621    }
10622
10623    /**
10624     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
10625     * {@link #setTranslationX(float) translationX} property to be the difference between
10626     * the x value passed in and the current {@link #getLeft() left} property.
10627     *
10628     * @param x The visual x position of this view, in pixels.
10629     */
10630    public void setX(float x) {
10631        setTranslationX(x - mLeft);
10632    }
10633
10634    /**
10635     * The visual y position of this view, in pixels. This is equivalent to the
10636     * {@link #setTranslationY(float) translationY} property plus the current
10637     * {@link #getTop() top} property.
10638     *
10639     * @return The visual y position of this view, in pixels.
10640     */
10641    @ViewDebug.ExportedProperty(category = "drawing")
10642    public float getY() {
10643        return mTop + getTranslationY();
10644    }
10645
10646    /**
10647     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
10648     * {@link #setTranslationY(float) translationY} property to be the difference between
10649     * the y value passed in and the current {@link #getTop() top} property.
10650     *
10651     * @param y The visual y position of this view, in pixels.
10652     */
10653    public void setY(float y) {
10654        setTranslationY(y - mTop);
10655    }
10656
10657    /**
10658     * The visual z position of this view, in pixels. This is equivalent to the
10659     * {@link #setTranslationZ(float) translationZ} property plus the current
10660     * {@link #getElevation() elevation} property.
10661     *
10662     * @return The visual z position of this view, in pixels.
10663     */
10664    @ViewDebug.ExportedProperty(category = "drawing")
10665    public float getZ() {
10666        return getElevation() + getTranslationZ();
10667    }
10668
10669    /**
10670     * Sets the visual z position of this view, in pixels. This is equivalent to setting the
10671     * {@link #setTranslationZ(float) translationZ} property to be the difference between
10672     * the x value passed in and the current {@link #getElevation() elevation} property.
10673     *
10674     * @param z The visual z position of this view, in pixels.
10675     */
10676    public void setZ(float z) {
10677        setTranslationZ(z - getElevation());
10678    }
10679
10680    /**
10681     * The base elevation of this view relative to its parent, in pixels.
10682     *
10683     * @return The base depth position of the view, in pixels.
10684     */
10685    @ViewDebug.ExportedProperty(category = "drawing")
10686    public float getElevation() {
10687        return mRenderNode.getElevation();
10688    }
10689
10690    /**
10691     * Sets the base elevation of this view, in pixels.
10692     *
10693     * @attr ref android.R.styleable#View_elevation
10694     */
10695    public void setElevation(float elevation) {
10696        if (elevation != getElevation()) {
10697            invalidateViewProperty(true, false);
10698            mRenderNode.setElevation(elevation);
10699            invalidateViewProperty(false, true);
10700
10701            invalidateParentIfNeededAndWasQuickRejected();
10702        }
10703    }
10704
10705    /**
10706     * The horizontal location of this view relative to its {@link #getLeft() left} position.
10707     * This position is post-layout, in addition to wherever the object's
10708     * layout placed it.
10709     *
10710     * @return The horizontal position of this view relative to its left position, in pixels.
10711     */
10712    @ViewDebug.ExportedProperty(category = "drawing")
10713    public float getTranslationX() {
10714        return mRenderNode.getTranslationX();
10715    }
10716
10717    /**
10718     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
10719     * This effectively positions the object post-layout, in addition to wherever the object's
10720     * layout placed it.
10721     *
10722     * @param translationX The horizontal position of this view relative to its left position,
10723     * in pixels.
10724     *
10725     * @attr ref android.R.styleable#View_translationX
10726     */
10727    public void setTranslationX(float translationX) {
10728        if (translationX != getTranslationX()) {
10729            invalidateViewProperty(true, false);
10730            mRenderNode.setTranslationX(translationX);
10731            invalidateViewProperty(false, true);
10732
10733            invalidateParentIfNeededAndWasQuickRejected();
10734            notifySubtreeAccessibilityStateChangedIfNeeded();
10735        }
10736    }
10737
10738    /**
10739     * The vertical location of this view relative to its {@link #getTop() top} position.
10740     * This position is post-layout, in addition to wherever the object's
10741     * layout placed it.
10742     *
10743     * @return The vertical position of this view relative to its top position,
10744     * in pixels.
10745     */
10746    @ViewDebug.ExportedProperty(category = "drawing")
10747    public float getTranslationY() {
10748        return mRenderNode.getTranslationY();
10749    }
10750
10751    /**
10752     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
10753     * This effectively positions the object post-layout, in addition to wherever the object's
10754     * layout placed it.
10755     *
10756     * @param translationY The vertical position of this view relative to its top position,
10757     * in pixels.
10758     *
10759     * @attr ref android.R.styleable#View_translationY
10760     */
10761    public void setTranslationY(float translationY) {
10762        if (translationY != getTranslationY()) {
10763            invalidateViewProperty(true, false);
10764            mRenderNode.setTranslationY(translationY);
10765            invalidateViewProperty(false, true);
10766
10767            invalidateParentIfNeededAndWasQuickRejected();
10768        }
10769    }
10770
10771    /**
10772     * The depth location of this view relative to its {@link #getElevation() elevation}.
10773     *
10774     * @return The depth of this view relative to its elevation.
10775     */
10776    @ViewDebug.ExportedProperty(category = "drawing")
10777    public float getTranslationZ() {
10778        return mRenderNode.getTranslationZ();
10779    }
10780
10781    /**
10782     * Sets the depth location of this view relative to its {@link #getElevation() elevation}.
10783     *
10784     * @attr ref android.R.styleable#View_translationZ
10785     */
10786    public void setTranslationZ(float translationZ) {
10787        if (translationZ != getTranslationZ()) {
10788            invalidateViewProperty(true, false);
10789            mRenderNode.setTranslationZ(translationZ);
10790            invalidateViewProperty(false, true);
10791
10792            invalidateParentIfNeededAndWasQuickRejected();
10793        }
10794    }
10795
10796    /** @hide */
10797    public void setAnimationMatrix(Matrix matrix) {
10798        invalidateViewProperty(true, false);
10799        mRenderNode.setAnimationMatrix(matrix);
10800        invalidateViewProperty(false, true);
10801
10802        invalidateParentIfNeededAndWasQuickRejected();
10803    }
10804
10805    /**
10806     * Returns the current StateListAnimator if exists.
10807     *
10808     * @return StateListAnimator or null if it does not exists
10809     * @see    #setStateListAnimator(android.animation.StateListAnimator)
10810     */
10811    public StateListAnimator getStateListAnimator() {
10812        return mStateListAnimator;
10813    }
10814
10815    /**
10816     * Attaches the provided StateListAnimator to this View.
10817     * <p>
10818     * Any previously attached StateListAnimator will be detached.
10819     *
10820     * @param stateListAnimator The StateListAnimator to update the view
10821     * @see {@link android.animation.StateListAnimator}
10822     */
10823    public void setStateListAnimator(StateListAnimator stateListAnimator) {
10824        if (mStateListAnimator == stateListAnimator) {
10825            return;
10826        }
10827        if (mStateListAnimator != null) {
10828            mStateListAnimator.setTarget(null);
10829        }
10830        mStateListAnimator = stateListAnimator;
10831        if (stateListAnimator != null) {
10832            stateListAnimator.setTarget(this);
10833            if (isAttachedToWindow()) {
10834                stateListAnimator.setState(getDrawableState());
10835            }
10836        }
10837    }
10838
10839    /**
10840     * Returns whether the Outline should be used to clip the contents of the View.
10841     * <p>
10842     * Note that this flag will only be respected if the View's Outline returns true from
10843     * {@link Outline#canClip()}.
10844     *
10845     * @see #setOutlineProvider(ViewOutlineProvider)
10846     * @see #setClipToOutline(boolean)
10847     */
10848    public final boolean getClipToOutline() {
10849        return mRenderNode.getClipToOutline();
10850    }
10851
10852    /**
10853     * Sets whether the View's Outline should be used to clip the contents of the View.
10854     * <p>
10855     * Note that this flag will only be respected if the View's Outline returns true from
10856     * {@link Outline#canClip()}.
10857     *
10858     * @see #setOutlineProvider(ViewOutlineProvider)
10859     * @see #getClipToOutline()
10860     */
10861    public void setClipToOutline(boolean clipToOutline) {
10862        damageInParent();
10863        if (getClipToOutline() != clipToOutline) {
10864            mRenderNode.setClipToOutline(clipToOutline);
10865        }
10866    }
10867
10868    // correspond to the enum values of View_outlineProvider
10869    private static final int PROVIDER_BACKGROUND = 0;
10870    private static final int PROVIDER_NONE = 1;
10871    private static final int PROVIDER_BOUNDS = 2;
10872    private static final int PROVIDER_PADDED_BOUNDS = 3;
10873    private void setOutlineProviderFromAttribute(int providerInt) {
10874        switch (providerInt) {
10875            case PROVIDER_BACKGROUND:
10876                setOutlineProvider(ViewOutlineProvider.BACKGROUND);
10877                break;
10878            case PROVIDER_NONE:
10879                setOutlineProvider(null);
10880                break;
10881            case PROVIDER_BOUNDS:
10882                setOutlineProvider(ViewOutlineProvider.BOUNDS);
10883                break;
10884            case PROVIDER_PADDED_BOUNDS:
10885                setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS);
10886                break;
10887        }
10888    }
10889
10890    /**
10891     * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
10892     * the shape of the shadow it casts, and enables outline clipping.
10893     * <p>
10894     * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
10895     * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
10896     * outline provider with this method allows this behavior to be overridden.
10897     * <p>
10898     * If the ViewOutlineProvider is null, if querying it for an outline returns false,
10899     * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
10900     * <p>
10901     * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
10902     *
10903     * @see #setClipToOutline(boolean)
10904     * @see #getClipToOutline()
10905     * @see #getOutlineProvider()
10906     */
10907    public void setOutlineProvider(ViewOutlineProvider provider) {
10908        mOutlineProvider = provider;
10909        invalidateOutline();
10910    }
10911
10912    /**
10913     * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline
10914     * that defines the shape of the shadow it casts, and enables outline clipping.
10915     *
10916     * @see #setOutlineProvider(ViewOutlineProvider)
10917     */
10918    public ViewOutlineProvider getOutlineProvider() {
10919        return mOutlineProvider;
10920    }
10921
10922    /**
10923     * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
10924     *
10925     * @see #setOutlineProvider(ViewOutlineProvider)
10926     */
10927    public void invalidateOutline() {
10928        // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
10929        if (mAttachInfo == null) return;
10930
10931        if (mOutlineProvider == null) {
10932            // no provider, remove outline
10933            mRenderNode.setOutline(null);
10934        } else {
10935            final Outline outline = mAttachInfo.mTmpOutline;
10936            outline.setEmpty();
10937            outline.setAlpha(1.0f);
10938
10939            mOutlineProvider.getOutline(this, outline);
10940            mRenderNode.setOutline(outline);
10941        }
10942
10943        notifySubtreeAccessibilityStateChangedIfNeeded();
10944        invalidateViewProperty(false, false);
10945    }
10946
10947    /** @hide */
10948    public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
10949        mRenderNode.setRevealClip(shouldClip, x, y, radius);
10950        invalidateViewProperty(false, false);
10951    }
10952
10953    /**
10954     * Hit rectangle in parent's coordinates
10955     *
10956     * @param outRect The hit rectangle of the view.
10957     */
10958    public void getHitRect(Rect outRect) {
10959        if (hasIdentityMatrix() || mAttachInfo == null) {
10960            outRect.set(mLeft, mTop, mRight, mBottom);
10961        } else {
10962            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
10963            tmpRect.set(0, 0, getWidth(), getHeight());
10964            getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect)
10965            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
10966                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
10967        }
10968    }
10969
10970    /**
10971     * Determines whether the given point, in local coordinates is inside the view.
10972     */
10973    /*package*/ final boolean pointInView(float localX, float localY) {
10974        return localX >= 0 && localX < (mRight - mLeft)
10975                && localY >= 0 && localY < (mBottom - mTop);
10976    }
10977
10978    /**
10979     * Utility method to determine whether the given point, in local coordinates,
10980     * is inside the view, where the area of the view is expanded by the slop factor.
10981     * This method is called while processing touch-move events to determine if the event
10982     * is still within the view.
10983     *
10984     * @hide
10985     */
10986    public boolean pointInView(float localX, float localY, float slop) {
10987        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
10988                localY < ((mBottom - mTop) + slop);
10989    }
10990
10991    /**
10992     * When a view has focus and the user navigates away from it, the next view is searched for
10993     * starting from the rectangle filled in by this method.
10994     *
10995     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10996     * of the view.  However, if your view maintains some idea of internal selection,
10997     * such as a cursor, or a selected row or column, you should override this method and
10998     * fill in a more specific rectangle.
10999     *
11000     * @param r The rectangle to fill in, in this view's coordinates.
11001     */
11002    public void getFocusedRect(Rect r) {
11003        getDrawingRect(r);
11004    }
11005
11006    /**
11007     * If some part of this view is not clipped by any of its parents, then
11008     * return that area in r in global (root) coordinates. To convert r to local
11009     * coordinates (without taking possible View rotations into account), offset
11010     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
11011     * If the view is completely clipped or translated out, return false.
11012     *
11013     * @param r If true is returned, r holds the global coordinates of the
11014     *        visible portion of this view.
11015     * @param globalOffset If true is returned, globalOffset holds the dx,dy
11016     *        between this view and its root. globalOffet may be null.
11017     * @return true if r is non-empty (i.e. part of the view is visible at the
11018     *         root level.
11019     */
11020    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
11021        int width = mRight - mLeft;
11022        int height = mBottom - mTop;
11023        if (width > 0 && height > 0) {
11024            r.set(0, 0, width, height);
11025            if (globalOffset != null) {
11026                globalOffset.set(-mScrollX, -mScrollY);
11027            }
11028            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
11029        }
11030        return false;
11031    }
11032
11033    public final boolean getGlobalVisibleRect(Rect r) {
11034        return getGlobalVisibleRect(r, null);
11035    }
11036
11037    public final boolean getLocalVisibleRect(Rect r) {
11038        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
11039        if (getGlobalVisibleRect(r, offset)) {
11040            r.offset(-offset.x, -offset.y); // make r local
11041            return true;
11042        }
11043        return false;
11044    }
11045
11046    /**
11047     * Offset this view's vertical location by the specified number of pixels.
11048     *
11049     * @param offset the number of pixels to offset the view by
11050     */
11051    public void offsetTopAndBottom(int offset) {
11052        if (offset != 0) {
11053            final boolean matrixIsIdentity = hasIdentityMatrix();
11054            if (matrixIsIdentity) {
11055                if (isHardwareAccelerated()) {
11056                    invalidateViewProperty(false, false);
11057                } else {
11058                    final ViewParent p = mParent;
11059                    if (p != null && mAttachInfo != null) {
11060                        final Rect r = mAttachInfo.mTmpInvalRect;
11061                        int minTop;
11062                        int maxBottom;
11063                        int yLoc;
11064                        if (offset < 0) {
11065                            minTop = mTop + offset;
11066                            maxBottom = mBottom;
11067                            yLoc = offset;
11068                        } else {
11069                            minTop = mTop;
11070                            maxBottom = mBottom + offset;
11071                            yLoc = 0;
11072                        }
11073                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
11074                        p.invalidateChild(this, r);
11075                    }
11076                }
11077            } else {
11078                invalidateViewProperty(false, false);
11079            }
11080
11081            mTop += offset;
11082            mBottom += offset;
11083            mRenderNode.offsetTopAndBottom(offset);
11084            if (isHardwareAccelerated()) {
11085                invalidateViewProperty(false, false);
11086            } else {
11087                if (!matrixIsIdentity) {
11088                    invalidateViewProperty(false, true);
11089                }
11090                invalidateParentIfNeeded();
11091            }
11092            notifySubtreeAccessibilityStateChangedIfNeeded();
11093        }
11094    }
11095
11096    /**
11097     * Offset this view's horizontal location by the specified amount of pixels.
11098     *
11099     * @param offset the number of pixels to offset the view by
11100     */
11101    public void offsetLeftAndRight(int offset) {
11102        if (offset != 0) {
11103            final boolean matrixIsIdentity = hasIdentityMatrix();
11104            if (matrixIsIdentity) {
11105                if (isHardwareAccelerated()) {
11106                    invalidateViewProperty(false, false);
11107                } else {
11108                    final ViewParent p = mParent;
11109                    if (p != null && mAttachInfo != null) {
11110                        final Rect r = mAttachInfo.mTmpInvalRect;
11111                        int minLeft;
11112                        int maxRight;
11113                        if (offset < 0) {
11114                            minLeft = mLeft + offset;
11115                            maxRight = mRight;
11116                        } else {
11117                            minLeft = mLeft;
11118                            maxRight = mRight + offset;
11119                        }
11120                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
11121                        p.invalidateChild(this, r);
11122                    }
11123                }
11124            } else {
11125                invalidateViewProperty(false, false);
11126            }
11127
11128            mLeft += offset;
11129            mRight += offset;
11130            mRenderNode.offsetLeftAndRight(offset);
11131            if (isHardwareAccelerated()) {
11132                invalidateViewProperty(false, false);
11133            } else {
11134                if (!matrixIsIdentity) {
11135                    invalidateViewProperty(false, true);
11136                }
11137                invalidateParentIfNeeded();
11138            }
11139            notifySubtreeAccessibilityStateChangedIfNeeded();
11140        }
11141    }
11142
11143    /**
11144     * Get the LayoutParams associated with this view. All views should have
11145     * layout parameters. These supply parameters to the <i>parent</i> of this
11146     * view specifying how it should be arranged. There are many subclasses of
11147     * ViewGroup.LayoutParams, and these correspond to the different subclasses
11148     * of ViewGroup that are responsible for arranging their children.
11149     *
11150     * This method may return null if this View is not attached to a parent
11151     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
11152     * was not invoked successfully. When a View is attached to a parent
11153     * ViewGroup, this method must not return null.
11154     *
11155     * @return The LayoutParams associated with this view, or null if no
11156     *         parameters have been set yet
11157     */
11158    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
11159    public ViewGroup.LayoutParams getLayoutParams() {
11160        return mLayoutParams;
11161    }
11162
11163    /**
11164     * Set the layout parameters associated with this view. These supply
11165     * parameters to the <i>parent</i> of this view specifying how it should be
11166     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
11167     * correspond to the different subclasses of ViewGroup that are responsible
11168     * for arranging their children.
11169     *
11170     * @param params The layout parameters for this view, cannot be null
11171     */
11172    public void setLayoutParams(ViewGroup.LayoutParams params) {
11173        if (params == null) {
11174            throw new NullPointerException("Layout parameters cannot be null");
11175        }
11176        mLayoutParams = params;
11177        resolveLayoutParams();
11178        if (mParent instanceof ViewGroup) {
11179            ((ViewGroup) mParent).onSetLayoutParams(this, params);
11180        }
11181        requestLayout();
11182    }
11183
11184    /**
11185     * Resolve the layout parameters depending on the resolved layout direction
11186     *
11187     * @hide
11188     */
11189    public void resolveLayoutParams() {
11190        if (mLayoutParams != null) {
11191            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
11192        }
11193    }
11194
11195    /**
11196     * Set the scrolled position of your view. This will cause a call to
11197     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11198     * invalidated.
11199     * @param x the x position to scroll to
11200     * @param y the y position to scroll to
11201     */
11202    public void scrollTo(int x, int y) {
11203        if (mScrollX != x || mScrollY != y) {
11204            int oldX = mScrollX;
11205            int oldY = mScrollY;
11206            mScrollX = x;
11207            mScrollY = y;
11208            invalidateParentCaches();
11209            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
11210            if (!awakenScrollBars()) {
11211                postInvalidateOnAnimation();
11212            }
11213        }
11214    }
11215
11216    /**
11217     * Move the scrolled position of your view. This will cause a call to
11218     * {@link #onScrollChanged(int, int, int, int)} and the view will be
11219     * invalidated.
11220     * @param x the amount of pixels to scroll by horizontally
11221     * @param y the amount of pixels to scroll by vertically
11222     */
11223    public void scrollBy(int x, int y) {
11224        scrollTo(mScrollX + x, mScrollY + y);
11225    }
11226
11227    /**
11228     * <p>Trigger the scrollbars to draw. When invoked this method starts an
11229     * animation to fade the scrollbars out after a default delay. If a subclass
11230     * provides animated scrolling, the start delay should equal the duration
11231     * of the scrolling animation.</p>
11232     *
11233     * <p>The animation starts only if at least one of the scrollbars is
11234     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
11235     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11236     * this method returns true, and false otherwise. If the animation is
11237     * started, this method calls {@link #invalidate()}; in that case the
11238     * caller should not call {@link #invalidate()}.</p>
11239     *
11240     * <p>This method should be invoked every time a subclass directly updates
11241     * the scroll parameters.</p>
11242     *
11243     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
11244     * and {@link #scrollTo(int, int)}.</p>
11245     *
11246     * @return true if the animation is played, false otherwise
11247     *
11248     * @see #awakenScrollBars(int)
11249     * @see #scrollBy(int, int)
11250     * @see #scrollTo(int, int)
11251     * @see #isHorizontalScrollBarEnabled()
11252     * @see #isVerticalScrollBarEnabled()
11253     * @see #setHorizontalScrollBarEnabled(boolean)
11254     * @see #setVerticalScrollBarEnabled(boolean)
11255     */
11256    protected boolean awakenScrollBars() {
11257        return mScrollCache != null &&
11258                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
11259    }
11260
11261    /**
11262     * Trigger the scrollbars to draw.
11263     * This method differs from awakenScrollBars() only in its default duration.
11264     * initialAwakenScrollBars() will show the scroll bars for longer than
11265     * usual to give the user more of a chance to notice them.
11266     *
11267     * @return true if the animation is played, false otherwise.
11268     */
11269    private boolean initialAwakenScrollBars() {
11270        return mScrollCache != null &&
11271                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
11272    }
11273
11274    /**
11275     * <p>
11276     * Trigger the scrollbars to draw. When invoked this method starts an
11277     * animation to fade the scrollbars out after a fixed delay. If a subclass
11278     * provides animated scrolling, the start delay should equal the duration of
11279     * the scrolling animation.
11280     * </p>
11281     *
11282     * <p>
11283     * The animation starts only if at least one of the scrollbars is enabled,
11284     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11285     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11286     * this method returns true, and false otherwise. If the animation is
11287     * started, this method calls {@link #invalidate()}; in that case the caller
11288     * should not call {@link #invalidate()}.
11289     * </p>
11290     *
11291     * <p>
11292     * This method should be invoked everytime a subclass directly updates the
11293     * scroll parameters.
11294     * </p>
11295     *
11296     * @param startDelay the delay, in milliseconds, after which the animation
11297     *        should start; when the delay is 0, the animation starts
11298     *        immediately
11299     * @return true if the animation is played, false otherwise
11300     *
11301     * @see #scrollBy(int, int)
11302     * @see #scrollTo(int, int)
11303     * @see #isHorizontalScrollBarEnabled()
11304     * @see #isVerticalScrollBarEnabled()
11305     * @see #setHorizontalScrollBarEnabled(boolean)
11306     * @see #setVerticalScrollBarEnabled(boolean)
11307     */
11308    protected boolean awakenScrollBars(int startDelay) {
11309        return awakenScrollBars(startDelay, true);
11310    }
11311
11312    /**
11313     * <p>
11314     * Trigger the scrollbars to draw. When invoked this method starts an
11315     * animation to fade the scrollbars out after a fixed delay. If a subclass
11316     * provides animated scrolling, the start delay should equal the duration of
11317     * the scrolling animation.
11318     * </p>
11319     *
11320     * <p>
11321     * The animation starts only if at least one of the scrollbars is enabled,
11322     * as specified by {@link #isHorizontalScrollBarEnabled()} and
11323     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
11324     * this method returns true, and false otherwise. If the animation is
11325     * started, this method calls {@link #invalidate()} if the invalidate parameter
11326     * is set to true; in that case the caller
11327     * should not call {@link #invalidate()}.
11328     * </p>
11329     *
11330     * <p>
11331     * This method should be invoked everytime a subclass directly updates the
11332     * scroll parameters.
11333     * </p>
11334     *
11335     * @param startDelay the delay, in milliseconds, after which the animation
11336     *        should start; when the delay is 0, the animation starts
11337     *        immediately
11338     *
11339     * @param invalidate Wheter this method should call invalidate
11340     *
11341     * @return true if the animation is played, false otherwise
11342     *
11343     * @see #scrollBy(int, int)
11344     * @see #scrollTo(int, int)
11345     * @see #isHorizontalScrollBarEnabled()
11346     * @see #isVerticalScrollBarEnabled()
11347     * @see #setHorizontalScrollBarEnabled(boolean)
11348     * @see #setVerticalScrollBarEnabled(boolean)
11349     */
11350    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
11351        final ScrollabilityCache scrollCache = mScrollCache;
11352
11353        if (scrollCache == null || !scrollCache.fadeScrollBars) {
11354            return false;
11355        }
11356
11357        if (scrollCache.scrollBar == null) {
11358            scrollCache.scrollBar = new ScrollBarDrawable();
11359        }
11360
11361        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
11362
11363            if (invalidate) {
11364                // Invalidate to show the scrollbars
11365                postInvalidateOnAnimation();
11366            }
11367
11368            if (scrollCache.state == ScrollabilityCache.OFF) {
11369                // FIXME: this is copied from WindowManagerService.
11370                // We should get this value from the system when it
11371                // is possible to do so.
11372                final int KEY_REPEAT_FIRST_DELAY = 750;
11373                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
11374            }
11375
11376            // Tell mScrollCache when we should start fading. This may
11377            // extend the fade start time if one was already scheduled
11378            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
11379            scrollCache.fadeStartTime = fadeStartTime;
11380            scrollCache.state = ScrollabilityCache.ON;
11381
11382            // Schedule our fader to run, unscheduling any old ones first
11383            if (mAttachInfo != null) {
11384                mAttachInfo.mHandler.removeCallbacks(scrollCache);
11385                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
11386            }
11387
11388            return true;
11389        }
11390
11391        return false;
11392    }
11393
11394    /**
11395     * Do not invalidate views which are not visible and which are not running an animation. They
11396     * will not get drawn and they should not set dirty flags as if they will be drawn
11397     */
11398    private boolean skipInvalidate() {
11399        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
11400                (!(mParent instanceof ViewGroup) ||
11401                        !((ViewGroup) mParent).isViewTransitioning(this));
11402    }
11403
11404    /**
11405     * Mark the area defined by dirty as needing to be drawn. If the view is
11406     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11407     * point in the future.
11408     * <p>
11409     * This must be called from a UI thread. To call from a non-UI thread, call
11410     * {@link #postInvalidate()}.
11411     * <p>
11412     * <b>WARNING:</b> In API 19 and below, this method may be destructive to
11413     * {@code dirty}.
11414     *
11415     * @param dirty the rectangle representing the bounds of the dirty region
11416     */
11417    public void invalidate(Rect dirty) {
11418        final int scrollX = mScrollX;
11419        final int scrollY = mScrollY;
11420        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
11421                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
11422    }
11423
11424    /**
11425     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
11426     * coordinates of the dirty rect are relative to the view. If the view is
11427     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
11428     * point in the future.
11429     * <p>
11430     * This must be called from a UI thread. To call from a non-UI thread, call
11431     * {@link #postInvalidate()}.
11432     *
11433     * @param l the left position of the dirty region
11434     * @param t the top position of the dirty region
11435     * @param r the right position of the dirty region
11436     * @param b the bottom position of the dirty region
11437     */
11438    public void invalidate(int l, int t, int r, int b) {
11439        final int scrollX = mScrollX;
11440        final int scrollY = mScrollY;
11441        invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false);
11442    }
11443
11444    /**
11445     * Invalidate the whole view. If the view is visible,
11446     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
11447     * the future.
11448     * <p>
11449     * This must be called from a UI thread. To call from a non-UI thread, call
11450     * {@link #postInvalidate()}.
11451     */
11452    public void invalidate() {
11453        invalidate(true);
11454    }
11455
11456    /**
11457     * This is where the invalidate() work actually happens. A full invalidate()
11458     * causes the drawing cache to be invalidated, but this function can be
11459     * called with invalidateCache set to false to skip that invalidation step
11460     * for cases that do not need it (for example, a component that remains at
11461     * the same dimensions with the same content).
11462     *
11463     * @param invalidateCache Whether the drawing cache for this view should be
11464     *            invalidated as well. This is usually true for a full
11465     *            invalidate, but may be set to false if the View's contents or
11466     *            dimensions have not changed.
11467     */
11468    void invalidate(boolean invalidateCache) {
11469        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
11470    }
11471
11472    void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
11473            boolean fullInvalidate) {
11474        if (mGhostView != null) {
11475            mGhostView.invalidate(invalidateCache);
11476            return;
11477        }
11478
11479        if (skipInvalidate()) {
11480            return;
11481        }
11482
11483        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
11484                || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
11485                || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
11486                || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
11487            if (fullInvalidate) {
11488                mLastIsOpaque = isOpaque();
11489                mPrivateFlags &= ~PFLAG_DRAWN;
11490            }
11491
11492            mPrivateFlags |= PFLAG_DIRTY;
11493
11494            if (invalidateCache) {
11495                mPrivateFlags |= PFLAG_INVALIDATED;
11496                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
11497            }
11498
11499            // Propagate the damage rectangle to the parent view.
11500            final AttachInfo ai = mAttachInfo;
11501            final ViewParent p = mParent;
11502            if (p != null && ai != null && l < r && t < b) {
11503                final Rect damage = ai.mTmpInvalRect;
11504                damage.set(l, t, r, b);
11505                p.invalidateChild(this, damage);
11506            }
11507
11508            // Damage the entire projection receiver, if necessary.
11509            if (mBackground != null && mBackground.isProjected()) {
11510                final View receiver = getProjectionReceiver();
11511                if (receiver != null) {
11512                    receiver.damageInParent();
11513                }
11514            }
11515
11516            // Damage the entire IsolatedZVolume receiving this view's shadow.
11517            if (isHardwareAccelerated() && getZ() != 0) {
11518                damageShadowReceiver();
11519            }
11520        }
11521    }
11522
11523    /**
11524     * @return this view's projection receiver, or {@code null} if none exists
11525     */
11526    private View getProjectionReceiver() {
11527        ViewParent p = getParent();
11528        while (p != null && p instanceof View) {
11529            final View v = (View) p;
11530            if (v.isProjectionReceiver()) {
11531                return v;
11532            }
11533            p = p.getParent();
11534        }
11535
11536        return null;
11537    }
11538
11539    /**
11540     * @return whether the view is a projection receiver
11541     */
11542    private boolean isProjectionReceiver() {
11543        return mBackground != null;
11544    }
11545
11546    /**
11547     * Damage area of the screen that can be covered by this View's shadow.
11548     *
11549     * This method will guarantee that any changes to shadows cast by a View
11550     * are damaged on the screen for future redraw.
11551     */
11552    private void damageShadowReceiver() {
11553        final AttachInfo ai = mAttachInfo;
11554        if (ai != null) {
11555            ViewParent p = getParent();
11556            if (p != null && p instanceof ViewGroup) {
11557                final ViewGroup vg = (ViewGroup) p;
11558                vg.damageInParent();
11559            }
11560        }
11561    }
11562
11563    /**
11564     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
11565     * set any flags or handle all of the cases handled by the default invalidation methods.
11566     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
11567     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
11568     * walk up the hierarchy, transforming the dirty rect as necessary.
11569     *
11570     * The method also handles normal invalidation logic if display list properties are not
11571     * being used in this view. The invalidateParent and forceRedraw flags are used by that
11572     * backup approach, to handle these cases used in the various property-setting methods.
11573     *
11574     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
11575     * are not being used in this view
11576     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
11577     * list properties are not being used in this view
11578     */
11579    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
11580        if (!isHardwareAccelerated()
11581                || !mRenderNode.isValid()
11582                || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
11583            if (invalidateParent) {
11584                invalidateParentCaches();
11585            }
11586            if (forceRedraw) {
11587                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
11588            }
11589            invalidate(false);
11590        } else {
11591            damageInParent();
11592        }
11593        if (isHardwareAccelerated() && invalidateParent && getZ() != 0) {
11594            damageShadowReceiver();
11595        }
11596    }
11597
11598    /**
11599     * Tells the parent view to damage this view's bounds.
11600     *
11601     * @hide
11602     */
11603    protected void damageInParent() {
11604        final AttachInfo ai = mAttachInfo;
11605        final ViewParent p = mParent;
11606        if (p != null && ai != null) {
11607            final Rect r = ai.mTmpInvalRect;
11608            r.set(0, 0, mRight - mLeft, mBottom - mTop);
11609            if (mParent instanceof ViewGroup) {
11610                ((ViewGroup) mParent).damageChild(this, r);
11611            } else {
11612                mParent.invalidateChild(this, r);
11613            }
11614        }
11615    }
11616
11617    /**
11618     * Utility method to transform a given Rect by the current matrix of this view.
11619     */
11620    void transformRect(final Rect rect) {
11621        if (!getMatrix().isIdentity()) {
11622            RectF boundingRect = mAttachInfo.mTmpTransformRect;
11623            boundingRect.set(rect);
11624            getMatrix().mapRect(boundingRect);
11625            rect.set((int) Math.floor(boundingRect.left),
11626                    (int) Math.floor(boundingRect.top),
11627                    (int) Math.ceil(boundingRect.right),
11628                    (int) Math.ceil(boundingRect.bottom));
11629        }
11630    }
11631
11632    /**
11633     * Used to indicate that the parent of this view should clear its caches. This functionality
11634     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11635     * which is necessary when various parent-managed properties of the view change, such as
11636     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
11637     * clears the parent caches and does not causes an invalidate event.
11638     *
11639     * @hide
11640     */
11641    protected void invalidateParentCaches() {
11642        if (mParent instanceof View) {
11643            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
11644        }
11645    }
11646
11647    /**
11648     * Used to indicate that the parent of this view should be invalidated. This functionality
11649     * is used to force the parent to rebuild its display list (when hardware-accelerated),
11650     * which is necessary when various parent-managed properties of the view change, such as
11651     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
11652     * an invalidation event to the parent.
11653     *
11654     * @hide
11655     */
11656    protected void invalidateParentIfNeeded() {
11657        if (isHardwareAccelerated() && mParent instanceof View) {
11658            ((View) mParent).invalidate(true);
11659        }
11660    }
11661
11662    /**
11663     * @hide
11664     */
11665    protected void invalidateParentIfNeededAndWasQuickRejected() {
11666        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) {
11667            // View was rejected last time it was drawn by its parent; this may have changed
11668            invalidateParentIfNeeded();
11669        }
11670    }
11671
11672    /**
11673     * Indicates whether this View is opaque. An opaque View guarantees that it will
11674     * draw all the pixels overlapping its bounds using a fully opaque color.
11675     *
11676     * Subclasses of View should override this method whenever possible to indicate
11677     * whether an instance is opaque. Opaque Views are treated in a special way by
11678     * the View hierarchy, possibly allowing it to perform optimizations during
11679     * invalidate/draw passes.
11680     *
11681     * @return True if this View is guaranteed to be fully opaque, false otherwise.
11682     */
11683    @ViewDebug.ExportedProperty(category = "drawing")
11684    public boolean isOpaque() {
11685        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
11686                getFinalAlpha() >= 1.0f;
11687    }
11688
11689    /**
11690     * @hide
11691     */
11692    protected void computeOpaqueFlags() {
11693        // Opaque if:
11694        //   - Has a background
11695        //   - Background is opaque
11696        //   - Doesn't have scrollbars or scrollbars overlay
11697
11698        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
11699            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
11700        } else {
11701            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
11702        }
11703
11704        final int flags = mViewFlags;
11705        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
11706                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
11707                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
11708            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
11709        } else {
11710            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
11711        }
11712    }
11713
11714    /**
11715     * @hide
11716     */
11717    protected boolean hasOpaqueScrollbars() {
11718        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
11719    }
11720
11721    /**
11722     * @return A handler associated with the thread running the View. This
11723     * handler can be used to pump events in the UI events queue.
11724     */
11725    public Handler getHandler() {
11726        final AttachInfo attachInfo = mAttachInfo;
11727        if (attachInfo != null) {
11728            return attachInfo.mHandler;
11729        }
11730        return null;
11731    }
11732
11733    /**
11734     * Gets the view root associated with the View.
11735     * @return The view root, or null if none.
11736     * @hide
11737     */
11738    public ViewRootImpl getViewRootImpl() {
11739        if (mAttachInfo != null) {
11740            return mAttachInfo.mViewRootImpl;
11741        }
11742        return null;
11743    }
11744
11745    /**
11746     * @hide
11747     */
11748    public HardwareRenderer getHardwareRenderer() {
11749        return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null;
11750    }
11751
11752    /**
11753     * <p>Causes the Runnable to be added to the message queue.
11754     * The runnable will be run on the user interface thread.</p>
11755     *
11756     * @param action The Runnable that will be executed.
11757     *
11758     * @return Returns true if the Runnable was successfully placed in to the
11759     *         message queue.  Returns false on failure, usually because the
11760     *         looper processing the message queue is exiting.
11761     *
11762     * @see #postDelayed
11763     * @see #removeCallbacks
11764     */
11765    public boolean post(Runnable action) {
11766        final AttachInfo attachInfo = mAttachInfo;
11767        if (attachInfo != null) {
11768            return attachInfo.mHandler.post(action);
11769        }
11770        // Assume that post will succeed later
11771        ViewRootImpl.getRunQueue().post(action);
11772        return true;
11773    }
11774
11775    /**
11776     * <p>Causes the Runnable to be added to the message queue, to be run
11777     * after the specified amount of time elapses.
11778     * The runnable will be run on the user interface thread.</p>
11779     *
11780     * @param action The Runnable that will be executed.
11781     * @param delayMillis The delay (in milliseconds) until the Runnable
11782     *        will be executed.
11783     *
11784     * @return true if the Runnable was successfully placed in to the
11785     *         message queue.  Returns false on failure, usually because the
11786     *         looper processing the message queue is exiting.  Note that a
11787     *         result of true does not mean the Runnable will be processed --
11788     *         if the looper is quit before the delivery time of the message
11789     *         occurs then the message will be dropped.
11790     *
11791     * @see #post
11792     * @see #removeCallbacks
11793     */
11794    public boolean postDelayed(Runnable action, long delayMillis) {
11795        final AttachInfo attachInfo = mAttachInfo;
11796        if (attachInfo != null) {
11797            return attachInfo.mHandler.postDelayed(action, delayMillis);
11798        }
11799        // Assume that post will succeed later
11800        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11801        return true;
11802    }
11803
11804    /**
11805     * <p>Causes the Runnable to execute on the next animation time step.
11806     * The runnable will be run on the user interface thread.</p>
11807     *
11808     * @param action The Runnable that will be executed.
11809     *
11810     * @see #postOnAnimationDelayed
11811     * @see #removeCallbacks
11812     */
11813    public void postOnAnimation(Runnable action) {
11814        final AttachInfo attachInfo = mAttachInfo;
11815        if (attachInfo != null) {
11816            attachInfo.mViewRootImpl.mChoreographer.postCallback(
11817                    Choreographer.CALLBACK_ANIMATION, action, null);
11818        } else {
11819            // Assume that post will succeed later
11820            ViewRootImpl.getRunQueue().post(action);
11821        }
11822    }
11823
11824    /**
11825     * <p>Causes the Runnable to execute on the next animation time step,
11826     * after the specified amount of time elapses.
11827     * The runnable will be run on the user interface thread.</p>
11828     *
11829     * @param action The Runnable that will be executed.
11830     * @param delayMillis The delay (in milliseconds) until the Runnable
11831     *        will be executed.
11832     *
11833     * @see #postOnAnimation
11834     * @see #removeCallbacks
11835     */
11836    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
11837        final AttachInfo attachInfo = mAttachInfo;
11838        if (attachInfo != null) {
11839            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
11840                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
11841        } else {
11842            // Assume that post will succeed later
11843            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
11844        }
11845    }
11846
11847    /**
11848     * <p>Removes the specified Runnable from the message queue.</p>
11849     *
11850     * @param action The Runnable to remove from the message handling queue
11851     *
11852     * @return true if this view could ask the Handler to remove the Runnable,
11853     *         false otherwise. When the returned value is true, the Runnable
11854     *         may or may not have been actually removed from the message queue
11855     *         (for instance, if the Runnable was not in the queue already.)
11856     *
11857     * @see #post
11858     * @see #postDelayed
11859     * @see #postOnAnimation
11860     * @see #postOnAnimationDelayed
11861     */
11862    public boolean removeCallbacks(Runnable action) {
11863        if (action != null) {
11864            final AttachInfo attachInfo = mAttachInfo;
11865            if (attachInfo != null) {
11866                attachInfo.mHandler.removeCallbacks(action);
11867                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
11868                        Choreographer.CALLBACK_ANIMATION, action, null);
11869            }
11870            // Assume that post will succeed later
11871            ViewRootImpl.getRunQueue().removeCallbacks(action);
11872        }
11873        return true;
11874    }
11875
11876    /**
11877     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
11878     * Use this to invalidate the View from a non-UI thread.</p>
11879     *
11880     * <p>This method can be invoked from outside of the UI thread
11881     * only when this View is attached to a window.</p>
11882     *
11883     * @see #invalidate()
11884     * @see #postInvalidateDelayed(long)
11885     */
11886    public void postInvalidate() {
11887        postInvalidateDelayed(0);
11888    }
11889
11890    /**
11891     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11892     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
11893     *
11894     * <p>This method can be invoked from outside of the UI thread
11895     * only when this View is attached to a window.</p>
11896     *
11897     * @param left The left coordinate of the rectangle to invalidate.
11898     * @param top The top coordinate of the rectangle to invalidate.
11899     * @param right The right coordinate of the rectangle to invalidate.
11900     * @param bottom The bottom coordinate of the rectangle to invalidate.
11901     *
11902     * @see #invalidate(int, int, int, int)
11903     * @see #invalidate(Rect)
11904     * @see #postInvalidateDelayed(long, int, int, int, int)
11905     */
11906    public void postInvalidate(int left, int top, int right, int bottom) {
11907        postInvalidateDelayed(0, left, top, right, bottom);
11908    }
11909
11910    /**
11911     * <p>Cause an invalidate to happen on a subsequent cycle through the event
11912     * loop. Waits for the specified amount of time.</p>
11913     *
11914     * <p>This method can be invoked from outside of the UI thread
11915     * only when this View is attached to a window.</p>
11916     *
11917     * @param delayMilliseconds the duration in milliseconds to delay the
11918     *         invalidation by
11919     *
11920     * @see #invalidate()
11921     * @see #postInvalidate()
11922     */
11923    public void postInvalidateDelayed(long delayMilliseconds) {
11924        // We try only with the AttachInfo because there's no point in invalidating
11925        // if we are not attached to our window
11926        final AttachInfo attachInfo = mAttachInfo;
11927        if (attachInfo != null) {
11928            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
11929        }
11930    }
11931
11932    /**
11933     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
11934     * through the event loop. Waits for the specified amount of time.</p>
11935     *
11936     * <p>This method can be invoked from outside of the UI thread
11937     * only when this View is attached to a window.</p>
11938     *
11939     * @param delayMilliseconds the duration in milliseconds to delay the
11940     *         invalidation by
11941     * @param left The left coordinate of the rectangle to invalidate.
11942     * @param top The top coordinate of the rectangle to invalidate.
11943     * @param right The right coordinate of the rectangle to invalidate.
11944     * @param bottom The bottom coordinate of the rectangle to invalidate.
11945     *
11946     * @see #invalidate(int, int, int, int)
11947     * @see #invalidate(Rect)
11948     * @see #postInvalidate(int, int, int, int)
11949     */
11950    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
11951            int right, int bottom) {
11952
11953        // We try only with the AttachInfo because there's no point in invalidating
11954        // if we are not attached to our window
11955        final AttachInfo attachInfo = mAttachInfo;
11956        if (attachInfo != null) {
11957            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
11958            info.target = this;
11959            info.left = left;
11960            info.top = top;
11961            info.right = right;
11962            info.bottom = bottom;
11963
11964            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
11965        }
11966    }
11967
11968    /**
11969     * <p>Cause an invalidate to happen on the next animation time step, typically the
11970     * next display frame.</p>
11971     *
11972     * <p>This method can be invoked from outside of the UI thread
11973     * only when this View is attached to a window.</p>
11974     *
11975     * @see #invalidate()
11976     */
11977    public void postInvalidateOnAnimation() {
11978        // We try only with the AttachInfo because there's no point in invalidating
11979        // if we are not attached to our window
11980        final AttachInfo attachInfo = mAttachInfo;
11981        if (attachInfo != null) {
11982            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
11983        }
11984    }
11985
11986    /**
11987     * <p>Cause an invalidate of the specified area to happen on the next animation
11988     * time step, typically the next display frame.</p>
11989     *
11990     * <p>This method can be invoked from outside of the UI thread
11991     * only when this View is attached to a window.</p>
11992     *
11993     * @param left The left coordinate of the rectangle to invalidate.
11994     * @param top The top coordinate of the rectangle to invalidate.
11995     * @param right The right coordinate of the rectangle to invalidate.
11996     * @param bottom The bottom coordinate of the rectangle to invalidate.
11997     *
11998     * @see #invalidate(int, int, int, int)
11999     * @see #invalidate(Rect)
12000     */
12001    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
12002        // We try only with the AttachInfo because there's no point in invalidating
12003        // if we are not attached to our window
12004        final AttachInfo attachInfo = mAttachInfo;
12005        if (attachInfo != null) {
12006            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
12007            info.target = this;
12008            info.left = left;
12009            info.top = top;
12010            info.right = right;
12011            info.bottom = bottom;
12012
12013            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
12014        }
12015    }
12016
12017    /**
12018     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
12019     * This event is sent at most once every
12020     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
12021     */
12022    private void postSendViewScrolledAccessibilityEventCallback() {
12023        if (mSendViewScrolledAccessibilityEvent == null) {
12024            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
12025        }
12026        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
12027            mSendViewScrolledAccessibilityEvent.mIsPending = true;
12028            postDelayed(mSendViewScrolledAccessibilityEvent,
12029                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
12030        }
12031    }
12032
12033    /**
12034     * Called by a parent to request that a child update its values for mScrollX
12035     * and mScrollY if necessary. This will typically be done if the child is
12036     * animating a scroll using a {@link android.widget.Scroller Scroller}
12037     * object.
12038     */
12039    public void computeScroll() {
12040    }
12041
12042    /**
12043     * <p>Indicate whether the horizontal edges are faded when the view is
12044     * scrolled horizontally.</p>
12045     *
12046     * @return true if the horizontal edges should are faded on scroll, false
12047     *         otherwise
12048     *
12049     * @see #setHorizontalFadingEdgeEnabled(boolean)
12050     *
12051     * @attr ref android.R.styleable#View_requiresFadingEdge
12052     */
12053    public boolean isHorizontalFadingEdgeEnabled() {
12054        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
12055    }
12056
12057    /**
12058     * <p>Define whether the horizontal edges should be faded when this view
12059     * is scrolled horizontally.</p>
12060     *
12061     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
12062     *                                    be faded when the view is scrolled
12063     *                                    horizontally
12064     *
12065     * @see #isHorizontalFadingEdgeEnabled()
12066     *
12067     * @attr ref android.R.styleable#View_requiresFadingEdge
12068     */
12069    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
12070        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
12071            if (horizontalFadingEdgeEnabled) {
12072                initScrollCache();
12073            }
12074
12075            mViewFlags ^= FADING_EDGE_HORIZONTAL;
12076        }
12077    }
12078
12079    /**
12080     * <p>Indicate whether the vertical edges are faded when the view is
12081     * scrolled horizontally.</p>
12082     *
12083     * @return true if the vertical edges should are faded on scroll, false
12084     *         otherwise
12085     *
12086     * @see #setVerticalFadingEdgeEnabled(boolean)
12087     *
12088     * @attr ref android.R.styleable#View_requiresFadingEdge
12089     */
12090    public boolean isVerticalFadingEdgeEnabled() {
12091        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
12092    }
12093
12094    /**
12095     * <p>Define whether the vertical edges should be faded when this view
12096     * is scrolled vertically.</p>
12097     *
12098     * @param verticalFadingEdgeEnabled true if the vertical edges should
12099     *                                  be faded when the view is scrolled
12100     *                                  vertically
12101     *
12102     * @see #isVerticalFadingEdgeEnabled()
12103     *
12104     * @attr ref android.R.styleable#View_requiresFadingEdge
12105     */
12106    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
12107        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
12108            if (verticalFadingEdgeEnabled) {
12109                initScrollCache();
12110            }
12111
12112            mViewFlags ^= FADING_EDGE_VERTICAL;
12113        }
12114    }
12115
12116    /**
12117     * Returns the strength, or intensity, of the top faded edge. The strength is
12118     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12119     * returns 0.0 or 1.0 but no value in between.
12120     *
12121     * Subclasses should override this method to provide a smoother fade transition
12122     * when scrolling occurs.
12123     *
12124     * @return the intensity of the top fade as a float between 0.0f and 1.0f
12125     */
12126    protected float getTopFadingEdgeStrength() {
12127        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
12128    }
12129
12130    /**
12131     * Returns the strength, or intensity, of the bottom faded edge. The strength is
12132     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12133     * returns 0.0 or 1.0 but no value in between.
12134     *
12135     * Subclasses should override this method to provide a smoother fade transition
12136     * when scrolling occurs.
12137     *
12138     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
12139     */
12140    protected float getBottomFadingEdgeStrength() {
12141        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
12142                computeVerticalScrollRange() ? 1.0f : 0.0f;
12143    }
12144
12145    /**
12146     * Returns the strength, or intensity, of the left faded edge. The strength is
12147     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12148     * returns 0.0 or 1.0 but no value in between.
12149     *
12150     * Subclasses should override this method to provide a smoother fade transition
12151     * when scrolling occurs.
12152     *
12153     * @return the intensity of the left fade as a float between 0.0f and 1.0f
12154     */
12155    protected float getLeftFadingEdgeStrength() {
12156        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
12157    }
12158
12159    /**
12160     * Returns the strength, or intensity, of the right faded edge. The strength is
12161     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
12162     * returns 0.0 or 1.0 but no value in between.
12163     *
12164     * Subclasses should override this method to provide a smoother fade transition
12165     * when scrolling occurs.
12166     *
12167     * @return the intensity of the right fade as a float between 0.0f and 1.0f
12168     */
12169    protected float getRightFadingEdgeStrength() {
12170        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
12171                computeHorizontalScrollRange() ? 1.0f : 0.0f;
12172    }
12173
12174    /**
12175     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
12176     * scrollbar is not drawn by default.</p>
12177     *
12178     * @return true if the horizontal scrollbar should be painted, false
12179     *         otherwise
12180     *
12181     * @see #setHorizontalScrollBarEnabled(boolean)
12182     */
12183    public boolean isHorizontalScrollBarEnabled() {
12184        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12185    }
12186
12187    /**
12188     * <p>Define whether the horizontal scrollbar should be drawn or not. The
12189     * scrollbar is not drawn by default.</p>
12190     *
12191     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
12192     *                                   be painted
12193     *
12194     * @see #isHorizontalScrollBarEnabled()
12195     */
12196    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
12197        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
12198            mViewFlags ^= SCROLLBARS_HORIZONTAL;
12199            computeOpaqueFlags();
12200            resolvePadding();
12201        }
12202    }
12203
12204    /**
12205     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
12206     * scrollbar is not drawn by default.</p>
12207     *
12208     * @return true if the vertical scrollbar should be painted, false
12209     *         otherwise
12210     *
12211     * @see #setVerticalScrollBarEnabled(boolean)
12212     */
12213    public boolean isVerticalScrollBarEnabled() {
12214        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
12215    }
12216
12217    /**
12218     * <p>Define whether the vertical scrollbar should be drawn or not. The
12219     * scrollbar is not drawn by default.</p>
12220     *
12221     * @param verticalScrollBarEnabled true if the vertical scrollbar should
12222     *                                 be painted
12223     *
12224     * @see #isVerticalScrollBarEnabled()
12225     */
12226    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
12227        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
12228            mViewFlags ^= SCROLLBARS_VERTICAL;
12229            computeOpaqueFlags();
12230            resolvePadding();
12231        }
12232    }
12233
12234    /**
12235     * @hide
12236     */
12237    protected void recomputePadding() {
12238        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
12239    }
12240
12241    /**
12242     * Define whether scrollbars will fade when the view is not scrolling.
12243     *
12244     * @param fadeScrollbars wheter to enable fading
12245     *
12246     * @attr ref android.R.styleable#View_fadeScrollbars
12247     */
12248    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
12249        initScrollCache();
12250        final ScrollabilityCache scrollabilityCache = mScrollCache;
12251        scrollabilityCache.fadeScrollBars = fadeScrollbars;
12252        if (fadeScrollbars) {
12253            scrollabilityCache.state = ScrollabilityCache.OFF;
12254        } else {
12255            scrollabilityCache.state = ScrollabilityCache.ON;
12256        }
12257    }
12258
12259    /**
12260     *
12261     * Returns true if scrollbars will fade when this view is not scrolling
12262     *
12263     * @return true if scrollbar fading is enabled
12264     *
12265     * @attr ref android.R.styleable#View_fadeScrollbars
12266     */
12267    public boolean isScrollbarFadingEnabled() {
12268        return mScrollCache != null && mScrollCache.fadeScrollBars;
12269    }
12270
12271    /**
12272     *
12273     * Returns the delay before scrollbars fade.
12274     *
12275     * @return the delay before scrollbars fade
12276     *
12277     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12278     */
12279    public int getScrollBarDefaultDelayBeforeFade() {
12280        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
12281                mScrollCache.scrollBarDefaultDelayBeforeFade;
12282    }
12283
12284    /**
12285     * Define the delay before scrollbars fade.
12286     *
12287     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
12288     *
12289     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
12290     */
12291    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
12292        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
12293    }
12294
12295    /**
12296     *
12297     * Returns the scrollbar fade duration.
12298     *
12299     * @return the scrollbar fade duration
12300     *
12301     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12302     */
12303    public int getScrollBarFadeDuration() {
12304        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
12305                mScrollCache.scrollBarFadeDuration;
12306    }
12307
12308    /**
12309     * Define the scrollbar fade duration.
12310     *
12311     * @param scrollBarFadeDuration - the scrollbar fade duration
12312     *
12313     * @attr ref android.R.styleable#View_scrollbarFadeDuration
12314     */
12315    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
12316        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
12317    }
12318
12319    /**
12320     *
12321     * Returns the scrollbar size.
12322     *
12323     * @return the scrollbar size
12324     *
12325     * @attr ref android.R.styleable#View_scrollbarSize
12326     */
12327    public int getScrollBarSize() {
12328        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
12329                mScrollCache.scrollBarSize;
12330    }
12331
12332    /**
12333     * Define the scrollbar size.
12334     *
12335     * @param scrollBarSize - the scrollbar size
12336     *
12337     * @attr ref android.R.styleable#View_scrollbarSize
12338     */
12339    public void setScrollBarSize(int scrollBarSize) {
12340        getScrollCache().scrollBarSize = scrollBarSize;
12341    }
12342
12343    /**
12344     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
12345     * inset. When inset, they add to the padding of the view. And the scrollbars
12346     * can be drawn inside the padding area or on the edge of the view. For example,
12347     * if a view has a background drawable and you want to draw the scrollbars
12348     * inside the padding specified by the drawable, you can use
12349     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
12350     * appear at the edge of the view, ignoring the padding, then you can use
12351     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
12352     * @param style the style of the scrollbars. Should be one of
12353     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
12354     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
12355     * @see #SCROLLBARS_INSIDE_OVERLAY
12356     * @see #SCROLLBARS_INSIDE_INSET
12357     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12358     * @see #SCROLLBARS_OUTSIDE_INSET
12359     *
12360     * @attr ref android.R.styleable#View_scrollbarStyle
12361     */
12362    public void setScrollBarStyle(@ScrollBarStyle int style) {
12363        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
12364            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
12365            computeOpaqueFlags();
12366            resolvePadding();
12367        }
12368    }
12369
12370    /**
12371     * <p>Returns the current scrollbar style.</p>
12372     * @return the current scrollbar style
12373     * @see #SCROLLBARS_INSIDE_OVERLAY
12374     * @see #SCROLLBARS_INSIDE_INSET
12375     * @see #SCROLLBARS_OUTSIDE_OVERLAY
12376     * @see #SCROLLBARS_OUTSIDE_INSET
12377     *
12378     * @attr ref android.R.styleable#View_scrollbarStyle
12379     */
12380    @ViewDebug.ExportedProperty(mapping = {
12381            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
12382            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
12383            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
12384            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
12385    })
12386    @ScrollBarStyle
12387    public int getScrollBarStyle() {
12388        return mViewFlags & SCROLLBARS_STYLE_MASK;
12389    }
12390
12391    /**
12392     * <p>Compute the horizontal range that the horizontal scrollbar
12393     * represents.</p>
12394     *
12395     * <p>The range is expressed in arbitrary units that must be the same as the
12396     * units used by {@link #computeHorizontalScrollExtent()} and
12397     * {@link #computeHorizontalScrollOffset()}.</p>
12398     *
12399     * <p>The default range is the drawing width of this view.</p>
12400     *
12401     * @return the total horizontal range represented by the horizontal
12402     *         scrollbar
12403     *
12404     * @see #computeHorizontalScrollExtent()
12405     * @see #computeHorizontalScrollOffset()
12406     * @see android.widget.ScrollBarDrawable
12407     */
12408    protected int computeHorizontalScrollRange() {
12409        return getWidth();
12410    }
12411
12412    /**
12413     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
12414     * within the horizontal range. This value is used to compute the position
12415     * of the thumb within the scrollbar's track.</p>
12416     *
12417     * <p>The range is expressed in arbitrary units that must be the same as the
12418     * units used by {@link #computeHorizontalScrollRange()} and
12419     * {@link #computeHorizontalScrollExtent()}.</p>
12420     *
12421     * <p>The default offset is the scroll offset of this view.</p>
12422     *
12423     * @return the horizontal offset of the scrollbar's thumb
12424     *
12425     * @see #computeHorizontalScrollRange()
12426     * @see #computeHorizontalScrollExtent()
12427     * @see android.widget.ScrollBarDrawable
12428     */
12429    protected int computeHorizontalScrollOffset() {
12430        return mScrollX;
12431    }
12432
12433    /**
12434     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
12435     * within the horizontal range. This value is used to compute the length
12436     * of the thumb within the scrollbar's track.</p>
12437     *
12438     * <p>The range is expressed in arbitrary units that must be the same as the
12439     * units used by {@link #computeHorizontalScrollRange()} and
12440     * {@link #computeHorizontalScrollOffset()}.</p>
12441     *
12442     * <p>The default extent is the drawing width of this view.</p>
12443     *
12444     * @return the horizontal extent of the scrollbar's thumb
12445     *
12446     * @see #computeHorizontalScrollRange()
12447     * @see #computeHorizontalScrollOffset()
12448     * @see android.widget.ScrollBarDrawable
12449     */
12450    protected int computeHorizontalScrollExtent() {
12451        return getWidth();
12452    }
12453
12454    /**
12455     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
12456     *
12457     * <p>The range is expressed in arbitrary units that must be the same as the
12458     * units used by {@link #computeVerticalScrollExtent()} and
12459     * {@link #computeVerticalScrollOffset()}.</p>
12460     *
12461     * @return the total vertical range represented by the vertical scrollbar
12462     *
12463     * <p>The default range is the drawing height of this view.</p>
12464     *
12465     * @see #computeVerticalScrollExtent()
12466     * @see #computeVerticalScrollOffset()
12467     * @see android.widget.ScrollBarDrawable
12468     */
12469    protected int computeVerticalScrollRange() {
12470        return getHeight();
12471    }
12472
12473    /**
12474     * <p>Compute the vertical offset of the vertical scrollbar's thumb
12475     * within the horizontal range. This value is used to compute the position
12476     * of the thumb within the scrollbar's track.</p>
12477     *
12478     * <p>The range is expressed in arbitrary units that must be the same as the
12479     * units used by {@link #computeVerticalScrollRange()} and
12480     * {@link #computeVerticalScrollExtent()}.</p>
12481     *
12482     * <p>The default offset is the scroll offset of this view.</p>
12483     *
12484     * @return the vertical offset of the scrollbar's thumb
12485     *
12486     * @see #computeVerticalScrollRange()
12487     * @see #computeVerticalScrollExtent()
12488     * @see android.widget.ScrollBarDrawable
12489     */
12490    protected int computeVerticalScrollOffset() {
12491        return mScrollY;
12492    }
12493
12494    /**
12495     * <p>Compute the vertical extent of the vertical scrollbar's thumb
12496     * within the vertical range. This value is used to compute the length
12497     * of the thumb within the scrollbar's track.</p>
12498     *
12499     * <p>The range is expressed in arbitrary units that must be the same as the
12500     * units used by {@link #computeVerticalScrollRange()} and
12501     * {@link #computeVerticalScrollOffset()}.</p>
12502     *
12503     * <p>The default extent is the drawing height of this view.</p>
12504     *
12505     * @return the vertical extent of the scrollbar's thumb
12506     *
12507     * @see #computeVerticalScrollRange()
12508     * @see #computeVerticalScrollOffset()
12509     * @see android.widget.ScrollBarDrawable
12510     */
12511    protected int computeVerticalScrollExtent() {
12512        return getHeight();
12513    }
12514
12515    /**
12516     * Check if this view can be scrolled horizontally in a certain direction.
12517     *
12518     * @param direction Negative to check scrolling left, positive to check scrolling right.
12519     * @return true if this view can be scrolled in the specified direction, false otherwise.
12520     */
12521    public boolean canScrollHorizontally(int direction) {
12522        final int offset = computeHorizontalScrollOffset();
12523        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
12524        if (range == 0) return false;
12525        if (direction < 0) {
12526            return offset > 0;
12527        } else {
12528            return offset < range - 1;
12529        }
12530    }
12531
12532    /**
12533     * Check if this view can be scrolled vertically in a certain direction.
12534     *
12535     * @param direction Negative to check scrolling up, positive to check scrolling down.
12536     * @return true if this view can be scrolled in the specified direction, false otherwise.
12537     */
12538    public boolean canScrollVertically(int direction) {
12539        final int offset = computeVerticalScrollOffset();
12540        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
12541        if (range == 0) return false;
12542        if (direction < 0) {
12543            return offset > 0;
12544        } else {
12545            return offset < range - 1;
12546        }
12547    }
12548
12549    /**
12550     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
12551     * scrollbars are painted only if they have been awakened first.</p>
12552     *
12553     * @param canvas the canvas on which to draw the scrollbars
12554     *
12555     * @see #awakenScrollBars(int)
12556     */
12557    protected final void onDrawScrollBars(Canvas canvas) {
12558        // scrollbars are drawn only when the animation is running
12559        final ScrollabilityCache cache = mScrollCache;
12560        if (cache != null) {
12561
12562            int state = cache.state;
12563
12564            if (state == ScrollabilityCache.OFF) {
12565                return;
12566            }
12567
12568            boolean invalidate = false;
12569
12570            if (state == ScrollabilityCache.FADING) {
12571                // We're fading -- get our fade interpolation
12572                if (cache.interpolatorValues == null) {
12573                    cache.interpolatorValues = new float[1];
12574                }
12575
12576                float[] values = cache.interpolatorValues;
12577
12578                // Stops the animation if we're done
12579                if (cache.scrollBarInterpolator.timeToValues(values) ==
12580                        Interpolator.Result.FREEZE_END) {
12581                    cache.state = ScrollabilityCache.OFF;
12582                } else {
12583                    cache.scrollBar.setAlpha(Math.round(values[0]));
12584                }
12585
12586                // This will make the scroll bars inval themselves after
12587                // drawing. We only want this when we're fading so that
12588                // we prevent excessive redraws
12589                invalidate = true;
12590            } else {
12591                // We're just on -- but we may have been fading before so
12592                // reset alpha
12593                cache.scrollBar.setAlpha(255);
12594            }
12595
12596
12597            final int viewFlags = mViewFlags;
12598
12599            final boolean drawHorizontalScrollBar =
12600                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
12601            final boolean drawVerticalScrollBar =
12602                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
12603                && !isVerticalScrollBarHidden();
12604
12605            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
12606                final int width = mRight - mLeft;
12607                final int height = mBottom - mTop;
12608
12609                final ScrollBarDrawable scrollBar = cache.scrollBar;
12610
12611                final int scrollX = mScrollX;
12612                final int scrollY = mScrollY;
12613                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
12614
12615                int left;
12616                int top;
12617                int right;
12618                int bottom;
12619
12620                if (drawHorizontalScrollBar) {
12621                    int size = scrollBar.getSize(false);
12622                    if (size <= 0) {
12623                        size = cache.scrollBarSize;
12624                    }
12625
12626                    scrollBar.setParameters(computeHorizontalScrollRange(),
12627                                            computeHorizontalScrollOffset(),
12628                                            computeHorizontalScrollExtent(), false);
12629                    final int verticalScrollBarGap = drawVerticalScrollBar ?
12630                            getVerticalScrollbarWidth() : 0;
12631                    top = scrollY + height - size - (mUserPaddingBottom & inside);
12632                    left = scrollX + (mPaddingLeft & inside);
12633                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
12634                    bottom = top + size;
12635                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
12636                    if (invalidate) {
12637                        invalidate(left, top, right, bottom);
12638                    }
12639                }
12640
12641                if (drawVerticalScrollBar) {
12642                    int size = scrollBar.getSize(true);
12643                    if (size <= 0) {
12644                        size = cache.scrollBarSize;
12645                    }
12646
12647                    scrollBar.setParameters(computeVerticalScrollRange(),
12648                                            computeVerticalScrollOffset(),
12649                                            computeVerticalScrollExtent(), true);
12650                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
12651                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
12652                        verticalScrollbarPosition = isLayoutRtl() ?
12653                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
12654                    }
12655                    switch (verticalScrollbarPosition) {
12656                        default:
12657                        case SCROLLBAR_POSITION_RIGHT:
12658                            left = scrollX + width - size - (mUserPaddingRight & inside);
12659                            break;
12660                        case SCROLLBAR_POSITION_LEFT:
12661                            left = scrollX + (mUserPaddingLeft & inside);
12662                            break;
12663                    }
12664                    top = scrollY + (mPaddingTop & inside);
12665                    right = left + size;
12666                    bottom = scrollY + height - (mUserPaddingBottom & inside);
12667                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
12668                    if (invalidate) {
12669                        invalidate(left, top, right, bottom);
12670                    }
12671                }
12672            }
12673        }
12674    }
12675
12676    /**
12677     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
12678     * FastScroller is visible.
12679     * @return whether to temporarily hide the vertical scrollbar
12680     * @hide
12681     */
12682    protected boolean isVerticalScrollBarHidden() {
12683        return false;
12684    }
12685
12686    /**
12687     * <p>Draw the horizontal scrollbar if
12688     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
12689     *
12690     * @param canvas the canvas on which to draw the scrollbar
12691     * @param scrollBar the scrollbar's drawable
12692     *
12693     * @see #isHorizontalScrollBarEnabled()
12694     * @see #computeHorizontalScrollRange()
12695     * @see #computeHorizontalScrollExtent()
12696     * @see #computeHorizontalScrollOffset()
12697     * @see android.widget.ScrollBarDrawable
12698     * @hide
12699     */
12700    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
12701            int l, int t, int r, int b) {
12702        scrollBar.setBounds(l, t, r, b);
12703        scrollBar.draw(canvas);
12704    }
12705
12706    /**
12707     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
12708     * returns true.</p>
12709     *
12710     * @param canvas the canvas on which to draw the scrollbar
12711     * @param scrollBar the scrollbar's drawable
12712     *
12713     * @see #isVerticalScrollBarEnabled()
12714     * @see #computeVerticalScrollRange()
12715     * @see #computeVerticalScrollExtent()
12716     * @see #computeVerticalScrollOffset()
12717     * @see android.widget.ScrollBarDrawable
12718     * @hide
12719     */
12720    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
12721            int l, int t, int r, int b) {
12722        scrollBar.setBounds(l, t, r, b);
12723        scrollBar.draw(canvas);
12724    }
12725
12726    /**
12727     * Implement this to do your drawing.
12728     *
12729     * @param canvas the canvas on which the background will be drawn
12730     */
12731    protected void onDraw(Canvas canvas) {
12732    }
12733
12734    /*
12735     * Caller is responsible for calling requestLayout if necessary.
12736     * (This allows addViewInLayout to not request a new layout.)
12737     */
12738    void assignParent(ViewParent parent) {
12739        if (mParent == null) {
12740            mParent = parent;
12741        } else if (parent == null) {
12742            mParent = null;
12743        } else {
12744            throw new RuntimeException("view " + this + " being added, but"
12745                    + " it already has a parent");
12746        }
12747    }
12748
12749    /**
12750     * This is called when the view is attached to a window.  At this point it
12751     * has a Surface and will start drawing.  Note that this function is
12752     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
12753     * however it may be called any time before the first onDraw -- including
12754     * before or after {@link #onMeasure(int, int)}.
12755     *
12756     * @see #onDetachedFromWindow()
12757     */
12758    protected void onAttachedToWindow() {
12759        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
12760            mParent.requestTransparentRegion(this);
12761        }
12762
12763        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
12764            initialAwakenScrollBars();
12765            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
12766        }
12767
12768        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
12769
12770        jumpDrawablesToCurrentState();
12771
12772        resetSubtreeAccessibilityStateChanged();
12773
12774        invalidateOutline();
12775
12776        if (isFocused()) {
12777            InputMethodManager imm = InputMethodManager.peekInstance();
12778            imm.focusIn(this);
12779        }
12780    }
12781
12782    /**
12783     * Resolve all RTL related properties.
12784     *
12785     * @return true if resolution of RTL properties has been done
12786     *
12787     * @hide
12788     */
12789    public boolean resolveRtlPropertiesIfNeeded() {
12790        if (!needRtlPropertiesResolution()) return false;
12791
12792        // Order is important here: LayoutDirection MUST be resolved first
12793        if (!isLayoutDirectionResolved()) {
12794            resolveLayoutDirection();
12795            resolveLayoutParams();
12796        }
12797        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
12798        if (!isTextDirectionResolved()) {
12799            resolveTextDirection();
12800        }
12801        if (!isTextAlignmentResolved()) {
12802            resolveTextAlignment();
12803        }
12804        // Should resolve Drawables before Padding because we need the layout direction of the
12805        // Drawable to correctly resolve Padding.
12806        if (!isDrawablesResolved()) {
12807            resolveDrawables();
12808        }
12809        if (!isPaddingResolved()) {
12810            resolvePadding();
12811        }
12812        onRtlPropertiesChanged(getLayoutDirection());
12813        return true;
12814    }
12815
12816    /**
12817     * Reset resolution of all RTL related properties.
12818     *
12819     * @hide
12820     */
12821    public void resetRtlProperties() {
12822        resetResolvedLayoutDirection();
12823        resetResolvedTextDirection();
12824        resetResolvedTextAlignment();
12825        resetResolvedPadding();
12826        resetResolvedDrawables();
12827    }
12828
12829    /**
12830     * @see #onScreenStateChanged(int)
12831     */
12832    void dispatchScreenStateChanged(int screenState) {
12833        onScreenStateChanged(screenState);
12834    }
12835
12836    /**
12837     * This method is called whenever the state of the screen this view is
12838     * attached to changes. A state change will usually occurs when the screen
12839     * turns on or off (whether it happens automatically or the user does it
12840     * manually.)
12841     *
12842     * @param screenState The new state of the screen. Can be either
12843     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
12844     */
12845    public void onScreenStateChanged(int screenState) {
12846    }
12847
12848    /**
12849     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
12850     */
12851    private boolean hasRtlSupport() {
12852        return mContext.getApplicationInfo().hasRtlSupport();
12853    }
12854
12855    /**
12856     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
12857     * RTL not supported)
12858     */
12859    private boolean isRtlCompatibilityMode() {
12860        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
12861        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
12862    }
12863
12864    /**
12865     * @return true if RTL properties need resolution.
12866     *
12867     */
12868    private boolean needRtlPropertiesResolution() {
12869        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
12870    }
12871
12872    /**
12873     * Called when any RTL property (layout direction or text direction or text alignment) has
12874     * been changed.
12875     *
12876     * Subclasses need to override this method to take care of cached information that depends on the
12877     * resolved layout direction, or to inform child views that inherit their layout direction.
12878     *
12879     * The default implementation does nothing.
12880     *
12881     * @param layoutDirection the direction of the layout
12882     *
12883     * @see #LAYOUT_DIRECTION_LTR
12884     * @see #LAYOUT_DIRECTION_RTL
12885     */
12886    public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) {
12887    }
12888
12889    /**
12890     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
12891     * that the parent directionality can and will be resolved before its children.
12892     *
12893     * @return true if resolution has been done, false otherwise.
12894     *
12895     * @hide
12896     */
12897    public boolean resolveLayoutDirection() {
12898        // Clear any previous layout direction resolution
12899        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12900
12901        if (hasRtlSupport()) {
12902            // Set resolved depending on layout direction
12903            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
12904                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
12905                case LAYOUT_DIRECTION_INHERIT:
12906                    // We cannot resolve yet. LTR is by default and let the resolution happen again
12907                    // later to get the correct resolved value
12908                    if (!canResolveLayoutDirection()) return false;
12909
12910                    // Parent has not yet resolved, LTR is still the default
12911                    try {
12912                        if (!mParent.isLayoutDirectionResolved()) return false;
12913
12914                        if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12915                            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12916                        }
12917                    } catch (AbstractMethodError e) {
12918                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12919                                " does not fully implement ViewParent", e);
12920                    }
12921                    break;
12922                case LAYOUT_DIRECTION_RTL:
12923                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12924                    break;
12925                case LAYOUT_DIRECTION_LOCALE:
12926                    if((LAYOUT_DIRECTION_RTL ==
12927                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
12928                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
12929                    }
12930                    break;
12931                default:
12932                    // Nothing to do, LTR by default
12933            }
12934        }
12935
12936        // Set to resolved
12937        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12938        return true;
12939    }
12940
12941    /**
12942     * Check if layout direction resolution can be done.
12943     *
12944     * @return true if layout direction resolution can be done otherwise return false.
12945     */
12946    public boolean canResolveLayoutDirection() {
12947        switch (getRawLayoutDirection()) {
12948            case LAYOUT_DIRECTION_INHERIT:
12949                if (mParent != null) {
12950                    try {
12951                        return mParent.canResolveLayoutDirection();
12952                    } catch (AbstractMethodError e) {
12953                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
12954                                " does not fully implement ViewParent", e);
12955                    }
12956                }
12957                return false;
12958
12959            default:
12960                return true;
12961        }
12962    }
12963
12964    /**
12965     * Reset the resolved layout direction. Layout direction will be resolved during a call to
12966     * {@link #onMeasure(int, int)}.
12967     *
12968     * @hide
12969     */
12970    public void resetResolvedLayoutDirection() {
12971        // Reset the current resolved bits
12972        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
12973    }
12974
12975    /**
12976     * @return true if the layout direction is inherited.
12977     *
12978     * @hide
12979     */
12980    public boolean isLayoutDirectionInherited() {
12981        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
12982    }
12983
12984    /**
12985     * @return true if layout direction has been resolved.
12986     */
12987    public boolean isLayoutDirectionResolved() {
12988        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
12989    }
12990
12991    /**
12992     * Return if padding has been resolved
12993     *
12994     * @hide
12995     */
12996    boolean isPaddingResolved() {
12997        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
12998    }
12999
13000    /**
13001     * Resolves padding depending on layout direction, if applicable, and
13002     * recomputes internal padding values to adjust for scroll bars.
13003     *
13004     * @hide
13005     */
13006    public void resolvePadding() {
13007        final int resolvedLayoutDirection = getLayoutDirection();
13008
13009        if (!isRtlCompatibilityMode()) {
13010            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
13011            // If start / end padding are defined, they will be resolved (hence overriding) to
13012            // left / right or right / left depending on the resolved layout direction.
13013            // If start / end padding are not defined, use the left / right ones.
13014            if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) {
13015                Rect padding = sThreadLocal.get();
13016                if (padding == null) {
13017                    padding = new Rect();
13018                    sThreadLocal.set(padding);
13019                }
13020                mBackground.getPadding(padding);
13021                if (!mLeftPaddingDefined) {
13022                    mUserPaddingLeftInitial = padding.left;
13023                }
13024                if (!mRightPaddingDefined) {
13025                    mUserPaddingRightInitial = padding.right;
13026                }
13027            }
13028            switch (resolvedLayoutDirection) {
13029                case LAYOUT_DIRECTION_RTL:
13030                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13031                        mUserPaddingRight = mUserPaddingStart;
13032                    } else {
13033                        mUserPaddingRight = mUserPaddingRightInitial;
13034                    }
13035                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13036                        mUserPaddingLeft = mUserPaddingEnd;
13037                    } else {
13038                        mUserPaddingLeft = mUserPaddingLeftInitial;
13039                    }
13040                    break;
13041                case LAYOUT_DIRECTION_LTR:
13042                default:
13043                    if (mUserPaddingStart != UNDEFINED_PADDING) {
13044                        mUserPaddingLeft = mUserPaddingStart;
13045                    } else {
13046                        mUserPaddingLeft = mUserPaddingLeftInitial;
13047                    }
13048                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
13049                        mUserPaddingRight = mUserPaddingEnd;
13050                    } else {
13051                        mUserPaddingRight = mUserPaddingRightInitial;
13052                    }
13053            }
13054
13055            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
13056        }
13057
13058        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
13059        onRtlPropertiesChanged(resolvedLayoutDirection);
13060
13061        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
13062    }
13063
13064    /**
13065     * Reset the resolved layout direction.
13066     *
13067     * @hide
13068     */
13069    public void resetResolvedPadding() {
13070        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
13071    }
13072
13073    /**
13074     * This is called when the view is detached from a window.  At this point it
13075     * no longer has a surface for drawing.
13076     *
13077     * @see #onAttachedToWindow()
13078     */
13079    protected void onDetachedFromWindow() {
13080    }
13081
13082    /**
13083     * This is a framework-internal mirror of onDetachedFromWindow() that's called
13084     * after onDetachedFromWindow().
13085     *
13086     * If you override this you *MUST* call super.onDetachedFromWindowInternal()!
13087     * The super method should be called at the end of the overriden method to ensure
13088     * subclasses are destroyed first
13089     *
13090     * @hide
13091     */
13092    protected void onDetachedFromWindowInternal() {
13093        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
13094        mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT;
13095
13096        removeUnsetPressCallback();
13097        removeLongPressCallback();
13098        removePerformClickCallback();
13099        removeSendViewScrolledAccessibilityEventCallback();
13100        stopNestedScroll();
13101
13102        // Anything that started animating right before detach should already
13103        // be in its final state when re-attached.
13104        jumpDrawablesToCurrentState();
13105
13106        destroyDrawingCache();
13107
13108        cleanupDraw();
13109        mCurrentAnimation = null;
13110    }
13111
13112    private void cleanupDraw() {
13113        resetDisplayList();
13114        if (mAttachInfo != null) {
13115            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
13116        }
13117    }
13118
13119    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
13120    }
13121
13122    /**
13123     * @return The number of times this view has been attached to a window
13124     */
13125    protected int getWindowAttachCount() {
13126        return mWindowAttachCount;
13127    }
13128
13129    /**
13130     * Retrieve a unique token identifying the window this view is attached to.
13131     * @return Return the window's token for use in
13132     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
13133     */
13134    public IBinder getWindowToken() {
13135        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
13136    }
13137
13138    /**
13139     * Retrieve the {@link WindowId} for the window this view is
13140     * currently attached to.
13141     */
13142    public WindowId getWindowId() {
13143        if (mAttachInfo == null) {
13144            return null;
13145        }
13146        if (mAttachInfo.mWindowId == null) {
13147            try {
13148                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
13149                        mAttachInfo.mWindowToken);
13150                mAttachInfo.mWindowId = new WindowId(
13151                        mAttachInfo.mIWindowId);
13152            } catch (RemoteException e) {
13153            }
13154        }
13155        return mAttachInfo.mWindowId;
13156    }
13157
13158    /**
13159     * Retrieve a unique token identifying the top-level "real" window of
13160     * the window that this view is attached to.  That is, this is like
13161     * {@link #getWindowToken}, except if the window this view in is a panel
13162     * window (attached to another containing window), then the token of
13163     * the containing window is returned instead.
13164     *
13165     * @return Returns the associated window token, either
13166     * {@link #getWindowToken()} or the containing window's token.
13167     */
13168    public IBinder getApplicationWindowToken() {
13169        AttachInfo ai = mAttachInfo;
13170        if (ai != null) {
13171            IBinder appWindowToken = ai.mPanelParentWindowToken;
13172            if (appWindowToken == null) {
13173                appWindowToken = ai.mWindowToken;
13174            }
13175            return appWindowToken;
13176        }
13177        return null;
13178    }
13179
13180    /**
13181     * Gets the logical display to which the view's window has been attached.
13182     *
13183     * @return The logical display, or null if the view is not currently attached to a window.
13184     */
13185    public Display getDisplay() {
13186        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
13187    }
13188
13189    /**
13190     * Retrieve private session object this view hierarchy is using to
13191     * communicate with the window manager.
13192     * @return the session object to communicate with the window manager
13193     */
13194    /*package*/ IWindowSession getWindowSession() {
13195        return mAttachInfo != null ? mAttachInfo.mSession : null;
13196    }
13197
13198    /**
13199     * @param info the {@link android.view.View.AttachInfo} to associated with
13200     *        this view
13201     */
13202    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
13203        //System.out.println("Attached! " + this);
13204        mAttachInfo = info;
13205        if (mOverlay != null) {
13206            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
13207        }
13208        mWindowAttachCount++;
13209        // We will need to evaluate the drawable state at least once.
13210        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
13211        if (mFloatingTreeObserver != null) {
13212            info.mTreeObserver.merge(mFloatingTreeObserver);
13213            mFloatingTreeObserver = null;
13214        }
13215        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
13216            mAttachInfo.mScrollContainers.add(this);
13217            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
13218        }
13219        performCollectViewAttributes(mAttachInfo, visibility);
13220        onAttachedToWindow();
13221
13222        ListenerInfo li = mListenerInfo;
13223        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13224                li != null ? li.mOnAttachStateChangeListeners : null;
13225        if (listeners != null && listeners.size() > 0) {
13226            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13227            // perform the dispatching. The iterator is a safe guard against listeners that
13228            // could mutate the list by calling the various add/remove methods. This prevents
13229            // the array from being modified while we iterate it.
13230            for (OnAttachStateChangeListener listener : listeners) {
13231                listener.onViewAttachedToWindow(this);
13232            }
13233        }
13234
13235        int vis = info.mWindowVisibility;
13236        if (vis != GONE) {
13237            onWindowVisibilityChanged(vis);
13238        }
13239        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
13240            // If nobody has evaluated the drawable state yet, then do it now.
13241            refreshDrawableState();
13242        }
13243        needGlobalAttributesUpdate(false);
13244    }
13245
13246    void dispatchDetachedFromWindow() {
13247        AttachInfo info = mAttachInfo;
13248        if (info != null) {
13249            int vis = info.mWindowVisibility;
13250            if (vis != GONE) {
13251                onWindowVisibilityChanged(GONE);
13252            }
13253        }
13254
13255        onDetachedFromWindow();
13256        onDetachedFromWindowInternal();
13257
13258        ListenerInfo li = mListenerInfo;
13259        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
13260                li != null ? li.mOnAttachStateChangeListeners : null;
13261        if (listeners != null && listeners.size() > 0) {
13262            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
13263            // perform the dispatching. The iterator is a safe guard against listeners that
13264            // could mutate the list by calling the various add/remove methods. This prevents
13265            // the array from being modified while we iterate it.
13266            for (OnAttachStateChangeListener listener : listeners) {
13267                listener.onViewDetachedFromWindow(this);
13268            }
13269        }
13270
13271        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
13272            mAttachInfo.mScrollContainers.remove(this);
13273            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
13274        }
13275
13276        mAttachInfo = null;
13277        if (mOverlay != null) {
13278            mOverlay.getOverlayView().dispatchDetachedFromWindow();
13279        }
13280    }
13281
13282    /**
13283     * Cancel any deferred high-level input events that were previously posted to the event queue.
13284     *
13285     * <p>Many views post high-level events such as click handlers to the event queue
13286     * to run deferred in order to preserve a desired user experience - clearing visible
13287     * pressed states before executing, etc. This method will abort any events of this nature
13288     * that are currently in flight.</p>
13289     *
13290     * <p>Custom views that generate their own high-level deferred input events should override
13291     * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p>
13292     *
13293     * <p>This will also cancel pending input events for any child views.</p>
13294     *
13295     * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases.
13296     * This will not impact newer events posted after this call that may occur as a result of
13297     * lower-level input events still waiting in the queue. If you are trying to prevent
13298     * double-submitted  events for the duration of some sort of asynchronous transaction
13299     * you should also take other steps to protect against unexpected double inputs e.g. calling
13300     * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when
13301     * the transaction completes, tracking already submitted transaction IDs, etc.</p>
13302     */
13303    public final void cancelPendingInputEvents() {
13304        dispatchCancelPendingInputEvents();
13305    }
13306
13307    /**
13308     * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight.
13309     * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling.
13310     */
13311    void dispatchCancelPendingInputEvents() {
13312        mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER;
13313        onCancelPendingInputEvents();
13314        if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) {
13315            throw new SuperNotCalledException("View " + getClass().getSimpleName() +
13316                    " did not call through to super.onCancelPendingInputEvents()");
13317        }
13318    }
13319
13320    /**
13321     * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or
13322     * a parent view.
13323     *
13324     * <p>This method is responsible for removing any pending high-level input events that were
13325     * posted to the event queue to run later. Custom view classes that post their own deferred
13326     * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or
13327     * {@link android.os.Handler} should override this method, call
13328     * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate.
13329     * </p>
13330     */
13331    public void onCancelPendingInputEvents() {
13332        removePerformClickCallback();
13333        cancelLongPress();
13334        mPrivateFlags3 |= PFLAG3_CALLED_SUPER;
13335    }
13336
13337    /**
13338     * Store this view hierarchy's frozen state into the given container.
13339     *
13340     * @param container The SparseArray in which to save the view's state.
13341     *
13342     * @see #restoreHierarchyState(android.util.SparseArray)
13343     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13344     * @see #onSaveInstanceState()
13345     */
13346    public void saveHierarchyState(SparseArray<Parcelable> container) {
13347        dispatchSaveInstanceState(container);
13348    }
13349
13350    /**
13351     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
13352     * this view and its children. May be overridden to modify how freezing happens to a
13353     * view's children; for example, some views may want to not store state for their children.
13354     *
13355     * @param container The SparseArray in which to save the view's state.
13356     *
13357     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13358     * @see #saveHierarchyState(android.util.SparseArray)
13359     * @see #onSaveInstanceState()
13360     */
13361    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
13362        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
13363            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13364            Parcelable state = onSaveInstanceState();
13365            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13366                throw new IllegalStateException(
13367                        "Derived class did not call super.onSaveInstanceState()");
13368            }
13369            if (state != null) {
13370                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
13371                // + ": " + state);
13372                container.put(mID, state);
13373            }
13374        }
13375    }
13376
13377    /**
13378     * Hook allowing a view to generate a representation of its internal state
13379     * that can later be used to create a new instance with that same state.
13380     * This state should only contain information that is not persistent or can
13381     * not be reconstructed later. For example, you will never store your
13382     * current position on screen because that will be computed again when a
13383     * new instance of the view is placed in its view hierarchy.
13384     * <p>
13385     * Some examples of things you may store here: the current cursor position
13386     * in a text view (but usually not the text itself since that is stored in a
13387     * content provider or other persistent storage), the currently selected
13388     * item in a list view.
13389     *
13390     * @return Returns a Parcelable object containing the view's current dynamic
13391     *         state, or null if there is nothing interesting to save. The
13392     *         default implementation returns null.
13393     * @see #onRestoreInstanceState(android.os.Parcelable)
13394     * @see #saveHierarchyState(android.util.SparseArray)
13395     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13396     * @see #setSaveEnabled(boolean)
13397     */
13398    protected Parcelable onSaveInstanceState() {
13399        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13400        return BaseSavedState.EMPTY_STATE;
13401    }
13402
13403    /**
13404     * Restore this view hierarchy's frozen state from the given container.
13405     *
13406     * @param container The SparseArray which holds previously frozen states.
13407     *
13408     * @see #saveHierarchyState(android.util.SparseArray)
13409     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13410     * @see #onRestoreInstanceState(android.os.Parcelable)
13411     */
13412    public void restoreHierarchyState(SparseArray<Parcelable> container) {
13413        dispatchRestoreInstanceState(container);
13414    }
13415
13416    /**
13417     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
13418     * state for this view and its children. May be overridden to modify how restoring
13419     * happens to a view's children; for example, some views may want to not store state
13420     * for their children.
13421     *
13422     * @param container The SparseArray which holds previously saved state.
13423     *
13424     * @see #dispatchSaveInstanceState(android.util.SparseArray)
13425     * @see #restoreHierarchyState(android.util.SparseArray)
13426     * @see #onRestoreInstanceState(android.os.Parcelable)
13427     */
13428    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
13429        if (mID != NO_ID) {
13430            Parcelable state = container.get(mID);
13431            if (state != null) {
13432                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
13433                // + ": " + state);
13434                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
13435                onRestoreInstanceState(state);
13436                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
13437                    throw new IllegalStateException(
13438                            "Derived class did not call super.onRestoreInstanceState()");
13439                }
13440            }
13441        }
13442    }
13443
13444    /**
13445     * Hook allowing a view to re-apply a representation of its internal state that had previously
13446     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
13447     * null state.
13448     *
13449     * @param state The frozen state that had previously been returned by
13450     *        {@link #onSaveInstanceState}.
13451     *
13452     * @see #onSaveInstanceState()
13453     * @see #restoreHierarchyState(android.util.SparseArray)
13454     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
13455     */
13456    protected void onRestoreInstanceState(Parcelable state) {
13457        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
13458        if (state != BaseSavedState.EMPTY_STATE && state != null) {
13459            throw new IllegalArgumentException("Wrong state class, expecting View State but "
13460                    + "received " + state.getClass().toString() + " instead. This usually happens "
13461                    + "when two views of different type have the same id in the same hierarchy. "
13462                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
13463                    + "other views do not use the same id.");
13464        }
13465    }
13466
13467    /**
13468     * <p>Return the time at which the drawing of the view hierarchy started.</p>
13469     *
13470     * @return the drawing start time in milliseconds
13471     */
13472    public long getDrawingTime() {
13473        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
13474    }
13475
13476    /**
13477     * <p>Enables or disables the duplication of the parent's state into this view. When
13478     * duplication is enabled, this view gets its drawable state from its parent rather
13479     * than from its own internal properties.</p>
13480     *
13481     * <p>Note: in the current implementation, setting this property to true after the
13482     * view was added to a ViewGroup might have no effect at all. This property should
13483     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
13484     *
13485     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
13486     * property is enabled, an exception will be thrown.</p>
13487     *
13488     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
13489     * parent, these states should not be affected by this method.</p>
13490     *
13491     * @param enabled True to enable duplication of the parent's drawable state, false
13492     *                to disable it.
13493     *
13494     * @see #getDrawableState()
13495     * @see #isDuplicateParentStateEnabled()
13496     */
13497    public void setDuplicateParentStateEnabled(boolean enabled) {
13498        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
13499    }
13500
13501    /**
13502     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
13503     *
13504     * @return True if this view's drawable state is duplicated from the parent,
13505     *         false otherwise
13506     *
13507     * @see #getDrawableState()
13508     * @see #setDuplicateParentStateEnabled(boolean)
13509     */
13510    public boolean isDuplicateParentStateEnabled() {
13511        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
13512    }
13513
13514    /**
13515     * <p>Specifies the type of layer backing this view. The layer can be
13516     * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13517     * {@link #LAYER_TYPE_HARDWARE}.</p>
13518     *
13519     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13520     * instance that controls how the layer is composed on screen. The following
13521     * properties of the paint are taken into account when composing the layer:</p>
13522     * <ul>
13523     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13524     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13525     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13526     * </ul>
13527     *
13528     * <p>If this view has an alpha value set to < 1.0 by calling
13529     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
13530     * by this view's alpha value.</p>
13531     *
13532     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
13533     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
13534     * for more information on when and how to use layers.</p>
13535     *
13536     * @param layerType The type of layer to use with this view, must be one of
13537     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13538     *        {@link #LAYER_TYPE_HARDWARE}
13539     * @param paint The paint used to compose the layer. This argument is optional
13540     *        and can be null. It is ignored when the layer type is
13541     *        {@link #LAYER_TYPE_NONE}
13542     *
13543     * @see #getLayerType()
13544     * @see #LAYER_TYPE_NONE
13545     * @see #LAYER_TYPE_SOFTWARE
13546     * @see #LAYER_TYPE_HARDWARE
13547     * @see #setAlpha(float)
13548     *
13549     * @attr ref android.R.styleable#View_layerType
13550     */
13551    public void setLayerType(int layerType, Paint paint) {
13552        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
13553            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
13554                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
13555        }
13556
13557        boolean typeChanged = mRenderNode.setLayerType(layerType);
13558
13559        if (!typeChanged) {
13560            setLayerPaint(paint);
13561            return;
13562        }
13563
13564        // Destroy any previous software drawing cache if needed
13565        if (mLayerType == LAYER_TYPE_SOFTWARE) {
13566            destroyDrawingCache();
13567        }
13568
13569        mLayerType = layerType;
13570        final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE);
13571        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
13572        mRenderNode.setLayerPaint(mLayerPaint);
13573
13574        // draw() behaves differently if we are on a layer, so we need to
13575        // invalidate() here
13576        invalidateParentCaches();
13577        invalidate(true);
13578    }
13579
13580    /**
13581     * Updates the {@link Paint} object used with the current layer (used only if the current
13582     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
13583     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
13584     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
13585     * ensure that the view gets redrawn immediately.
13586     *
13587     * <p>A layer is associated with an optional {@link android.graphics.Paint}
13588     * instance that controls how the layer is composed on screen. The following
13589     * properties of the paint are taken into account when composing the layer:</p>
13590     * <ul>
13591     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
13592     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
13593     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
13594     * </ul>
13595     *
13596     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
13597     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
13598     *
13599     * @param paint The paint used to compose the layer. This argument is optional
13600     *        and can be null. It is ignored when the layer type is
13601     *        {@link #LAYER_TYPE_NONE}
13602     *
13603     * @see #setLayerType(int, android.graphics.Paint)
13604     */
13605    public void setLayerPaint(Paint paint) {
13606        int layerType = getLayerType();
13607        if (layerType != LAYER_TYPE_NONE) {
13608            mLayerPaint = paint == null ? new Paint() : paint;
13609            if (layerType == LAYER_TYPE_HARDWARE) {
13610                if (mRenderNode.setLayerPaint(mLayerPaint)) {
13611                    invalidateViewProperty(false, false);
13612                }
13613            } else {
13614                invalidate();
13615            }
13616        }
13617    }
13618
13619    /**
13620     * Indicates whether this view has a static layer. A view with layer type
13621     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
13622     * dynamic.
13623     */
13624    boolean hasStaticLayer() {
13625        return true;
13626    }
13627
13628    /**
13629     * Indicates what type of layer is currently associated with this view. By default
13630     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
13631     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
13632     * for more information on the different types of layers.
13633     *
13634     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
13635     *         {@link #LAYER_TYPE_HARDWARE}
13636     *
13637     * @see #setLayerType(int, android.graphics.Paint)
13638     * @see #buildLayer()
13639     * @see #LAYER_TYPE_NONE
13640     * @see #LAYER_TYPE_SOFTWARE
13641     * @see #LAYER_TYPE_HARDWARE
13642     */
13643    public int getLayerType() {
13644        return mLayerType;
13645    }
13646
13647    /**
13648     * Forces this view's layer to be created and this view to be rendered
13649     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
13650     * invoking this method will have no effect.
13651     *
13652     * This method can for instance be used to render a view into its layer before
13653     * starting an animation. If this view is complex, rendering into the layer
13654     * before starting the animation will avoid skipping frames.
13655     *
13656     * @throws IllegalStateException If this view is not attached to a window
13657     *
13658     * @see #setLayerType(int, android.graphics.Paint)
13659     */
13660    public void buildLayer() {
13661        if (mLayerType == LAYER_TYPE_NONE) return;
13662
13663        final AttachInfo attachInfo = mAttachInfo;
13664        if (attachInfo == null) {
13665            throw new IllegalStateException("This view must be attached to a window first");
13666        }
13667
13668        if (getWidth() == 0 || getHeight() == 0) {
13669            return;
13670        }
13671
13672        switch (mLayerType) {
13673            case LAYER_TYPE_HARDWARE:
13674                updateDisplayListIfDirty();
13675                if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) {
13676                    attachInfo.mHardwareRenderer.buildLayer(mRenderNode);
13677                }
13678                break;
13679            case LAYER_TYPE_SOFTWARE:
13680                buildDrawingCache(true);
13681                break;
13682        }
13683    }
13684
13685    /**
13686     * If this View draws with a HardwareLayer, returns it.
13687     * Otherwise returns null
13688     *
13689     * TODO: Only TextureView uses this, can we eliminate it?
13690     */
13691    HardwareLayer getHardwareLayer() {
13692        return null;
13693    }
13694
13695    /**
13696     * Destroys all hardware rendering resources. This method is invoked
13697     * when the system needs to reclaim resources. Upon execution of this
13698     * method, you should free any OpenGL resources created by the view.
13699     *
13700     * Note: you <strong>must</strong> call
13701     * <code>super.destroyHardwareResources()</code> when overriding
13702     * this method.
13703     *
13704     * @hide
13705     */
13706    protected void destroyHardwareResources() {
13707        // Although the Layer will be destroyed by RenderNode, we want to release
13708        // the staging display list, which is also a signal to RenderNode that it's
13709        // safe to free its copy of the display list as it knows that we will
13710        // push an updated DisplayList if we try to draw again
13711        resetDisplayList();
13712    }
13713
13714    /**
13715     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
13716     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
13717     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
13718     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
13719     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
13720     * null.</p>
13721     *
13722     * <p>Enabling the drawing cache is similar to
13723     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
13724     * acceleration is turned off. When hardware acceleration is turned on, enabling the
13725     * drawing cache has no effect on rendering because the system uses a different mechanism
13726     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
13727     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
13728     * for information on how to enable software and hardware layers.</p>
13729     *
13730     * <p>This API can be used to manually generate
13731     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
13732     * {@link #getDrawingCache()}.</p>
13733     *
13734     * @param enabled true to enable the drawing cache, false otherwise
13735     *
13736     * @see #isDrawingCacheEnabled()
13737     * @see #getDrawingCache()
13738     * @see #buildDrawingCache()
13739     * @see #setLayerType(int, android.graphics.Paint)
13740     */
13741    public void setDrawingCacheEnabled(boolean enabled) {
13742        mCachingFailed = false;
13743        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
13744    }
13745
13746    /**
13747     * <p>Indicates whether the drawing cache is enabled for this view.</p>
13748     *
13749     * @return true if the drawing cache is enabled
13750     *
13751     * @see #setDrawingCacheEnabled(boolean)
13752     * @see #getDrawingCache()
13753     */
13754    @ViewDebug.ExportedProperty(category = "drawing")
13755    public boolean isDrawingCacheEnabled() {
13756        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
13757    }
13758
13759    /**
13760     * Debugging utility which recursively outputs the dirty state of a view and its
13761     * descendants.
13762     *
13763     * @hide
13764     */
13765    @SuppressWarnings({"UnusedDeclaration"})
13766    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
13767        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
13768                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
13769                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
13770                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
13771        if (clear) {
13772            mPrivateFlags &= clearMask;
13773        }
13774        if (this instanceof ViewGroup) {
13775            ViewGroup parent = (ViewGroup) this;
13776            final int count = parent.getChildCount();
13777            for (int i = 0; i < count; i++) {
13778                final View child = parent.getChildAt(i);
13779                child.outputDirtyFlags(indent + "  ", clear, clearMask);
13780            }
13781        }
13782    }
13783
13784    /**
13785     * This method is used by ViewGroup to cause its children to restore or recreate their
13786     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
13787     * to recreate its own display list, which would happen if it went through the normal
13788     * draw/dispatchDraw mechanisms.
13789     *
13790     * @hide
13791     */
13792    protected void dispatchGetDisplayList() {}
13793
13794    /**
13795     * A view that is not attached or hardware accelerated cannot create a display list.
13796     * This method checks these conditions and returns the appropriate result.
13797     *
13798     * @return true if view has the ability to create a display list, false otherwise.
13799     *
13800     * @hide
13801     */
13802    public boolean canHaveDisplayList() {
13803        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
13804    }
13805
13806    private void updateDisplayListIfDirty() {
13807        final RenderNode renderNode = mRenderNode;
13808        if (!canHaveDisplayList()) {
13809            // can't populate RenderNode, don't try
13810            return;
13811        }
13812
13813        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0
13814                || !renderNode.isValid()
13815                || (mRecreateDisplayList)) {
13816            // Don't need to recreate the display list, just need to tell our
13817            // children to restore/recreate theirs
13818            if (renderNode.isValid()
13819                    && !mRecreateDisplayList) {
13820                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13821                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13822                dispatchGetDisplayList();
13823
13824                return; // no work needed
13825            }
13826
13827            // If we got here, we're recreating it. Mark it as such to ensure that
13828            // we copy in child display lists into ours in drawChild()
13829            mRecreateDisplayList = true;
13830
13831            int width = mRight - mLeft;
13832            int height = mBottom - mTop;
13833            int layerType = getLayerType();
13834
13835            final HardwareCanvas canvas = renderNode.start(width, height);
13836            canvas.setHighContrastText(mAttachInfo.mHighContrastText);
13837
13838            try {
13839                final HardwareLayer layer = getHardwareLayer();
13840                if (layer != null && layer.isValid()) {
13841                    canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
13842                } else if (layerType == LAYER_TYPE_SOFTWARE) {
13843                    buildDrawingCache(true);
13844                    Bitmap cache = getDrawingCache(true);
13845                    if (cache != null) {
13846                        canvas.drawBitmap(cache, 0, 0, mLayerPaint);
13847                    }
13848                } else {
13849                    computeScroll();
13850
13851                    canvas.translate(-mScrollX, -mScrollY);
13852                    mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13853                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13854
13855                    // Fast path for layouts with no backgrounds
13856                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13857                        dispatchDraw(canvas);
13858                        if (mOverlay != null && !mOverlay.isEmpty()) {
13859                            mOverlay.getOverlayView().draw(canvas);
13860                        }
13861                    } else {
13862                        draw(canvas);
13863                    }
13864                    drawAccessibilityFocus(canvas);
13865                }
13866            } finally {
13867                renderNode.end(canvas);
13868                setDisplayListProperties(renderNode);
13869            }
13870        } else {
13871            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
13872            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13873        }
13874    }
13875
13876    /**
13877     * Returns a RenderNode with View draw content recorded, which can be
13878     * used to draw this view again without executing its draw method.
13879     *
13880     * @return A RenderNode ready to replay, or null if caching is not enabled.
13881     *
13882     * @hide
13883     */
13884    public RenderNode getDisplayList() {
13885        updateDisplayListIfDirty();
13886        return mRenderNode;
13887    }
13888
13889    private void resetDisplayList() {
13890        if (mRenderNode.isValid()) {
13891            mRenderNode.destroyDisplayListData();
13892        }
13893
13894        if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) {
13895            mBackgroundRenderNode.destroyDisplayListData();
13896        }
13897    }
13898
13899    /**
13900     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
13901     *
13902     * @return A non-scaled bitmap representing this view or null if cache is disabled.
13903     *
13904     * @see #getDrawingCache(boolean)
13905     */
13906    public Bitmap getDrawingCache() {
13907        return getDrawingCache(false);
13908    }
13909
13910    /**
13911     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
13912     * is null when caching is disabled. If caching is enabled and the cache is not ready,
13913     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
13914     * draw from the cache when the cache is enabled. To benefit from the cache, you must
13915     * request the drawing cache by calling this method and draw it on screen if the
13916     * returned bitmap is not null.</p>
13917     *
13918     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13919     * this method will create a bitmap of the same size as this view. Because this bitmap
13920     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13921     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13922     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13923     * size than the view. This implies that your application must be able to handle this
13924     * size.</p>
13925     *
13926     * @param autoScale Indicates whether the generated bitmap should be scaled based on
13927     *        the current density of the screen when the application is in compatibility
13928     *        mode.
13929     *
13930     * @return A bitmap representing this view or null if cache is disabled.
13931     *
13932     * @see #setDrawingCacheEnabled(boolean)
13933     * @see #isDrawingCacheEnabled()
13934     * @see #buildDrawingCache(boolean)
13935     * @see #destroyDrawingCache()
13936     */
13937    public Bitmap getDrawingCache(boolean autoScale) {
13938        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
13939            return null;
13940        }
13941        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
13942            buildDrawingCache(autoScale);
13943        }
13944        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
13945    }
13946
13947    /**
13948     * <p>Frees the resources used by the drawing cache. If you call
13949     * {@link #buildDrawingCache()} manually without calling
13950     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13951     * should cleanup the cache with this method afterwards.</p>
13952     *
13953     * @see #setDrawingCacheEnabled(boolean)
13954     * @see #buildDrawingCache()
13955     * @see #getDrawingCache()
13956     */
13957    public void destroyDrawingCache() {
13958        if (mDrawingCache != null) {
13959            mDrawingCache.recycle();
13960            mDrawingCache = null;
13961        }
13962        if (mUnscaledDrawingCache != null) {
13963            mUnscaledDrawingCache.recycle();
13964            mUnscaledDrawingCache = null;
13965        }
13966    }
13967
13968    /**
13969     * Setting a solid background color for the drawing cache's bitmaps will improve
13970     * performance and memory usage. Note, though that this should only be used if this
13971     * view will always be drawn on top of a solid color.
13972     *
13973     * @param color The background color to use for the drawing cache's bitmap
13974     *
13975     * @see #setDrawingCacheEnabled(boolean)
13976     * @see #buildDrawingCache()
13977     * @see #getDrawingCache()
13978     */
13979    public void setDrawingCacheBackgroundColor(int color) {
13980        if (color != mDrawingCacheBackgroundColor) {
13981            mDrawingCacheBackgroundColor = color;
13982            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
13983        }
13984    }
13985
13986    /**
13987     * @see #setDrawingCacheBackgroundColor(int)
13988     *
13989     * @return The background color to used for the drawing cache's bitmap
13990     */
13991    public int getDrawingCacheBackgroundColor() {
13992        return mDrawingCacheBackgroundColor;
13993    }
13994
13995    /**
13996     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
13997     *
13998     * @see #buildDrawingCache(boolean)
13999     */
14000    public void buildDrawingCache() {
14001        buildDrawingCache(false);
14002    }
14003
14004    /**
14005     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
14006     *
14007     * <p>If you call {@link #buildDrawingCache()} manually without calling
14008     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
14009     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
14010     *
14011     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
14012     * this method will create a bitmap of the same size as this view. Because this bitmap
14013     * will be drawn scaled by the parent ViewGroup, the result on screen might show
14014     * scaling artifacts. To avoid such artifacts, you should call this method by setting
14015     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
14016     * size than the view. This implies that your application must be able to handle this
14017     * size.</p>
14018     *
14019     * <p>You should avoid calling this method when hardware acceleration is enabled. If
14020     * you do not need the drawing cache bitmap, calling this method will increase memory
14021     * usage and cause the view to be rendered in software once, thus negatively impacting
14022     * performance.</p>
14023     *
14024     * @see #getDrawingCache()
14025     * @see #destroyDrawingCache()
14026     */
14027    public void buildDrawingCache(boolean autoScale) {
14028        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
14029                mDrawingCache == null : mUnscaledDrawingCache == null)) {
14030            mCachingFailed = false;
14031
14032            int width = mRight - mLeft;
14033            int height = mBottom - mTop;
14034
14035            final AttachInfo attachInfo = mAttachInfo;
14036            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
14037
14038            if (autoScale && scalingRequired) {
14039                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
14040                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
14041            }
14042
14043            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
14044            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
14045            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
14046
14047            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
14048            final long drawingCacheSize =
14049                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
14050            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
14051                if (width > 0 && height > 0) {
14052                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
14053                            + projectedBitmapSize + " bytes, only "
14054                            + drawingCacheSize + " available");
14055                }
14056                destroyDrawingCache();
14057                mCachingFailed = true;
14058                return;
14059            }
14060
14061            boolean clear = true;
14062            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
14063
14064            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
14065                Bitmap.Config quality;
14066                if (!opaque) {
14067                    // Never pick ARGB_4444 because it looks awful
14068                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
14069                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
14070                        case DRAWING_CACHE_QUALITY_AUTO:
14071                        case DRAWING_CACHE_QUALITY_LOW:
14072                        case DRAWING_CACHE_QUALITY_HIGH:
14073                        default:
14074                            quality = Bitmap.Config.ARGB_8888;
14075                            break;
14076                    }
14077                } else {
14078                    // Optimization for translucent windows
14079                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
14080                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
14081                }
14082
14083                // Try to cleanup memory
14084                if (bitmap != null) bitmap.recycle();
14085
14086                try {
14087                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14088                            width, height, quality);
14089                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
14090                    if (autoScale) {
14091                        mDrawingCache = bitmap;
14092                    } else {
14093                        mUnscaledDrawingCache = bitmap;
14094                    }
14095                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
14096                } catch (OutOfMemoryError e) {
14097                    // If there is not enough memory to create the bitmap cache, just
14098                    // ignore the issue as bitmap caches are not required to draw the
14099                    // view hierarchy
14100                    if (autoScale) {
14101                        mDrawingCache = null;
14102                    } else {
14103                        mUnscaledDrawingCache = null;
14104                    }
14105                    mCachingFailed = true;
14106                    return;
14107                }
14108
14109                clear = drawingCacheBackgroundColor != 0;
14110            }
14111
14112            Canvas canvas;
14113            if (attachInfo != null) {
14114                canvas = attachInfo.mCanvas;
14115                if (canvas == null) {
14116                    canvas = new Canvas();
14117                }
14118                canvas.setBitmap(bitmap);
14119                // Temporarily clobber the cached Canvas in case one of our children
14120                // is also using a drawing cache. Without this, the children would
14121                // steal the canvas by attaching their own bitmap to it and bad, bad
14122                // thing would happen (invisible views, corrupted drawings, etc.)
14123                attachInfo.mCanvas = null;
14124            } else {
14125                // This case should hopefully never or seldom happen
14126                canvas = new Canvas(bitmap);
14127            }
14128
14129            if (clear) {
14130                bitmap.eraseColor(drawingCacheBackgroundColor);
14131            }
14132
14133            computeScroll();
14134            final int restoreCount = canvas.save();
14135
14136            if (autoScale && scalingRequired) {
14137                final float scale = attachInfo.mApplicationScale;
14138                canvas.scale(scale, scale);
14139            }
14140
14141            canvas.translate(-mScrollX, -mScrollY);
14142
14143            mPrivateFlags |= PFLAG_DRAWN;
14144            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
14145                    mLayerType != LAYER_TYPE_NONE) {
14146                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
14147            }
14148
14149            // Fast path for layouts with no backgrounds
14150            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14151                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14152                dispatchDraw(canvas);
14153                if (mOverlay != null && !mOverlay.isEmpty()) {
14154                    mOverlay.getOverlayView().draw(canvas);
14155                }
14156            } else {
14157                draw(canvas);
14158            }
14159            drawAccessibilityFocus(canvas);
14160
14161            canvas.restoreToCount(restoreCount);
14162            canvas.setBitmap(null);
14163
14164            if (attachInfo != null) {
14165                // Restore the cached Canvas for our siblings
14166                attachInfo.mCanvas = canvas;
14167            }
14168        }
14169    }
14170
14171    /**
14172     * Create a snapshot of the view into a bitmap.  We should probably make
14173     * some form of this public, but should think about the API.
14174     */
14175    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
14176        int width = mRight - mLeft;
14177        int height = mBottom - mTop;
14178
14179        final AttachInfo attachInfo = mAttachInfo;
14180        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
14181        width = (int) ((width * scale) + 0.5f);
14182        height = (int) ((height * scale) + 0.5f);
14183
14184        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
14185                width > 0 ? width : 1, height > 0 ? height : 1, quality);
14186        if (bitmap == null) {
14187            throw new OutOfMemoryError();
14188        }
14189
14190        Resources resources = getResources();
14191        if (resources != null) {
14192            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
14193        }
14194
14195        Canvas canvas;
14196        if (attachInfo != null) {
14197            canvas = attachInfo.mCanvas;
14198            if (canvas == null) {
14199                canvas = new Canvas();
14200            }
14201            canvas.setBitmap(bitmap);
14202            // Temporarily clobber the cached Canvas in case one of our children
14203            // is also using a drawing cache. Without this, the children would
14204            // steal the canvas by attaching their own bitmap to it and bad, bad
14205            // things would happen (invisible views, corrupted drawings, etc.)
14206            attachInfo.mCanvas = null;
14207        } else {
14208            // This case should hopefully never or seldom happen
14209            canvas = new Canvas(bitmap);
14210        }
14211
14212        if ((backgroundColor & 0xff000000) != 0) {
14213            bitmap.eraseColor(backgroundColor);
14214        }
14215
14216        computeScroll();
14217        final int restoreCount = canvas.save();
14218        canvas.scale(scale, scale);
14219        canvas.translate(-mScrollX, -mScrollY);
14220
14221        // Temporarily remove the dirty mask
14222        int flags = mPrivateFlags;
14223        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14224
14225        // Fast path for layouts with no backgrounds
14226        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14227            dispatchDraw(canvas);
14228            if (mOverlay != null && !mOverlay.isEmpty()) {
14229                mOverlay.getOverlayView().draw(canvas);
14230            }
14231        } else {
14232            draw(canvas);
14233        }
14234        drawAccessibilityFocus(canvas);
14235
14236        mPrivateFlags = flags;
14237
14238        canvas.restoreToCount(restoreCount);
14239        canvas.setBitmap(null);
14240
14241        if (attachInfo != null) {
14242            // Restore the cached Canvas for our siblings
14243            attachInfo.mCanvas = canvas;
14244        }
14245
14246        return bitmap;
14247    }
14248
14249    /**
14250     * Indicates whether this View is currently in edit mode. A View is usually
14251     * in edit mode when displayed within a developer tool. For instance, if
14252     * this View is being drawn by a visual user interface builder, this method
14253     * should return true.
14254     *
14255     * Subclasses should check the return value of this method to provide
14256     * different behaviors if their normal behavior might interfere with the
14257     * host environment. For instance: the class spawns a thread in its
14258     * constructor, the drawing code relies on device-specific features, etc.
14259     *
14260     * This method is usually checked in the drawing code of custom widgets.
14261     *
14262     * @return True if this View is in edit mode, false otherwise.
14263     */
14264    public boolean isInEditMode() {
14265        return false;
14266    }
14267
14268    /**
14269     * If the View draws content inside its padding and enables fading edges,
14270     * it needs to support padding offsets. Padding offsets are added to the
14271     * fading edges to extend the length of the fade so that it covers pixels
14272     * drawn inside the padding.
14273     *
14274     * Subclasses of this class should override this method if they need
14275     * to draw content inside the padding.
14276     *
14277     * @return True if padding offset must be applied, false otherwise.
14278     *
14279     * @see #getLeftPaddingOffset()
14280     * @see #getRightPaddingOffset()
14281     * @see #getTopPaddingOffset()
14282     * @see #getBottomPaddingOffset()
14283     *
14284     * @since CURRENT
14285     */
14286    protected boolean isPaddingOffsetRequired() {
14287        return false;
14288    }
14289
14290    /**
14291     * Amount by which to extend the left fading region. Called only when
14292     * {@link #isPaddingOffsetRequired()} returns true.
14293     *
14294     * @return The left padding offset in pixels.
14295     *
14296     * @see #isPaddingOffsetRequired()
14297     *
14298     * @since CURRENT
14299     */
14300    protected int getLeftPaddingOffset() {
14301        return 0;
14302    }
14303
14304    /**
14305     * Amount by which to extend the right fading region. Called only when
14306     * {@link #isPaddingOffsetRequired()} returns true.
14307     *
14308     * @return The right padding offset in pixels.
14309     *
14310     * @see #isPaddingOffsetRequired()
14311     *
14312     * @since CURRENT
14313     */
14314    protected int getRightPaddingOffset() {
14315        return 0;
14316    }
14317
14318    /**
14319     * Amount by which to extend the top fading region. Called only when
14320     * {@link #isPaddingOffsetRequired()} returns true.
14321     *
14322     * @return The top padding offset in pixels.
14323     *
14324     * @see #isPaddingOffsetRequired()
14325     *
14326     * @since CURRENT
14327     */
14328    protected int getTopPaddingOffset() {
14329        return 0;
14330    }
14331
14332    /**
14333     * Amount by which to extend the bottom fading region. Called only when
14334     * {@link #isPaddingOffsetRequired()} returns true.
14335     *
14336     * @return The bottom padding offset in pixels.
14337     *
14338     * @see #isPaddingOffsetRequired()
14339     *
14340     * @since CURRENT
14341     */
14342    protected int getBottomPaddingOffset() {
14343        return 0;
14344    }
14345
14346    /**
14347     * @hide
14348     * @param offsetRequired
14349     */
14350    protected int getFadeTop(boolean offsetRequired) {
14351        int top = mPaddingTop;
14352        if (offsetRequired) top += getTopPaddingOffset();
14353        return top;
14354    }
14355
14356    /**
14357     * @hide
14358     * @param offsetRequired
14359     */
14360    protected int getFadeHeight(boolean offsetRequired) {
14361        int padding = mPaddingTop;
14362        if (offsetRequired) padding += getTopPaddingOffset();
14363        return mBottom - mTop - mPaddingBottom - padding;
14364    }
14365
14366    /**
14367     * <p>Indicates whether this view is attached to a hardware accelerated
14368     * window or not.</p>
14369     *
14370     * <p>Even if this method returns true, it does not mean that every call
14371     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
14372     * accelerated {@link android.graphics.Canvas}. For instance, if this view
14373     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
14374     * window is hardware accelerated,
14375     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
14376     * return false, and this method will return true.</p>
14377     *
14378     * @return True if the view is attached to a window and the window is
14379     *         hardware accelerated; false in any other case.
14380     */
14381    @ViewDebug.ExportedProperty(category = "drawing")
14382    public boolean isHardwareAccelerated() {
14383        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14384    }
14385
14386    /**
14387     * Sets a rectangular area on this view to which the view will be clipped
14388     * when it is drawn. Setting the value to null will remove the clip bounds
14389     * and the view will draw normally, using its full bounds.
14390     *
14391     * @param clipBounds The rectangular area, in the local coordinates of
14392     * this view, to which future drawing operations will be clipped.
14393     */
14394    public void setClipBounds(Rect clipBounds) {
14395        if (clipBounds != null) {
14396            if (clipBounds.equals(mClipBounds)) {
14397                return;
14398            }
14399            if (mClipBounds == null) {
14400                invalidate();
14401                mClipBounds = new Rect(clipBounds);
14402            } else {
14403                invalidate(Math.min(mClipBounds.left, clipBounds.left),
14404                        Math.min(mClipBounds.top, clipBounds.top),
14405                        Math.max(mClipBounds.right, clipBounds.right),
14406                        Math.max(mClipBounds.bottom, clipBounds.bottom));
14407                mClipBounds.set(clipBounds);
14408            }
14409        } else {
14410            if (mClipBounds != null) {
14411                invalidate();
14412                mClipBounds = null;
14413            }
14414        }
14415        mRenderNode.setClipBounds(mClipBounds);
14416    }
14417
14418    /**
14419     * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}.
14420     *
14421     * @return A copy of the current clip bounds if clip bounds are set,
14422     * otherwise null.
14423     */
14424    public Rect getClipBounds() {
14425        return (mClipBounds != null) ? new Rect(mClipBounds) : null;
14426    }
14427
14428    /**
14429     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
14430     * case of an active Animation being run on the view.
14431     */
14432    private boolean drawAnimation(ViewGroup parent, long drawingTime,
14433            Animation a, boolean scalingRequired) {
14434        Transformation invalidationTransform;
14435        final int flags = parent.mGroupFlags;
14436        final boolean initialized = a.isInitialized();
14437        if (!initialized) {
14438            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
14439            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
14440            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
14441            onAnimationStart();
14442        }
14443
14444        final Transformation t = parent.getChildTransformation();
14445        boolean more = a.getTransformation(drawingTime, t, 1f);
14446        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
14447            if (parent.mInvalidationTransformation == null) {
14448                parent.mInvalidationTransformation = new Transformation();
14449            }
14450            invalidationTransform = parent.mInvalidationTransformation;
14451            a.getTransformation(drawingTime, invalidationTransform, 1f);
14452        } else {
14453            invalidationTransform = t;
14454        }
14455
14456        if (more) {
14457            if (!a.willChangeBounds()) {
14458                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
14459                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
14460                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
14461                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
14462                    // The child need to draw an animation, potentially offscreen, so
14463                    // make sure we do not cancel invalidate requests
14464                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14465                    parent.invalidate(mLeft, mTop, mRight, mBottom);
14466                }
14467            } else {
14468                if (parent.mInvalidateRegion == null) {
14469                    parent.mInvalidateRegion = new RectF();
14470                }
14471                final RectF region = parent.mInvalidateRegion;
14472                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
14473                        invalidationTransform);
14474
14475                // The child need to draw an animation, potentially offscreen, so
14476                // make sure we do not cancel invalidate requests
14477                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
14478
14479                final int left = mLeft + (int) region.left;
14480                final int top = mTop + (int) region.top;
14481                parent.invalidate(left, top, left + (int) (region.width() + .5f),
14482                        top + (int) (region.height() + .5f));
14483            }
14484        }
14485        return more;
14486    }
14487
14488    /**
14489     * This method is called by getDisplayList() when a display list is recorded for a View.
14490     * It pushes any properties to the RenderNode that aren't managed by the RenderNode.
14491     */
14492    void setDisplayListProperties(RenderNode renderNode) {
14493        if (renderNode != null) {
14494            renderNode.setHasOverlappingRendering(hasOverlappingRendering());
14495            if (mParent instanceof ViewGroup) {
14496                renderNode.setClipToBounds(
14497                        (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
14498            }
14499            float alpha = 1;
14500            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
14501                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14502                ViewGroup parentVG = (ViewGroup) mParent;
14503                final Transformation t = parentVG.getChildTransformation();
14504                if (parentVG.getChildStaticTransformation(this, t)) {
14505                    final int transformType = t.getTransformationType();
14506                    if (transformType != Transformation.TYPE_IDENTITY) {
14507                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
14508                            alpha = t.getAlpha();
14509                        }
14510                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
14511                            renderNode.setStaticMatrix(t.getMatrix());
14512                        }
14513                    }
14514                }
14515            }
14516            if (mTransformationInfo != null) {
14517                alpha *= getFinalAlpha();
14518                if (alpha < 1) {
14519                    final int multipliedAlpha = (int) (255 * alpha);
14520                    if (onSetAlpha(multipliedAlpha)) {
14521                        alpha = 1;
14522                    }
14523                }
14524                renderNode.setAlpha(alpha);
14525            } else if (alpha < 1) {
14526                renderNode.setAlpha(alpha);
14527            }
14528        }
14529    }
14530
14531    /**
14532     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
14533     * This draw() method is an implementation detail and is not intended to be overridden or
14534     * to be called from anywhere else other than ViewGroup.drawChild().
14535     */
14536    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
14537        boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
14538        boolean more = false;
14539        final boolean childHasIdentityMatrix = hasIdentityMatrix();
14540        final int flags = parent.mGroupFlags;
14541
14542        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
14543            parent.getChildTransformation().clear();
14544            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14545        }
14546
14547        Transformation transformToApply = null;
14548        boolean concatMatrix = false;
14549
14550        boolean scalingRequired = false;
14551        boolean caching;
14552        int layerType = getLayerType();
14553
14554        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
14555        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
14556                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
14557            caching = true;
14558            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
14559            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
14560        } else {
14561            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
14562        }
14563
14564        final Animation a = getAnimation();
14565        if (a != null) {
14566            more = drawAnimation(parent, drawingTime, a, scalingRequired);
14567            concatMatrix = a.willChangeTransformationMatrix();
14568            if (concatMatrix) {
14569                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14570            }
14571            transformToApply = parent.getChildTransformation();
14572        } else {
14573            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) {
14574                // No longer animating: clear out old animation matrix
14575                mRenderNode.setAnimationMatrix(null);
14576                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
14577            }
14578            if (!usingRenderNodeProperties &&
14579                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
14580                final Transformation t = parent.getChildTransformation();
14581                final boolean hasTransform = parent.getChildStaticTransformation(this, t);
14582                if (hasTransform) {
14583                    final int transformType = t.getTransformationType();
14584                    transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null;
14585                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
14586                }
14587            }
14588        }
14589
14590        concatMatrix |= !childHasIdentityMatrix;
14591
14592        // Sets the flag as early as possible to allow draw() implementations
14593        // to call invalidate() successfully when doing animations
14594        mPrivateFlags |= PFLAG_DRAWN;
14595
14596        if (!concatMatrix &&
14597                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
14598                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
14599                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
14600                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
14601            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
14602            return more;
14603        }
14604        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
14605
14606        if (hardwareAccelerated) {
14607            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
14608            // retain the flag's value temporarily in the mRecreateDisplayList flag
14609            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
14610            mPrivateFlags &= ~PFLAG_INVALIDATED;
14611        }
14612
14613        RenderNode renderNode = null;
14614        Bitmap cache = null;
14615        boolean hasDisplayList = false;
14616        if (caching) {
14617            if (!hardwareAccelerated) {
14618                if (layerType != LAYER_TYPE_NONE) {
14619                    layerType = LAYER_TYPE_SOFTWARE;
14620                    buildDrawingCache(true);
14621                }
14622                cache = getDrawingCache(true);
14623            } else {
14624                switch (layerType) {
14625                    case LAYER_TYPE_SOFTWARE:
14626                        if (usingRenderNodeProperties) {
14627                            hasDisplayList = canHaveDisplayList();
14628                        } else {
14629                            buildDrawingCache(true);
14630                            cache = getDrawingCache(true);
14631                        }
14632                        break;
14633                    case LAYER_TYPE_HARDWARE:
14634                        if (usingRenderNodeProperties) {
14635                            hasDisplayList = canHaveDisplayList();
14636                        }
14637                        break;
14638                    case LAYER_TYPE_NONE:
14639                        // Delay getting the display list until animation-driven alpha values are
14640                        // set up and possibly passed on to the view
14641                        hasDisplayList = canHaveDisplayList();
14642                        break;
14643                }
14644            }
14645        }
14646        usingRenderNodeProperties &= hasDisplayList;
14647        if (usingRenderNodeProperties) {
14648            renderNode = getDisplayList();
14649            if (!renderNode.isValid()) {
14650                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14651                // to getDisplayList(), the display list will be marked invalid and we should not
14652                // try to use it again.
14653                renderNode = null;
14654                hasDisplayList = false;
14655                usingRenderNodeProperties = false;
14656            }
14657        }
14658
14659        int sx = 0;
14660        int sy = 0;
14661        if (!hasDisplayList) {
14662            computeScroll();
14663            sx = mScrollX;
14664            sy = mScrollY;
14665        }
14666
14667        final boolean hasNoCache = cache == null || hasDisplayList;
14668        final boolean offsetForScroll = cache == null && !hasDisplayList &&
14669                layerType != LAYER_TYPE_HARDWARE;
14670
14671        int restoreTo = -1;
14672        if (!usingRenderNodeProperties || transformToApply != null) {
14673            restoreTo = canvas.save();
14674        }
14675        if (offsetForScroll) {
14676            canvas.translate(mLeft - sx, mTop - sy);
14677        } else {
14678            if (!usingRenderNodeProperties) {
14679                canvas.translate(mLeft, mTop);
14680            }
14681            if (scalingRequired) {
14682                if (usingRenderNodeProperties) {
14683                    // TODO: Might not need this if we put everything inside the DL
14684                    restoreTo = canvas.save();
14685                }
14686                // mAttachInfo cannot be null, otherwise scalingRequired == false
14687                final float scale = 1.0f / mAttachInfo.mApplicationScale;
14688                canvas.scale(scale, scale);
14689            }
14690        }
14691
14692        float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha());
14693        if (transformToApply != null || alpha < 1 ||  !hasIdentityMatrix() ||
14694                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14695            if (transformToApply != null || !childHasIdentityMatrix) {
14696                int transX = 0;
14697                int transY = 0;
14698
14699                if (offsetForScroll) {
14700                    transX = -sx;
14701                    transY = -sy;
14702                }
14703
14704                if (transformToApply != null) {
14705                    if (concatMatrix) {
14706                        if (usingRenderNodeProperties) {
14707                            renderNode.setAnimationMatrix(transformToApply.getMatrix());
14708                        } else {
14709                            // Undo the scroll translation, apply the transformation matrix,
14710                            // then redo the scroll translate to get the correct result.
14711                            canvas.translate(-transX, -transY);
14712                            canvas.concat(transformToApply.getMatrix());
14713                            canvas.translate(transX, transY);
14714                        }
14715                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14716                    }
14717
14718                    float transformAlpha = transformToApply.getAlpha();
14719                    if (transformAlpha < 1) {
14720                        alpha *= transformAlpha;
14721                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14722                    }
14723                }
14724
14725                if (!childHasIdentityMatrix && !usingRenderNodeProperties) {
14726                    canvas.translate(-transX, -transY);
14727                    canvas.concat(getMatrix());
14728                    canvas.translate(transX, transY);
14729                }
14730            }
14731
14732            // Deal with alpha if it is or used to be <1
14733            if (alpha < 1 ||
14734                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
14735                if (alpha < 1) {
14736                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14737                } else {
14738                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
14739                }
14740                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
14741                if (hasNoCache) {
14742                    final int multipliedAlpha = (int) (255 * alpha);
14743                    if (!onSetAlpha(multipliedAlpha)) {
14744                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
14745                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
14746                                layerType != LAYER_TYPE_NONE) {
14747                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
14748                        }
14749                        if (usingRenderNodeProperties) {
14750                            renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
14751                        } else  if (layerType == LAYER_TYPE_NONE) {
14752                            final int scrollX = hasDisplayList ? 0 : sx;
14753                            final int scrollY = hasDisplayList ? 0 : sy;
14754                            canvas.saveLayerAlpha(scrollX, scrollY,
14755                                    scrollX + (mRight - mLeft), scrollY + (mBottom - mTop),
14756                                    multipliedAlpha, layerFlags);
14757                        }
14758                    } else {
14759                        // Alpha is handled by the child directly, clobber the layer's alpha
14760                        mPrivateFlags |= PFLAG_ALPHA_SET;
14761                    }
14762                }
14763            }
14764        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14765            onSetAlpha(255);
14766            mPrivateFlags &= ~PFLAG_ALPHA_SET;
14767        }
14768
14769        if (!usingRenderNodeProperties) {
14770            // apply clips directly, since RenderNode won't do it for this draw
14771            if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN
14772                    && cache == null) {
14773                if (offsetForScroll) {
14774                    canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
14775                } else {
14776                    if (!scalingRequired || cache == null) {
14777                        canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
14778                    } else {
14779                        canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
14780                    }
14781                }
14782            }
14783
14784            if (mClipBounds != null) {
14785                // clip bounds ignore scroll
14786                canvas.clipRect(mClipBounds);
14787            }
14788        }
14789
14790
14791
14792        if (!usingRenderNodeProperties && hasDisplayList) {
14793            renderNode = getDisplayList();
14794            if (!renderNode.isValid()) {
14795                // Uncommon, but possible. If a view is removed from the hierarchy during the call
14796                // to getDisplayList(), the display list will be marked invalid and we should not
14797                // try to use it again.
14798                renderNode = null;
14799                hasDisplayList = false;
14800            }
14801        }
14802
14803        if (hasNoCache) {
14804            boolean layerRendered = false;
14805            if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) {
14806                final HardwareLayer layer = getHardwareLayer();
14807                if (layer != null && layer.isValid()) {
14808                    int restoreAlpha = mLayerPaint.getAlpha();
14809                    mLayerPaint.setAlpha((int) (alpha * 255));
14810                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
14811                    mLayerPaint.setAlpha(restoreAlpha);
14812                    layerRendered = true;
14813                } else {
14814                    final int scrollX = hasDisplayList ? 0 : sx;
14815                    final int scrollY = hasDisplayList ? 0 : sy;
14816                    canvas.saveLayer(scrollX, scrollY,
14817                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
14818                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
14819                }
14820            }
14821
14822            if (!layerRendered) {
14823                if (!hasDisplayList) {
14824                    // Fast path for layouts with no backgrounds
14825                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
14826                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14827                        dispatchDraw(canvas);
14828                        if (mOverlay != null && !mOverlay.isEmpty()) {
14829                            mOverlay.getOverlayView().draw(canvas);
14830                        }
14831                    } else {
14832                        draw(canvas);
14833                    }
14834                    drawAccessibilityFocus(canvas);
14835                } else {
14836                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14837                    ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags);
14838                }
14839            }
14840        } else if (cache != null) {
14841            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
14842            Paint cachePaint;
14843            int restoreAlpha = 0;
14844
14845            if (layerType == LAYER_TYPE_NONE) {
14846                cachePaint = parent.mCachePaint;
14847                if (cachePaint == null) {
14848                    cachePaint = new Paint();
14849                    cachePaint.setDither(false);
14850                    parent.mCachePaint = cachePaint;
14851                }
14852            } else {
14853                cachePaint = mLayerPaint;
14854                restoreAlpha = mLayerPaint.getAlpha();
14855            }
14856            cachePaint.setAlpha((int) (alpha * 255));
14857            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
14858            cachePaint.setAlpha(restoreAlpha);
14859        }
14860
14861        if (restoreTo >= 0) {
14862            canvas.restoreToCount(restoreTo);
14863        }
14864
14865        if (a != null && !more) {
14866            if (!hardwareAccelerated && !a.getFillAfter()) {
14867                onSetAlpha(255);
14868            }
14869            parent.finishAnimatingView(this, a);
14870        }
14871
14872        if (more && hardwareAccelerated) {
14873            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
14874                // alpha animations should cause the child to recreate its display list
14875                invalidate(true);
14876            }
14877        }
14878
14879        mRecreateDisplayList = false;
14880
14881        return more;
14882    }
14883
14884    /**
14885     * Manually render this view (and all of its children) to the given Canvas.
14886     * The view must have already done a full layout before this function is
14887     * called.  When implementing a view, implement
14888     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
14889     * If you do need to override this method, call the superclass version.
14890     *
14891     * @param canvas The Canvas to which the View is rendered.
14892     */
14893    public void draw(Canvas canvas) {
14894        final int privateFlags = mPrivateFlags;
14895        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
14896                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
14897        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
14898
14899        /*
14900         * Draw traversal performs several drawing steps which must be executed
14901         * in the appropriate order:
14902         *
14903         *      1. Draw the background
14904         *      2. If necessary, save the canvas' layers to prepare for fading
14905         *      3. Draw view's content
14906         *      4. Draw children
14907         *      5. If necessary, draw the fading edges and restore layers
14908         *      6. Draw decorations (scrollbars for instance)
14909         */
14910
14911        // Step 1, draw the background, if needed
14912        int saveCount;
14913
14914        if (!dirtyOpaque) {
14915            drawBackground(canvas);
14916        }
14917
14918        // skip step 2 & 5 if possible (common case)
14919        final int viewFlags = mViewFlags;
14920        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
14921        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
14922        if (!verticalEdges && !horizontalEdges) {
14923            // Step 3, draw the content
14924            if (!dirtyOpaque) onDraw(canvas);
14925
14926            // Step 4, draw the children
14927            dispatchDraw(canvas);
14928
14929            // Step 6, draw decorations (scrollbars)
14930            onDrawScrollBars(canvas);
14931
14932            if (mOverlay != null && !mOverlay.isEmpty()) {
14933                mOverlay.getOverlayView().dispatchDraw(canvas);
14934            }
14935
14936            // we're done...
14937            return;
14938        }
14939
14940        /*
14941         * Here we do the full fledged routine...
14942         * (this is an uncommon case where speed matters less,
14943         * this is why we repeat some of the tests that have been
14944         * done above)
14945         */
14946
14947        boolean drawTop = false;
14948        boolean drawBottom = false;
14949        boolean drawLeft = false;
14950        boolean drawRight = false;
14951
14952        float topFadeStrength = 0.0f;
14953        float bottomFadeStrength = 0.0f;
14954        float leftFadeStrength = 0.0f;
14955        float rightFadeStrength = 0.0f;
14956
14957        // Step 2, save the canvas' layers
14958        int paddingLeft = mPaddingLeft;
14959
14960        final boolean offsetRequired = isPaddingOffsetRequired();
14961        if (offsetRequired) {
14962            paddingLeft += getLeftPaddingOffset();
14963        }
14964
14965        int left = mScrollX + paddingLeft;
14966        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
14967        int top = mScrollY + getFadeTop(offsetRequired);
14968        int bottom = top + getFadeHeight(offsetRequired);
14969
14970        if (offsetRequired) {
14971            right += getRightPaddingOffset();
14972            bottom += getBottomPaddingOffset();
14973        }
14974
14975        final ScrollabilityCache scrollabilityCache = mScrollCache;
14976        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
14977        int length = (int) fadeHeight;
14978
14979        // clip the fade length if top and bottom fades overlap
14980        // overlapping fades produce odd-looking artifacts
14981        if (verticalEdges && (top + length > bottom - length)) {
14982            length = (bottom - top) / 2;
14983        }
14984
14985        // also clip horizontal fades if necessary
14986        if (horizontalEdges && (left + length > right - length)) {
14987            length = (right - left) / 2;
14988        }
14989
14990        if (verticalEdges) {
14991            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
14992            drawTop = topFadeStrength * fadeHeight > 1.0f;
14993            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
14994            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
14995        }
14996
14997        if (horizontalEdges) {
14998            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
14999            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
15000            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
15001            drawRight = rightFadeStrength * fadeHeight > 1.0f;
15002        }
15003
15004        saveCount = canvas.getSaveCount();
15005
15006        int solidColor = getSolidColor();
15007        if (solidColor == 0) {
15008            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
15009
15010            if (drawTop) {
15011                canvas.saveLayer(left, top, right, top + length, null, flags);
15012            }
15013
15014            if (drawBottom) {
15015                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
15016            }
15017
15018            if (drawLeft) {
15019                canvas.saveLayer(left, top, left + length, bottom, null, flags);
15020            }
15021
15022            if (drawRight) {
15023                canvas.saveLayer(right - length, top, right, bottom, null, flags);
15024            }
15025        } else {
15026            scrollabilityCache.setFadeColor(solidColor);
15027        }
15028
15029        // Step 3, draw the content
15030        if (!dirtyOpaque) onDraw(canvas);
15031
15032        // Step 4, draw the children
15033        dispatchDraw(canvas);
15034
15035        // Step 5, draw the fade effect and restore layers
15036        final Paint p = scrollabilityCache.paint;
15037        final Matrix matrix = scrollabilityCache.matrix;
15038        final Shader fade = scrollabilityCache.shader;
15039
15040        if (drawTop) {
15041            matrix.setScale(1, fadeHeight * topFadeStrength);
15042            matrix.postTranslate(left, top);
15043            fade.setLocalMatrix(matrix);
15044            p.setShader(fade);
15045            canvas.drawRect(left, top, right, top + length, p);
15046        }
15047
15048        if (drawBottom) {
15049            matrix.setScale(1, fadeHeight * bottomFadeStrength);
15050            matrix.postRotate(180);
15051            matrix.postTranslate(left, bottom);
15052            fade.setLocalMatrix(matrix);
15053            p.setShader(fade);
15054            canvas.drawRect(left, bottom - length, right, bottom, p);
15055        }
15056
15057        if (drawLeft) {
15058            matrix.setScale(1, fadeHeight * leftFadeStrength);
15059            matrix.postRotate(-90);
15060            matrix.postTranslate(left, top);
15061            fade.setLocalMatrix(matrix);
15062            p.setShader(fade);
15063            canvas.drawRect(left, top, left + length, bottom, p);
15064        }
15065
15066        if (drawRight) {
15067            matrix.setScale(1, fadeHeight * rightFadeStrength);
15068            matrix.postRotate(90);
15069            matrix.postTranslate(right, top);
15070            fade.setLocalMatrix(matrix);
15071            p.setShader(fade);
15072            canvas.drawRect(right - length, top, right, bottom, p);
15073        }
15074
15075        canvas.restoreToCount(saveCount);
15076
15077        // Step 6, draw decorations (scrollbars)
15078        onDrawScrollBars(canvas);
15079
15080        if (mOverlay != null && !mOverlay.isEmpty()) {
15081            mOverlay.getOverlayView().dispatchDraw(canvas);
15082        }
15083    }
15084
15085    /**
15086     * Draws the accessibility focus rect onto the specified canvas.
15087     *
15088     * @param canvas Canvas on which to draw the focus rect
15089     */
15090    private void drawAccessibilityFocus(Canvas canvas) {
15091        if (mAttachInfo == null) {
15092            return;
15093        }
15094
15095        final Rect bounds = mAttachInfo.mTmpInvalRect;
15096        final ViewRootImpl viewRoot = getViewRootImpl();
15097        if (viewRoot == null || viewRoot.getAccessibilityFocusedHost() != this) {
15098            return;
15099        }
15100
15101        final AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
15102        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
15103            return;
15104        }
15105
15106        final Drawable drawable = viewRoot.getAccessibilityFocusedDrawable();
15107        if (drawable == null) {
15108            return;
15109        }
15110
15111        final AccessibilityNodeInfo virtualView = viewRoot.getAccessibilityFocusedVirtualView();
15112        if (virtualView != null) {
15113            virtualView.getBoundsInScreen(bounds);
15114            final int[] offset = mAttachInfo.mTmpLocation;
15115            getLocationOnScreen(offset);
15116            bounds.offset(-offset[0], -offset[1]);
15117        } else {
15118            bounds.set(0, 0, mRight - mLeft, mBottom - mTop);
15119        }
15120
15121        canvas.translate(mScrollX, mScrollY);
15122        drawable.setBounds(bounds);
15123        drawable.draw(canvas);
15124        canvas.translate(-mScrollX, -mScrollY);
15125    }
15126
15127    /**
15128     * Draws the background onto the specified canvas.
15129     *
15130     * @param canvas Canvas on which to draw the background
15131     */
15132    private void drawBackground(Canvas canvas) {
15133        final Drawable background = mBackground;
15134        if (background == null) {
15135            return;
15136        }
15137
15138        if (mBackgroundSizeChanged) {
15139            background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
15140            mBackgroundSizeChanged = false;
15141            invalidateOutline();
15142        }
15143
15144        // Attempt to use a display list if requested.
15145        if (canvas.isHardwareAccelerated() && mAttachInfo != null
15146                && mAttachInfo.mHardwareRenderer != null) {
15147            mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);
15148
15149            final RenderNode displayList = mBackgroundRenderNode;
15150            if (displayList != null && displayList.isValid()) {
15151                setBackgroundDisplayListProperties(displayList);
15152                ((HardwareCanvas) canvas).drawRenderNode(displayList);
15153                return;
15154            }
15155        }
15156
15157        final int scrollX = mScrollX;
15158        final int scrollY = mScrollY;
15159        if ((scrollX | scrollY) == 0) {
15160            background.draw(canvas);
15161        } else {
15162            canvas.translate(scrollX, scrollY);
15163            background.draw(canvas);
15164            canvas.translate(-scrollX, -scrollY);
15165        }
15166    }
15167
15168    /**
15169     * Set up background drawable display list properties.
15170     *
15171     * @param displayList Valid display list for the background drawable
15172     */
15173    private void setBackgroundDisplayListProperties(RenderNode displayList) {
15174        displayList.setTranslationX(mScrollX);
15175        displayList.setTranslationY(mScrollY);
15176    }
15177
15178    /**
15179     * Creates a new display list or updates the existing display list for the
15180     * specified Drawable.
15181     *
15182     * @param drawable Drawable for which to create a display list
15183     * @param renderNode Existing RenderNode, or {@code null}
15184     * @return A valid display list for the specified drawable
15185     */
15186    private static RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) {
15187        if (renderNode == null) {
15188            renderNode = RenderNode.create(drawable.getClass().getName());
15189        }
15190
15191        final Rect bounds = drawable.getBounds();
15192        final int width = bounds.width();
15193        final int height = bounds.height();
15194        final HardwareCanvas canvas = renderNode.start(width, height);
15195        try {
15196            drawable.draw(canvas);
15197        } finally {
15198            renderNode.end(canvas);
15199        }
15200
15201        // Set up drawable properties that are view-independent.
15202        renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom);
15203        renderNode.setProjectBackwards(drawable.isProjected());
15204        renderNode.setProjectionReceiver(true);
15205        renderNode.setClipToBounds(false);
15206        return renderNode;
15207    }
15208
15209    /**
15210     * Returns the overlay for this view, creating it if it does not yet exist.
15211     * Adding drawables to the overlay will cause them to be displayed whenever
15212     * the view itself is redrawn. Objects in the overlay should be actively
15213     * managed: remove them when they should not be displayed anymore. The
15214     * overlay will always have the same size as its host view.
15215     *
15216     * <p>Note: Overlays do not currently work correctly with {@link
15217     * SurfaceView} or {@link TextureView}; contents in overlays for these
15218     * types of views may not display correctly.</p>
15219     *
15220     * @return The ViewOverlay object for this view.
15221     * @see ViewOverlay
15222     */
15223    public ViewOverlay getOverlay() {
15224        if (mOverlay == null) {
15225            mOverlay = new ViewOverlay(mContext, this);
15226        }
15227        return mOverlay;
15228    }
15229
15230    /**
15231     * Override this if your view is known to always be drawn on top of a solid color background,
15232     * and needs to draw fading edges. Returning a non-zero color enables the view system to
15233     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
15234     * should be set to 0xFF.
15235     *
15236     * @see #setVerticalFadingEdgeEnabled(boolean)
15237     * @see #setHorizontalFadingEdgeEnabled(boolean)
15238     *
15239     * @return The known solid color background for this view, or 0 if the color may vary
15240     */
15241    @ViewDebug.ExportedProperty(category = "drawing")
15242    public int getSolidColor() {
15243        return 0;
15244    }
15245
15246    /**
15247     * Build a human readable string representation of the specified view flags.
15248     *
15249     * @param flags the view flags to convert to a string
15250     * @return a String representing the supplied flags
15251     */
15252    private static String printFlags(int flags) {
15253        String output = "";
15254        int numFlags = 0;
15255        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
15256            output += "TAKES_FOCUS";
15257            numFlags++;
15258        }
15259
15260        switch (flags & VISIBILITY_MASK) {
15261        case INVISIBLE:
15262            if (numFlags > 0) {
15263                output += " ";
15264            }
15265            output += "INVISIBLE";
15266            // USELESS HERE numFlags++;
15267            break;
15268        case GONE:
15269            if (numFlags > 0) {
15270                output += " ";
15271            }
15272            output += "GONE";
15273            // USELESS HERE numFlags++;
15274            break;
15275        default:
15276            break;
15277        }
15278        return output;
15279    }
15280
15281    /**
15282     * Build a human readable string representation of the specified private
15283     * view flags.
15284     *
15285     * @param privateFlags the private view flags to convert to a string
15286     * @return a String representing the supplied flags
15287     */
15288    private static String printPrivateFlags(int privateFlags) {
15289        String output = "";
15290        int numFlags = 0;
15291
15292        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
15293            output += "WANTS_FOCUS";
15294            numFlags++;
15295        }
15296
15297        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
15298            if (numFlags > 0) {
15299                output += " ";
15300            }
15301            output += "FOCUSED";
15302            numFlags++;
15303        }
15304
15305        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
15306            if (numFlags > 0) {
15307                output += " ";
15308            }
15309            output += "SELECTED";
15310            numFlags++;
15311        }
15312
15313        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
15314            if (numFlags > 0) {
15315                output += " ";
15316            }
15317            output += "IS_ROOT_NAMESPACE";
15318            numFlags++;
15319        }
15320
15321        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
15322            if (numFlags > 0) {
15323                output += " ";
15324            }
15325            output += "HAS_BOUNDS";
15326            numFlags++;
15327        }
15328
15329        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
15330            if (numFlags > 0) {
15331                output += " ";
15332            }
15333            output += "DRAWN";
15334            // USELESS HERE numFlags++;
15335        }
15336        return output;
15337    }
15338
15339    /**
15340     * <p>Indicates whether or not this view's layout will be requested during
15341     * the next hierarchy layout pass.</p>
15342     *
15343     * @return true if the layout will be forced during next layout pass
15344     */
15345    public boolean isLayoutRequested() {
15346        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
15347    }
15348
15349    /**
15350     * Return true if o is a ViewGroup that is laying out using optical bounds.
15351     * @hide
15352     */
15353    public static boolean isLayoutModeOptical(Object o) {
15354        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
15355    }
15356
15357    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
15358        Insets parentInsets = mParent instanceof View ?
15359                ((View) mParent).getOpticalInsets() : Insets.NONE;
15360        Insets childInsets = getOpticalInsets();
15361        return setFrame(
15362                left   + parentInsets.left - childInsets.left,
15363                top    + parentInsets.top  - childInsets.top,
15364                right  + parentInsets.left + childInsets.right,
15365                bottom + parentInsets.top  + childInsets.bottom);
15366    }
15367
15368    /**
15369     * Assign a size and position to a view and all of its
15370     * descendants
15371     *
15372     * <p>This is the second phase of the layout mechanism.
15373     * (The first is measuring). In this phase, each parent calls
15374     * layout on all of its children to position them.
15375     * This is typically done using the child measurements
15376     * that were stored in the measure pass().</p>
15377     *
15378     * <p>Derived classes should not override this method.
15379     * Derived classes with children should override
15380     * onLayout. In that method, they should
15381     * call layout on each of their children.</p>
15382     *
15383     * @param l Left position, relative to parent
15384     * @param t Top position, relative to parent
15385     * @param r Right position, relative to parent
15386     * @param b Bottom position, relative to parent
15387     */
15388    @SuppressWarnings({"unchecked"})
15389    public void layout(int l, int t, int r, int b) {
15390        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
15391            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
15392            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
15393        }
15394
15395        int oldL = mLeft;
15396        int oldT = mTop;
15397        int oldB = mBottom;
15398        int oldR = mRight;
15399
15400        boolean changed = isLayoutModeOptical(mParent) ?
15401                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
15402
15403        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
15404            onLayout(changed, l, t, r, b);
15405            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
15406
15407            ListenerInfo li = mListenerInfo;
15408            if (li != null && li.mOnLayoutChangeListeners != null) {
15409                ArrayList<OnLayoutChangeListener> listenersCopy =
15410                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
15411                int numListeners = listenersCopy.size();
15412                for (int i = 0; i < numListeners; ++i) {
15413                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
15414                }
15415            }
15416        }
15417
15418        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
15419        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
15420    }
15421
15422    /**
15423     * Called from layout when this view should
15424     * assign a size and position to each of its children.
15425     *
15426     * Derived classes with children should override
15427     * this method and call layout on each of
15428     * their children.
15429     * @param changed This is a new size or position for this view
15430     * @param left Left position, relative to parent
15431     * @param top Top position, relative to parent
15432     * @param right Right position, relative to parent
15433     * @param bottom Bottom position, relative to parent
15434     */
15435    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
15436    }
15437
15438    /**
15439     * Assign a size and position to this view.
15440     *
15441     * This is called from layout.
15442     *
15443     * @param left Left position, relative to parent
15444     * @param top Top position, relative to parent
15445     * @param right Right position, relative to parent
15446     * @param bottom Bottom position, relative to parent
15447     * @return true if the new size and position are different than the
15448     *         previous ones
15449     * {@hide}
15450     */
15451    protected boolean setFrame(int left, int top, int right, int bottom) {
15452        boolean changed = false;
15453
15454        if (DBG) {
15455            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
15456                    + right + "," + bottom + ")");
15457        }
15458
15459        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
15460            changed = true;
15461
15462            // Remember our drawn bit
15463            int drawn = mPrivateFlags & PFLAG_DRAWN;
15464
15465            int oldWidth = mRight - mLeft;
15466            int oldHeight = mBottom - mTop;
15467            int newWidth = right - left;
15468            int newHeight = bottom - top;
15469            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
15470
15471            // Invalidate our old position
15472            invalidate(sizeChanged);
15473
15474            mLeft = left;
15475            mTop = top;
15476            mRight = right;
15477            mBottom = bottom;
15478            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
15479
15480            mPrivateFlags |= PFLAG_HAS_BOUNDS;
15481
15482
15483            if (sizeChanged) {
15484                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
15485            }
15486
15487            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
15488                // If we are visible, force the DRAWN bit to on so that
15489                // this invalidate will go through (at least to our parent).
15490                // This is because someone may have invalidated this view
15491                // before this call to setFrame came in, thereby clearing
15492                // the DRAWN bit.
15493                mPrivateFlags |= PFLAG_DRAWN;
15494                invalidate(sizeChanged);
15495                // parent display list may need to be recreated based on a change in the bounds
15496                // of any child
15497                invalidateParentCaches();
15498            }
15499
15500            // Reset drawn bit to original value (invalidate turns it off)
15501            mPrivateFlags |= drawn;
15502
15503            mBackgroundSizeChanged = true;
15504
15505            notifySubtreeAccessibilityStateChangedIfNeeded();
15506        }
15507        return changed;
15508    }
15509
15510    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
15511        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
15512        if (mOverlay != null) {
15513            mOverlay.getOverlayView().setRight(newWidth);
15514            mOverlay.getOverlayView().setBottom(newHeight);
15515        }
15516        invalidateOutline();
15517    }
15518
15519    /**
15520     * Finalize inflating a view from XML.  This is called as the last phase
15521     * of inflation, after all child views have been added.
15522     *
15523     * <p>Even if the subclass overrides onFinishInflate, they should always be
15524     * sure to call the super method, so that we get called.
15525     */
15526    protected void onFinishInflate() {
15527    }
15528
15529    /**
15530     * Returns the resources associated with this view.
15531     *
15532     * @return Resources object.
15533     */
15534    public Resources getResources() {
15535        return mResources;
15536    }
15537
15538    /**
15539     * Invalidates the specified Drawable.
15540     *
15541     * @param drawable the drawable to invalidate
15542     */
15543    @Override
15544    public void invalidateDrawable(@NonNull Drawable drawable) {
15545        if (verifyDrawable(drawable)) {
15546            final Rect dirty = drawable.getDirtyBounds();
15547            final int scrollX = mScrollX;
15548            final int scrollY = mScrollY;
15549
15550            invalidate(dirty.left + scrollX, dirty.top + scrollY,
15551                    dirty.right + scrollX, dirty.bottom + scrollY);
15552
15553            invalidateOutline();
15554        }
15555    }
15556
15557    /**
15558     * Schedules an action on a drawable to occur at a specified time.
15559     *
15560     * @param who the recipient of the action
15561     * @param what the action to run on the drawable
15562     * @param when the time at which the action must occur. Uses the
15563     *        {@link SystemClock#uptimeMillis} timebase.
15564     */
15565    @Override
15566    public void scheduleDrawable(Drawable who, Runnable what, long when) {
15567        if (verifyDrawable(who) && what != null) {
15568            final long delay = when - SystemClock.uptimeMillis();
15569            if (mAttachInfo != null) {
15570                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
15571                        Choreographer.CALLBACK_ANIMATION, what, who,
15572                        Choreographer.subtractFrameDelay(delay));
15573            } else {
15574                ViewRootImpl.getRunQueue().postDelayed(what, delay);
15575            }
15576        }
15577    }
15578
15579    /**
15580     * Cancels a scheduled action on a drawable.
15581     *
15582     * @param who the recipient of the action
15583     * @param what the action to cancel
15584     */
15585    @Override
15586    public void unscheduleDrawable(Drawable who, Runnable what) {
15587        if (verifyDrawable(who) && what != null) {
15588            if (mAttachInfo != null) {
15589                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15590                        Choreographer.CALLBACK_ANIMATION, what, who);
15591            }
15592            ViewRootImpl.getRunQueue().removeCallbacks(what);
15593        }
15594    }
15595
15596    /**
15597     * Unschedule any events associated with the given Drawable.  This can be
15598     * used when selecting a new Drawable into a view, so that the previous
15599     * one is completely unscheduled.
15600     *
15601     * @param who The Drawable to unschedule.
15602     *
15603     * @see #drawableStateChanged
15604     */
15605    public void unscheduleDrawable(Drawable who) {
15606        if (mAttachInfo != null && who != null) {
15607            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
15608                    Choreographer.CALLBACK_ANIMATION, null, who);
15609        }
15610    }
15611
15612    /**
15613     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
15614     * that the View directionality can and will be resolved before its Drawables.
15615     *
15616     * Will call {@link View#onResolveDrawables} when resolution is done.
15617     *
15618     * @hide
15619     */
15620    protected void resolveDrawables() {
15621        // Drawables resolution may need to happen before resolving the layout direction (which is
15622        // done only during the measure() call).
15623        // If the layout direction is not resolved yet, we cannot resolve the Drawables except in
15624        // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT.
15625        // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or
15626        // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout
15627        // direction to be resolved as its resolved value will be the same as its raw value.
15628        if (!isLayoutDirectionResolved() &&
15629                getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) {
15630            return;
15631        }
15632
15633        final int layoutDirection = isLayoutDirectionResolved() ?
15634                getLayoutDirection() : getRawLayoutDirection();
15635
15636        if (mBackground != null) {
15637            mBackground.setLayoutDirection(layoutDirection);
15638        }
15639        mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
15640        onResolveDrawables(layoutDirection);
15641    }
15642
15643    /**
15644     * Called when layout direction has been resolved.
15645     *
15646     * The default implementation does nothing.
15647     *
15648     * @param layoutDirection The resolved layout direction.
15649     *
15650     * @see #LAYOUT_DIRECTION_LTR
15651     * @see #LAYOUT_DIRECTION_RTL
15652     *
15653     * @hide
15654     */
15655    public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) {
15656    }
15657
15658    /**
15659     * @hide
15660     */
15661    protected void resetResolvedDrawables() {
15662        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
15663    }
15664
15665    private boolean isDrawablesResolved() {
15666        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
15667    }
15668
15669    /**
15670     * If your view subclass is displaying its own Drawable objects, it should
15671     * override this function and return true for any Drawable it is
15672     * displaying.  This allows animations for those drawables to be
15673     * scheduled.
15674     *
15675     * <p>Be sure to call through to the super class when overriding this
15676     * function.
15677     *
15678     * @param who The Drawable to verify.  Return true if it is one you are
15679     *            displaying, else return the result of calling through to the
15680     *            super class.
15681     *
15682     * @return boolean If true than the Drawable is being displayed in the
15683     *         view; else false and it is not allowed to animate.
15684     *
15685     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
15686     * @see #drawableStateChanged()
15687     */
15688    protected boolean verifyDrawable(Drawable who) {
15689        return who == mBackground;
15690    }
15691
15692    /**
15693     * This function is called whenever the state of the view changes in such
15694     * a way that it impacts the state of drawables being shown.
15695     * <p>
15696     * If the View has a StateListAnimator, it will also be called to run necessary state
15697     * change animations.
15698     * <p>
15699     * Be sure to call through to the superclass when overriding this function.
15700     *
15701     * @see Drawable#setState(int[])
15702     */
15703    protected void drawableStateChanged() {
15704        final Drawable d = mBackground;
15705        if (d != null && d.isStateful()) {
15706            d.setState(getDrawableState());
15707        }
15708
15709        if (mStateListAnimator != null) {
15710            mStateListAnimator.setState(getDrawableState());
15711        }
15712    }
15713
15714    /**
15715     * This function is called whenever the view hotspot changes and needs to
15716     * be propagated to drawables managed by the view.
15717     * <p>
15718     * Be sure to call through to the superclass when overriding this function.
15719     *
15720     * @param x hotspot x coordinate
15721     * @param y hotspot y coordinate
15722     */
15723    public void drawableHotspotChanged(float x, float y) {
15724        if (mBackground != null) {
15725            mBackground.setHotspot(x, y);
15726        }
15727    }
15728
15729    /**
15730     * Call this to force a view to update its drawable state. This will cause
15731     * drawableStateChanged to be called on this view. Views that are interested
15732     * in the new state should call getDrawableState.
15733     *
15734     * @see #drawableStateChanged
15735     * @see #getDrawableState
15736     */
15737    public void refreshDrawableState() {
15738        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
15739        drawableStateChanged();
15740
15741        ViewParent parent = mParent;
15742        if (parent != null) {
15743            parent.childDrawableStateChanged(this);
15744        }
15745    }
15746
15747    /**
15748     * Return an array of resource IDs of the drawable states representing the
15749     * current state of the view.
15750     *
15751     * @return The current drawable state
15752     *
15753     * @see Drawable#setState(int[])
15754     * @see #drawableStateChanged()
15755     * @see #onCreateDrawableState(int)
15756     */
15757    public final int[] getDrawableState() {
15758        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
15759            return mDrawableState;
15760        } else {
15761            mDrawableState = onCreateDrawableState(0);
15762            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
15763            return mDrawableState;
15764        }
15765    }
15766
15767    /**
15768     * Generate the new {@link android.graphics.drawable.Drawable} state for
15769     * this view. This is called by the view
15770     * system when the cached Drawable state is determined to be invalid.  To
15771     * retrieve the current state, you should use {@link #getDrawableState}.
15772     *
15773     * @param extraSpace if non-zero, this is the number of extra entries you
15774     * would like in the returned array in which you can place your own
15775     * states.
15776     *
15777     * @return Returns an array holding the current {@link Drawable} state of
15778     * the view.
15779     *
15780     * @see #mergeDrawableStates(int[], int[])
15781     */
15782    protected int[] onCreateDrawableState(int extraSpace) {
15783        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
15784                mParent instanceof View) {
15785            return ((View) mParent).onCreateDrawableState(extraSpace);
15786        }
15787
15788        int[] drawableState;
15789
15790        int privateFlags = mPrivateFlags;
15791
15792        int viewStateIndex = 0;
15793        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
15794        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
15795        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
15796        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
15797        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
15798        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
15799        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
15800                HardwareRenderer.isAvailable()) {
15801            // This is set if HW acceleration is requested, even if the current
15802            // process doesn't allow it.  This is just to allow app preview
15803            // windows to better match their app.
15804            viewStateIndex |= VIEW_STATE_ACCELERATED;
15805        }
15806        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
15807
15808        final int privateFlags2 = mPrivateFlags2;
15809        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
15810        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
15811
15812        drawableState = VIEW_STATE_SETS[viewStateIndex];
15813
15814        //noinspection ConstantIfStatement
15815        if (false) {
15816            Log.i("View", "drawableStateIndex=" + viewStateIndex);
15817            Log.i("View", toString()
15818                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
15819                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
15820                    + " fo=" + hasFocus()
15821                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
15822                    + " wf=" + hasWindowFocus()
15823                    + ": " + Arrays.toString(drawableState));
15824        }
15825
15826        if (extraSpace == 0) {
15827            return drawableState;
15828        }
15829
15830        final int[] fullState;
15831        if (drawableState != null) {
15832            fullState = new int[drawableState.length + extraSpace];
15833            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
15834        } else {
15835            fullState = new int[extraSpace];
15836        }
15837
15838        return fullState;
15839    }
15840
15841    /**
15842     * Merge your own state values in <var>additionalState</var> into the base
15843     * state values <var>baseState</var> that were returned by
15844     * {@link #onCreateDrawableState(int)}.
15845     *
15846     * @param baseState The base state values returned by
15847     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
15848     * own additional state values.
15849     *
15850     * @param additionalState The additional state values you would like
15851     * added to <var>baseState</var>; this array is not modified.
15852     *
15853     * @return As a convenience, the <var>baseState</var> array you originally
15854     * passed into the function is returned.
15855     *
15856     * @see #onCreateDrawableState(int)
15857     */
15858    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
15859        final int N = baseState.length;
15860        int i = N - 1;
15861        while (i >= 0 && baseState[i] == 0) {
15862            i--;
15863        }
15864        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
15865        return baseState;
15866    }
15867
15868    /**
15869     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
15870     * on all Drawable objects associated with this view.
15871     * <p>
15872     * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator
15873     * attached to this view.
15874     */
15875    public void jumpDrawablesToCurrentState() {
15876        if (mBackground != null) {
15877            mBackground.jumpToCurrentState();
15878        }
15879        if (mStateListAnimator != null) {
15880            mStateListAnimator.jumpToCurrentState();
15881        }
15882    }
15883
15884    /**
15885     * Sets the background color for this view.
15886     * @param color the color of the background
15887     */
15888    @RemotableViewMethod
15889    public void setBackgroundColor(int color) {
15890        if (mBackground instanceof ColorDrawable) {
15891            ((ColorDrawable) mBackground.mutate()).setColor(color);
15892            computeOpaqueFlags();
15893            mBackgroundResource = 0;
15894        } else {
15895            setBackground(new ColorDrawable(color));
15896        }
15897    }
15898
15899    /**
15900     * Set the background to a given resource. The resource should refer to
15901     * a Drawable object or 0 to remove the background.
15902     * @param resid The identifier of the resource.
15903     *
15904     * @attr ref android.R.styleable#View_background
15905     */
15906    @RemotableViewMethod
15907    public void setBackgroundResource(int resid) {
15908        if (resid != 0 && resid == mBackgroundResource) {
15909            return;
15910        }
15911
15912        Drawable d = null;
15913        if (resid != 0) {
15914            d = mContext.getDrawable(resid);
15915        }
15916        setBackground(d);
15917
15918        mBackgroundResource = resid;
15919    }
15920
15921    /**
15922     * Set the background to a given Drawable, or remove the background. If the
15923     * background has padding, this View's padding is set to the background's
15924     * padding. However, when a background is removed, this View's padding isn't
15925     * touched. If setting the padding is desired, please use
15926     * {@link #setPadding(int, int, int, int)}.
15927     *
15928     * @param background The Drawable to use as the background, or null to remove the
15929     *        background
15930     */
15931    public void setBackground(Drawable background) {
15932        //noinspection deprecation
15933        setBackgroundDrawable(background);
15934    }
15935
15936    /**
15937     * @deprecated use {@link #setBackground(Drawable)} instead
15938     */
15939    @Deprecated
15940    public void setBackgroundDrawable(Drawable background) {
15941        computeOpaqueFlags();
15942
15943        if (background == mBackground) {
15944            return;
15945        }
15946
15947        boolean requestLayout = false;
15948
15949        mBackgroundResource = 0;
15950
15951        /*
15952         * Regardless of whether we're setting a new background or not, we want
15953         * to clear the previous drawable.
15954         */
15955        if (mBackground != null) {
15956            mBackground.setCallback(null);
15957            unscheduleDrawable(mBackground);
15958        }
15959
15960        if (background != null) {
15961            Rect padding = sThreadLocal.get();
15962            if (padding == null) {
15963                padding = new Rect();
15964                sThreadLocal.set(padding);
15965            }
15966            resetResolvedDrawables();
15967            background.setLayoutDirection(getLayoutDirection());
15968            if (background.getPadding(padding)) {
15969                resetResolvedPadding();
15970                switch (background.getLayoutDirection()) {
15971                    case LAYOUT_DIRECTION_RTL:
15972                        mUserPaddingLeftInitial = padding.right;
15973                        mUserPaddingRightInitial = padding.left;
15974                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
15975                        break;
15976                    case LAYOUT_DIRECTION_LTR:
15977                    default:
15978                        mUserPaddingLeftInitial = padding.left;
15979                        mUserPaddingRightInitial = padding.right;
15980                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
15981                }
15982                mLeftPaddingDefined = false;
15983                mRightPaddingDefined = false;
15984            }
15985
15986            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
15987            // if it has a different minimum size, we should layout again
15988            if (mBackground == null
15989                    || mBackground.getMinimumHeight() != background.getMinimumHeight()
15990                    || mBackground.getMinimumWidth() != background.getMinimumWidth()) {
15991                requestLayout = true;
15992            }
15993
15994            background.setCallback(this);
15995            if (background.isStateful()) {
15996                background.setState(getDrawableState());
15997            }
15998            background.setVisible(getVisibility() == VISIBLE, false);
15999            mBackground = background;
16000
16001            applyBackgroundTint();
16002
16003            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
16004                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
16005                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
16006                requestLayout = true;
16007            }
16008        } else {
16009            /* Remove the background */
16010            mBackground = null;
16011
16012            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
16013                /*
16014                 * This view ONLY drew the background before and we're removing
16015                 * the background, so now it won't draw anything
16016                 * (hence we SKIP_DRAW)
16017                 */
16018                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
16019                mPrivateFlags |= PFLAG_SKIP_DRAW;
16020            }
16021
16022            /*
16023             * When the background is set, we try to apply its padding to this
16024             * View. When the background is removed, we don't touch this View's
16025             * padding. This is noted in the Javadocs. Hence, we don't need to
16026             * requestLayout(), the invalidate() below is sufficient.
16027             */
16028
16029            // The old background's minimum size could have affected this
16030            // View's layout, so let's requestLayout
16031            requestLayout = true;
16032        }
16033
16034        computeOpaqueFlags();
16035
16036        if (requestLayout) {
16037            requestLayout();
16038        }
16039
16040        mBackgroundSizeChanged = true;
16041        invalidate(true);
16042    }
16043
16044    /**
16045     * Gets the background drawable
16046     *
16047     * @return The drawable used as the background for this view, if any.
16048     *
16049     * @see #setBackground(Drawable)
16050     *
16051     * @attr ref android.R.styleable#View_background
16052     */
16053    public Drawable getBackground() {
16054        return mBackground;
16055    }
16056
16057    /**
16058     * Applies a tint to the background drawable. Does not modify the current tint
16059     * mode, which is {@link PorterDuff.Mode#SRC_ATOP} by default.
16060     * <p>
16061     * Subsequent calls to {@link #setBackground(Drawable)} will automatically
16062     * mutate the drawable and apply the specified tint and tint mode using
16063     * {@link Drawable#setTintList(ColorStateList)}.
16064     *
16065     * @param tint the tint to apply, may be {@code null} to clear tint
16066     *
16067     * @attr ref android.R.styleable#View_backgroundTint
16068     * @see #getBackgroundTintList()
16069     * @see Drawable#setTintList(ColorStateList)
16070     */
16071    public void setBackgroundTintList(@Nullable ColorStateList tint) {
16072        mBackgroundTintList = tint;
16073        mHasBackgroundTint = true;
16074
16075        applyBackgroundTint();
16076    }
16077
16078    /**
16079     * @return the tint applied to the background drawable
16080     * @attr ref android.R.styleable#View_backgroundTint
16081     * @see #setBackgroundTintList(ColorStateList)
16082     */
16083    @Nullable
16084    public ColorStateList getBackgroundTintList() {
16085        return mBackgroundTintList;
16086    }
16087
16088    /**
16089     * Specifies the blending mode used to apply the tint specified by
16090     * {@link #setBackgroundTintList(ColorStateList)}} to the background drawable.
16091     * The default mode is {@link PorterDuff.Mode#SRC_ATOP}.
16092     *
16093     * @param tintMode the blending mode used to apply the tint, may be
16094     *                 {@code null} to clear tint
16095     * @attr ref android.R.styleable#View_backgroundTintMode
16096     * @see #getBackgroundTintMode()
16097     * @see Drawable#setTintMode(PorterDuff.Mode)
16098     */
16099    public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
16100        mBackgroundTintMode = tintMode;
16101
16102        applyBackgroundTint();
16103    }
16104
16105    /**
16106     * @return the blending mode used to apply the tint to the background drawable
16107     * @attr ref android.R.styleable#View_backgroundTintMode
16108     * @see #setBackgroundTintMode(PorterDuff.Mode)
16109     */
16110    @Nullable
16111    public PorterDuff.Mode getBackgroundTintMode() {
16112        return mBackgroundTintMode;
16113    }
16114
16115    private void applyBackgroundTint() {
16116        if (mBackground != null && mHasBackgroundTint) {
16117            mBackground = mBackground.mutate();
16118            mBackground.setTintList(mBackgroundTintList);
16119            mBackground.setTintMode(mBackgroundTintMode);
16120        }
16121    }
16122
16123    /**
16124     * Sets the padding. The view may add on the space required to display
16125     * the scrollbars, depending on the style and visibility of the scrollbars.
16126     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
16127     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
16128     * from the values set in this call.
16129     *
16130     * @attr ref android.R.styleable#View_padding
16131     * @attr ref android.R.styleable#View_paddingBottom
16132     * @attr ref android.R.styleable#View_paddingLeft
16133     * @attr ref android.R.styleable#View_paddingRight
16134     * @attr ref android.R.styleable#View_paddingTop
16135     * @param left the left padding in pixels
16136     * @param top the top padding in pixels
16137     * @param right the right padding in pixels
16138     * @param bottom the bottom padding in pixels
16139     */
16140    public void setPadding(int left, int top, int right, int bottom) {
16141        resetResolvedPadding();
16142
16143        mUserPaddingStart = UNDEFINED_PADDING;
16144        mUserPaddingEnd = UNDEFINED_PADDING;
16145
16146        mUserPaddingLeftInitial = left;
16147        mUserPaddingRightInitial = right;
16148
16149        mLeftPaddingDefined = true;
16150        mRightPaddingDefined = true;
16151
16152        internalSetPadding(left, top, right, bottom);
16153    }
16154
16155    /**
16156     * @hide
16157     */
16158    protected void internalSetPadding(int left, int top, int right, int bottom) {
16159        mUserPaddingLeft = left;
16160        mUserPaddingRight = right;
16161        mUserPaddingBottom = bottom;
16162
16163        final int viewFlags = mViewFlags;
16164        boolean changed = false;
16165
16166        // Common case is there are no scroll bars.
16167        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
16168            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
16169                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
16170                        ? 0 : getVerticalScrollbarWidth();
16171                switch (mVerticalScrollbarPosition) {
16172                    case SCROLLBAR_POSITION_DEFAULT:
16173                        if (isLayoutRtl()) {
16174                            left += offset;
16175                        } else {
16176                            right += offset;
16177                        }
16178                        break;
16179                    case SCROLLBAR_POSITION_RIGHT:
16180                        right += offset;
16181                        break;
16182                    case SCROLLBAR_POSITION_LEFT:
16183                        left += offset;
16184                        break;
16185                }
16186            }
16187            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
16188                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
16189                        ? 0 : getHorizontalScrollbarHeight();
16190            }
16191        }
16192
16193        if (mPaddingLeft != left) {
16194            changed = true;
16195            mPaddingLeft = left;
16196        }
16197        if (mPaddingTop != top) {
16198            changed = true;
16199            mPaddingTop = top;
16200        }
16201        if (mPaddingRight != right) {
16202            changed = true;
16203            mPaddingRight = right;
16204        }
16205        if (mPaddingBottom != bottom) {
16206            changed = true;
16207            mPaddingBottom = bottom;
16208        }
16209
16210        if (changed) {
16211            requestLayout();
16212        }
16213    }
16214
16215    /**
16216     * Sets the relative padding. The view may add on the space required to display
16217     * the scrollbars, depending on the style and visibility of the scrollbars.
16218     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
16219     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
16220     * from the values set in this call.
16221     *
16222     * @attr ref android.R.styleable#View_padding
16223     * @attr ref android.R.styleable#View_paddingBottom
16224     * @attr ref android.R.styleable#View_paddingStart
16225     * @attr ref android.R.styleable#View_paddingEnd
16226     * @attr ref android.R.styleable#View_paddingTop
16227     * @param start the start padding in pixels
16228     * @param top the top padding in pixels
16229     * @param end the end padding in pixels
16230     * @param bottom the bottom padding in pixels
16231     */
16232    public void setPaddingRelative(int start, int top, int end, int bottom) {
16233        resetResolvedPadding();
16234
16235        mUserPaddingStart = start;
16236        mUserPaddingEnd = end;
16237        mLeftPaddingDefined = true;
16238        mRightPaddingDefined = true;
16239
16240        switch(getLayoutDirection()) {
16241            case LAYOUT_DIRECTION_RTL:
16242                mUserPaddingLeftInitial = end;
16243                mUserPaddingRightInitial = start;
16244                internalSetPadding(end, top, start, bottom);
16245                break;
16246            case LAYOUT_DIRECTION_LTR:
16247            default:
16248                mUserPaddingLeftInitial = start;
16249                mUserPaddingRightInitial = end;
16250                internalSetPadding(start, top, end, bottom);
16251        }
16252    }
16253
16254    /**
16255     * Returns the top padding of this view.
16256     *
16257     * @return the top padding in pixels
16258     */
16259    public int getPaddingTop() {
16260        return mPaddingTop;
16261    }
16262
16263    /**
16264     * Returns the bottom padding of this view. If there are inset and enabled
16265     * scrollbars, this value may include the space required to display the
16266     * scrollbars as well.
16267     *
16268     * @return the bottom padding in pixels
16269     */
16270    public int getPaddingBottom() {
16271        return mPaddingBottom;
16272    }
16273
16274    /**
16275     * Returns the left padding of this view. If there are inset and enabled
16276     * scrollbars, this value may include the space required to display the
16277     * scrollbars as well.
16278     *
16279     * @return the left padding in pixels
16280     */
16281    public int getPaddingLeft() {
16282        if (!isPaddingResolved()) {
16283            resolvePadding();
16284        }
16285        return mPaddingLeft;
16286    }
16287
16288    /**
16289     * Returns the start padding of this view depending on its resolved layout direction.
16290     * If there are inset and enabled scrollbars, this value may include the space
16291     * required to display the scrollbars as well.
16292     *
16293     * @return the start padding in pixels
16294     */
16295    public int getPaddingStart() {
16296        if (!isPaddingResolved()) {
16297            resolvePadding();
16298        }
16299        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16300                mPaddingRight : mPaddingLeft;
16301    }
16302
16303    /**
16304     * Returns the right padding of this view. If there are inset and enabled
16305     * scrollbars, this value may include the space required to display the
16306     * scrollbars as well.
16307     *
16308     * @return the right padding in pixels
16309     */
16310    public int getPaddingRight() {
16311        if (!isPaddingResolved()) {
16312            resolvePadding();
16313        }
16314        return mPaddingRight;
16315    }
16316
16317    /**
16318     * Returns the end padding of this view depending on its resolved layout direction.
16319     * If there are inset and enabled scrollbars, this value may include the space
16320     * required to display the scrollbars as well.
16321     *
16322     * @return the end padding in pixels
16323     */
16324    public int getPaddingEnd() {
16325        if (!isPaddingResolved()) {
16326            resolvePadding();
16327        }
16328        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
16329                mPaddingLeft : mPaddingRight;
16330    }
16331
16332    /**
16333     * Return if the padding as been set thru relative values
16334     * {@link #setPaddingRelative(int, int, int, int)} or thru
16335     * @attr ref android.R.styleable#View_paddingStart or
16336     * @attr ref android.R.styleable#View_paddingEnd
16337     *
16338     * @return true if the padding is relative or false if it is not.
16339     */
16340    public boolean isPaddingRelative() {
16341        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
16342    }
16343
16344    Insets computeOpticalInsets() {
16345        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
16346    }
16347
16348    /**
16349     * @hide
16350     */
16351    public void resetPaddingToInitialValues() {
16352        if (isRtlCompatibilityMode()) {
16353            mPaddingLeft = mUserPaddingLeftInitial;
16354            mPaddingRight = mUserPaddingRightInitial;
16355            return;
16356        }
16357        if (isLayoutRtl()) {
16358            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
16359            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
16360        } else {
16361            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
16362            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
16363        }
16364    }
16365
16366    /**
16367     * @hide
16368     */
16369    public Insets getOpticalInsets() {
16370        if (mLayoutInsets == null) {
16371            mLayoutInsets = computeOpticalInsets();
16372        }
16373        return mLayoutInsets;
16374    }
16375
16376    /**
16377     * Set this view's optical insets.
16378     *
16379     * <p>This method should be treated similarly to setMeasuredDimension and not as a general
16380     * property. Views that compute their own optical insets should call it as part of measurement.
16381     * This method does not request layout. If you are setting optical insets outside of
16382     * measure/layout itself you will want to call requestLayout() yourself.
16383     * </p>
16384     * @hide
16385     */
16386    public void setOpticalInsets(Insets insets) {
16387        mLayoutInsets = insets;
16388    }
16389
16390    /**
16391     * Changes the selection state of this view. A view can be selected or not.
16392     * Note that selection is not the same as focus. Views are typically
16393     * selected in the context of an AdapterView like ListView or GridView;
16394     * the selected view is the view that is highlighted.
16395     *
16396     * @param selected true if the view must be selected, false otherwise
16397     */
16398    public void setSelected(boolean selected) {
16399        //noinspection DoubleNegation
16400        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
16401            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
16402            if (!selected) resetPressedState();
16403            invalidate(true);
16404            refreshDrawableState();
16405            dispatchSetSelected(selected);
16406            notifyViewAccessibilityStateChangedIfNeeded(
16407                    AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
16408        }
16409    }
16410
16411    /**
16412     * Dispatch setSelected to all of this View's children.
16413     *
16414     * @see #setSelected(boolean)
16415     *
16416     * @param selected The new selected state
16417     */
16418    protected void dispatchSetSelected(boolean selected) {
16419    }
16420
16421    /**
16422     * Indicates the selection state of this view.
16423     *
16424     * @return true if the view is selected, false otherwise
16425     */
16426    @ViewDebug.ExportedProperty
16427    public boolean isSelected() {
16428        return (mPrivateFlags & PFLAG_SELECTED) != 0;
16429    }
16430
16431    /**
16432     * Changes the activated state of this view. A view can be activated or not.
16433     * Note that activation is not the same as selection.  Selection is
16434     * a transient property, representing the view (hierarchy) the user is
16435     * currently interacting with.  Activation is a longer-term state that the
16436     * user can move views in and out of.  For example, in a list view with
16437     * single or multiple selection enabled, the views in the current selection
16438     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
16439     * here.)  The activated state is propagated down to children of the view it
16440     * is set on.
16441     *
16442     * @param activated true if the view must be activated, false otherwise
16443     */
16444    public void setActivated(boolean activated) {
16445        //noinspection DoubleNegation
16446        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
16447            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
16448            invalidate(true);
16449            refreshDrawableState();
16450            dispatchSetActivated(activated);
16451        }
16452    }
16453
16454    /**
16455     * Dispatch setActivated to all of this View's children.
16456     *
16457     * @see #setActivated(boolean)
16458     *
16459     * @param activated The new activated state
16460     */
16461    protected void dispatchSetActivated(boolean activated) {
16462    }
16463
16464    /**
16465     * Indicates the activation state of this view.
16466     *
16467     * @return true if the view is activated, false otherwise
16468     */
16469    @ViewDebug.ExportedProperty
16470    public boolean isActivated() {
16471        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
16472    }
16473
16474    /**
16475     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
16476     * observer can be used to get notifications when global events, like
16477     * layout, happen.
16478     *
16479     * The returned ViewTreeObserver observer is not guaranteed to remain
16480     * valid for the lifetime of this View. If the caller of this method keeps
16481     * a long-lived reference to ViewTreeObserver, it should always check for
16482     * the return value of {@link ViewTreeObserver#isAlive()}.
16483     *
16484     * @return The ViewTreeObserver for this view's hierarchy.
16485     */
16486    public ViewTreeObserver getViewTreeObserver() {
16487        if (mAttachInfo != null) {
16488            return mAttachInfo.mTreeObserver;
16489        }
16490        if (mFloatingTreeObserver == null) {
16491            mFloatingTreeObserver = new ViewTreeObserver();
16492        }
16493        return mFloatingTreeObserver;
16494    }
16495
16496    /**
16497     * <p>Finds the topmost view in the current view hierarchy.</p>
16498     *
16499     * @return the topmost view containing this view
16500     */
16501    public View getRootView() {
16502        if (mAttachInfo != null) {
16503            final View v = mAttachInfo.mRootView;
16504            if (v != null) {
16505                return v;
16506            }
16507        }
16508
16509        View parent = this;
16510
16511        while (parent.mParent != null && parent.mParent instanceof View) {
16512            parent = (View) parent.mParent;
16513        }
16514
16515        return parent;
16516    }
16517
16518    /**
16519     * Transforms a motion event from view-local coordinates to on-screen
16520     * coordinates.
16521     *
16522     * @param ev the view-local motion event
16523     * @return false if the transformation could not be applied
16524     * @hide
16525     */
16526    public boolean toGlobalMotionEvent(MotionEvent ev) {
16527        final AttachInfo info = mAttachInfo;
16528        if (info == null) {
16529            return false;
16530        }
16531
16532        final Matrix m = info.mTmpMatrix;
16533        m.set(Matrix.IDENTITY_MATRIX);
16534        transformMatrixToGlobal(m);
16535        ev.transform(m);
16536        return true;
16537    }
16538
16539    /**
16540     * Transforms a motion event from on-screen coordinates to view-local
16541     * coordinates.
16542     *
16543     * @param ev the on-screen motion event
16544     * @return false if the transformation could not be applied
16545     * @hide
16546     */
16547    public boolean toLocalMotionEvent(MotionEvent ev) {
16548        final AttachInfo info = mAttachInfo;
16549        if (info == null) {
16550            return false;
16551        }
16552
16553        final Matrix m = info.mTmpMatrix;
16554        m.set(Matrix.IDENTITY_MATRIX);
16555        transformMatrixToLocal(m);
16556        ev.transform(m);
16557        return true;
16558    }
16559
16560    /**
16561     * Modifies the input matrix such that it maps view-local coordinates to
16562     * on-screen coordinates.
16563     *
16564     * @param m input matrix to modify
16565     * @hide
16566     */
16567    public void transformMatrixToGlobal(Matrix m) {
16568        final ViewParent parent = mParent;
16569        if (parent instanceof View) {
16570            final View vp = (View) parent;
16571            vp.transformMatrixToGlobal(m);
16572            m.preTranslate(-vp.mScrollX, -vp.mScrollY);
16573        } else if (parent instanceof ViewRootImpl) {
16574            final ViewRootImpl vr = (ViewRootImpl) parent;
16575            vr.transformMatrixToGlobal(m);
16576            m.preTranslate(0, -vr.mCurScrollY);
16577        }
16578
16579        m.preTranslate(mLeft, mTop);
16580
16581        if (!hasIdentityMatrix()) {
16582            m.preConcat(getMatrix());
16583        }
16584    }
16585
16586    /**
16587     * Modifies the input matrix such that it maps on-screen coordinates to
16588     * view-local coordinates.
16589     *
16590     * @param m input matrix to modify
16591     * @hide
16592     */
16593    public void transformMatrixToLocal(Matrix m) {
16594        final ViewParent parent = mParent;
16595        if (parent instanceof View) {
16596            final View vp = (View) parent;
16597            vp.transformMatrixToLocal(m);
16598            m.postTranslate(vp.mScrollX, vp.mScrollY);
16599        } else if (parent instanceof ViewRootImpl) {
16600            final ViewRootImpl vr = (ViewRootImpl) parent;
16601            vr.transformMatrixToLocal(m);
16602            m.postTranslate(0, vr.mCurScrollY);
16603        }
16604
16605        m.postTranslate(-mLeft, -mTop);
16606
16607        if (!hasIdentityMatrix()) {
16608            m.postConcat(getInverseMatrix());
16609        }
16610    }
16611
16612    /**
16613     * @hide
16614     */
16615    @ViewDebug.ExportedProperty(category = "layout", indexMapping = {
16616            @ViewDebug.IntToString(from = 0, to = "x"),
16617            @ViewDebug.IntToString(from = 1, to = "y")
16618    })
16619    public int[] getLocationOnScreen() {
16620        int[] location = new int[2];
16621        getLocationOnScreen(location);
16622        return location;
16623    }
16624
16625    /**
16626     * <p>Computes the coordinates of this view on the screen. The argument
16627     * must be an array of two integers. After the method returns, the array
16628     * contains the x and y location in that order.</p>
16629     *
16630     * @param location an array of two integers in which to hold the coordinates
16631     */
16632    public void getLocationOnScreen(int[] location) {
16633        getLocationInWindow(location);
16634
16635        final AttachInfo info = mAttachInfo;
16636        if (info != null) {
16637            location[0] += info.mWindowLeft;
16638            location[1] += info.mWindowTop;
16639        }
16640    }
16641
16642    /**
16643     * <p>Computes the coordinates of this view in its window. The argument
16644     * must be an array of two integers. After the method returns, the array
16645     * contains the x and y location in that order.</p>
16646     *
16647     * @param location an array of two integers in which to hold the coordinates
16648     */
16649    public void getLocationInWindow(int[] location) {
16650        if (location == null || location.length < 2) {
16651            throw new IllegalArgumentException("location must be an array of two integers");
16652        }
16653
16654        if (mAttachInfo == null) {
16655            // When the view is not attached to a window, this method does not make sense
16656            location[0] = location[1] = 0;
16657            return;
16658        }
16659
16660        float[] position = mAttachInfo.mTmpTransformLocation;
16661        position[0] = position[1] = 0.0f;
16662
16663        if (!hasIdentityMatrix()) {
16664            getMatrix().mapPoints(position);
16665        }
16666
16667        position[0] += mLeft;
16668        position[1] += mTop;
16669
16670        ViewParent viewParent = mParent;
16671        while (viewParent instanceof View) {
16672            final View view = (View) viewParent;
16673
16674            position[0] -= view.mScrollX;
16675            position[1] -= view.mScrollY;
16676
16677            if (!view.hasIdentityMatrix()) {
16678                view.getMatrix().mapPoints(position);
16679            }
16680
16681            position[0] += view.mLeft;
16682            position[1] += view.mTop;
16683
16684            viewParent = view.mParent;
16685         }
16686
16687        if (viewParent instanceof ViewRootImpl) {
16688            // *cough*
16689            final ViewRootImpl vr = (ViewRootImpl) viewParent;
16690            position[1] -= vr.mCurScrollY;
16691        }
16692
16693        location[0] = (int) (position[0] + 0.5f);
16694        location[1] = (int) (position[1] + 0.5f);
16695    }
16696
16697    /**
16698     * {@hide}
16699     * @param id the id of the view to be found
16700     * @return the view of the specified id, null if cannot be found
16701     */
16702    protected View findViewTraversal(int id) {
16703        if (id == mID) {
16704            return this;
16705        }
16706        return null;
16707    }
16708
16709    /**
16710     * {@hide}
16711     * @param tag the tag of the view to be found
16712     * @return the view of specified tag, null if cannot be found
16713     */
16714    protected View findViewWithTagTraversal(Object tag) {
16715        if (tag != null && tag.equals(mTag)) {
16716            return this;
16717        }
16718        return null;
16719    }
16720
16721    /**
16722     * {@hide}
16723     * @param predicate The predicate to evaluate.
16724     * @param childToSkip If not null, ignores this child during the recursive traversal.
16725     * @return The first view that matches the predicate or null.
16726     */
16727    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
16728        if (predicate.apply(this)) {
16729            return this;
16730        }
16731        return null;
16732    }
16733
16734    /**
16735     * Look for a child view with the given id.  If this view has the given
16736     * id, return this view.
16737     *
16738     * @param id The id to search for.
16739     * @return The view that has the given id in the hierarchy or null
16740     */
16741    public final View findViewById(int id) {
16742        if (id < 0) {
16743            return null;
16744        }
16745        return findViewTraversal(id);
16746    }
16747
16748    /**
16749     * Finds a view by its unuque and stable accessibility id.
16750     *
16751     * @param accessibilityId The searched accessibility id.
16752     * @return The found view.
16753     */
16754    final View findViewByAccessibilityId(int accessibilityId) {
16755        if (accessibilityId < 0) {
16756            return null;
16757        }
16758        return findViewByAccessibilityIdTraversal(accessibilityId);
16759    }
16760
16761    /**
16762     * Performs the traversal to find a view by its unuque and stable accessibility id.
16763     *
16764     * <strong>Note:</strong>This method does not stop at the root namespace
16765     * boundary since the user can touch the screen at an arbitrary location
16766     * potentially crossing the root namespace bounday which will send an
16767     * accessibility event to accessibility services and they should be able
16768     * to obtain the event source. Also accessibility ids are guaranteed to be
16769     * unique in the window.
16770     *
16771     * @param accessibilityId The accessibility id.
16772     * @return The found view.
16773     *
16774     * @hide
16775     */
16776    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
16777        if (getAccessibilityViewId() == accessibilityId) {
16778            return this;
16779        }
16780        return null;
16781    }
16782
16783    /**
16784     * Look for a child view with the given tag.  If this view has the given
16785     * tag, return this view.
16786     *
16787     * @param tag The tag to search for, using "tag.equals(getTag())".
16788     * @return The View that has the given tag in the hierarchy or null
16789     */
16790    public final View findViewWithTag(Object tag) {
16791        if (tag == null) {
16792            return null;
16793        }
16794        return findViewWithTagTraversal(tag);
16795    }
16796
16797    /**
16798     * {@hide}
16799     * Look for a child view that matches the specified predicate.
16800     * If this view matches the predicate, return this view.
16801     *
16802     * @param predicate The predicate to evaluate.
16803     * @return The first view that matches the predicate or null.
16804     */
16805    public final View findViewByPredicate(Predicate<View> predicate) {
16806        return findViewByPredicateTraversal(predicate, null);
16807    }
16808
16809    /**
16810     * {@hide}
16811     * Look for a child view that matches the specified predicate,
16812     * starting with the specified view and its descendents and then
16813     * recusively searching the ancestors and siblings of that view
16814     * until this view is reached.
16815     *
16816     * This method is useful in cases where the predicate does not match
16817     * a single unique view (perhaps multiple views use the same id)
16818     * and we are trying to find the view that is "closest" in scope to the
16819     * starting view.
16820     *
16821     * @param start The view to start from.
16822     * @param predicate The predicate to evaluate.
16823     * @return The first view that matches the predicate or null.
16824     */
16825    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
16826        View childToSkip = null;
16827        for (;;) {
16828            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
16829            if (view != null || start == this) {
16830                return view;
16831            }
16832
16833            ViewParent parent = start.getParent();
16834            if (parent == null || !(parent instanceof View)) {
16835                return null;
16836            }
16837
16838            childToSkip = start;
16839            start = (View) parent;
16840        }
16841    }
16842
16843    /**
16844     * Sets the identifier for this view. The identifier does not have to be
16845     * unique in this view's hierarchy. The identifier should be a positive
16846     * number.
16847     *
16848     * @see #NO_ID
16849     * @see #getId()
16850     * @see #findViewById(int)
16851     *
16852     * @param id a number used to identify the view
16853     *
16854     * @attr ref android.R.styleable#View_id
16855     */
16856    public void setId(int id) {
16857        mID = id;
16858        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
16859            mID = generateViewId();
16860        }
16861    }
16862
16863    /**
16864     * {@hide}
16865     *
16866     * @param isRoot true if the view belongs to the root namespace, false
16867     *        otherwise
16868     */
16869    public void setIsRootNamespace(boolean isRoot) {
16870        if (isRoot) {
16871            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
16872        } else {
16873            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
16874        }
16875    }
16876
16877    /**
16878     * {@hide}
16879     *
16880     * @return true if the view belongs to the root namespace, false otherwise
16881     */
16882    public boolean isRootNamespace() {
16883        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
16884    }
16885
16886    /**
16887     * Returns this view's identifier.
16888     *
16889     * @return a positive integer used to identify the view or {@link #NO_ID}
16890     *         if the view has no ID
16891     *
16892     * @see #setId(int)
16893     * @see #findViewById(int)
16894     * @attr ref android.R.styleable#View_id
16895     */
16896    @ViewDebug.CapturedViewProperty
16897    public int getId() {
16898        return mID;
16899    }
16900
16901    /**
16902     * Returns this view's tag.
16903     *
16904     * @return the Object stored in this view as a tag, or {@code null} if not
16905     *         set
16906     *
16907     * @see #setTag(Object)
16908     * @see #getTag(int)
16909     */
16910    @ViewDebug.ExportedProperty
16911    public Object getTag() {
16912        return mTag;
16913    }
16914
16915    /**
16916     * Sets the tag associated with this view. A tag can be used to mark
16917     * a view in its hierarchy and does not have to be unique within the
16918     * hierarchy. Tags can also be used to store data within a view without
16919     * resorting to another data structure.
16920     *
16921     * @param tag an Object to tag the view with
16922     *
16923     * @see #getTag()
16924     * @see #setTag(int, Object)
16925     */
16926    public void setTag(final Object tag) {
16927        mTag = tag;
16928    }
16929
16930    /**
16931     * Returns the tag associated with this view and the specified key.
16932     *
16933     * @param key The key identifying the tag
16934     *
16935     * @return the Object stored in this view as a tag, or {@code null} if not
16936     *         set
16937     *
16938     * @see #setTag(int, Object)
16939     * @see #getTag()
16940     */
16941    public Object getTag(int key) {
16942        if (mKeyedTags != null) return mKeyedTags.get(key);
16943        return null;
16944    }
16945
16946    /**
16947     * Sets a tag associated with this view and a key. A tag can be used
16948     * to mark a view in its hierarchy and does not have to be unique within
16949     * the hierarchy. Tags can also be used to store data within a view
16950     * without resorting to another data structure.
16951     *
16952     * The specified key should be an id declared in the resources of the
16953     * application to ensure it is unique (see the <a
16954     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
16955     * Keys identified as belonging to
16956     * the Android framework or not associated with any package will cause
16957     * an {@link IllegalArgumentException} to be thrown.
16958     *
16959     * @param key The key identifying the tag
16960     * @param tag An Object to tag the view with
16961     *
16962     * @throws IllegalArgumentException If they specified key is not valid
16963     *
16964     * @see #setTag(Object)
16965     * @see #getTag(int)
16966     */
16967    public void setTag(int key, final Object tag) {
16968        // If the package id is 0x00 or 0x01, it's either an undefined package
16969        // or a framework id
16970        if ((key >>> 24) < 2) {
16971            throw new IllegalArgumentException("The key must be an application-specific "
16972                    + "resource id.");
16973        }
16974
16975        setKeyedTag(key, tag);
16976    }
16977
16978    /**
16979     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
16980     * framework id.
16981     *
16982     * @hide
16983     */
16984    public void setTagInternal(int key, Object tag) {
16985        if ((key >>> 24) != 0x1) {
16986            throw new IllegalArgumentException("The key must be a framework-specific "
16987                    + "resource id.");
16988        }
16989
16990        setKeyedTag(key, tag);
16991    }
16992
16993    private void setKeyedTag(int key, Object tag) {
16994        if (mKeyedTags == null) {
16995            mKeyedTags = new SparseArray<Object>(2);
16996        }
16997
16998        mKeyedTags.put(key, tag);
16999    }
17000
17001    /**
17002     * Prints information about this view in the log output, with the tag
17003     * {@link #VIEW_LOG_TAG}.
17004     *
17005     * @hide
17006     */
17007    public void debug() {
17008        debug(0);
17009    }
17010
17011    /**
17012     * Prints information about this view in the log output, with the tag
17013     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
17014     * indentation defined by the <code>depth</code>.
17015     *
17016     * @param depth the indentation level
17017     *
17018     * @hide
17019     */
17020    protected void debug(int depth) {
17021        String output = debugIndent(depth - 1);
17022
17023        output += "+ " + this;
17024        int id = getId();
17025        if (id != -1) {
17026            output += " (id=" + id + ")";
17027        }
17028        Object tag = getTag();
17029        if (tag != null) {
17030            output += " (tag=" + tag + ")";
17031        }
17032        Log.d(VIEW_LOG_TAG, output);
17033
17034        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
17035            output = debugIndent(depth) + " FOCUSED";
17036            Log.d(VIEW_LOG_TAG, output);
17037        }
17038
17039        output = debugIndent(depth);
17040        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
17041                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
17042                + "} ";
17043        Log.d(VIEW_LOG_TAG, output);
17044
17045        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
17046                || mPaddingBottom != 0) {
17047            output = debugIndent(depth);
17048            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
17049                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
17050            Log.d(VIEW_LOG_TAG, output);
17051        }
17052
17053        output = debugIndent(depth);
17054        output += "mMeasureWidth=" + mMeasuredWidth +
17055                " mMeasureHeight=" + mMeasuredHeight;
17056        Log.d(VIEW_LOG_TAG, output);
17057
17058        output = debugIndent(depth);
17059        if (mLayoutParams == null) {
17060            output += "BAD! no layout params";
17061        } else {
17062            output = mLayoutParams.debug(output);
17063        }
17064        Log.d(VIEW_LOG_TAG, output);
17065
17066        output = debugIndent(depth);
17067        output += "flags={";
17068        output += View.printFlags(mViewFlags);
17069        output += "}";
17070        Log.d(VIEW_LOG_TAG, output);
17071
17072        output = debugIndent(depth);
17073        output += "privateFlags={";
17074        output += View.printPrivateFlags(mPrivateFlags);
17075        output += "}";
17076        Log.d(VIEW_LOG_TAG, output);
17077    }
17078
17079    /**
17080     * Creates a string of whitespaces used for indentation.
17081     *
17082     * @param depth the indentation level
17083     * @return a String containing (depth * 2 + 3) * 2 white spaces
17084     *
17085     * @hide
17086     */
17087    protected static String debugIndent(int depth) {
17088        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
17089        for (int i = 0; i < (depth * 2) + 3; i++) {
17090            spaces.append(' ').append(' ');
17091        }
17092        return spaces.toString();
17093    }
17094
17095    /**
17096     * <p>Return the offset of the widget's text baseline from the widget's top
17097     * boundary. If this widget does not support baseline alignment, this
17098     * method returns -1. </p>
17099     *
17100     * @return the offset of the baseline within the widget's bounds or -1
17101     *         if baseline alignment is not supported
17102     */
17103    @ViewDebug.ExportedProperty(category = "layout")
17104    public int getBaseline() {
17105        return -1;
17106    }
17107
17108    /**
17109     * Returns whether the view hierarchy is currently undergoing a layout pass. This
17110     * information is useful to avoid situations such as calling {@link #requestLayout()} during
17111     * a layout pass.
17112     *
17113     * @return whether the view hierarchy is currently undergoing a layout pass
17114     */
17115    public boolean isInLayout() {
17116        ViewRootImpl viewRoot = getViewRootImpl();
17117        return (viewRoot != null && viewRoot.isInLayout());
17118    }
17119
17120    /**
17121     * Call this when something has changed which has invalidated the
17122     * layout of this view. This will schedule a layout pass of the view
17123     * tree. This should not be called while the view hierarchy is currently in a layout
17124     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
17125     * end of the current layout pass (and then layout will run again) or after the current
17126     * frame is drawn and the next layout occurs.
17127     *
17128     * <p>Subclasses which override this method should call the superclass method to
17129     * handle possible request-during-layout errors correctly.</p>
17130     */
17131    public void requestLayout() {
17132        if (mMeasureCache != null) mMeasureCache.clear();
17133
17134        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
17135            // Only trigger request-during-layout logic if this is the view requesting it,
17136            // not the views in its parent hierarchy
17137            ViewRootImpl viewRoot = getViewRootImpl();
17138            if (viewRoot != null && viewRoot.isInLayout()) {
17139                if (!viewRoot.requestLayoutDuringLayout(this)) {
17140                    return;
17141                }
17142            }
17143            mAttachInfo.mViewRequestingLayout = this;
17144        }
17145
17146        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17147        mPrivateFlags |= PFLAG_INVALIDATED;
17148
17149        if (mParent != null && !mParent.isLayoutRequested()) {
17150            mParent.requestLayout();
17151        }
17152        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
17153            mAttachInfo.mViewRequestingLayout = null;
17154        }
17155    }
17156
17157    /**
17158     * Forces this view to be laid out during the next layout pass.
17159     * This method does not call requestLayout() or forceLayout()
17160     * on the parent.
17161     */
17162    public void forceLayout() {
17163        if (mMeasureCache != null) mMeasureCache.clear();
17164
17165        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
17166        mPrivateFlags |= PFLAG_INVALIDATED;
17167    }
17168
17169    /**
17170     * <p>
17171     * This is called to find out how big a view should be. The parent
17172     * supplies constraint information in the width and height parameters.
17173     * </p>
17174     *
17175     * <p>
17176     * The actual measurement work of a view is performed in
17177     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
17178     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
17179     * </p>
17180     *
17181     *
17182     * @param widthMeasureSpec Horizontal space requirements as imposed by the
17183     *        parent
17184     * @param heightMeasureSpec Vertical space requirements as imposed by the
17185     *        parent
17186     *
17187     * @see #onMeasure(int, int)
17188     */
17189    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
17190        boolean optical = isLayoutModeOptical(this);
17191        if (optical != isLayoutModeOptical(mParent)) {
17192            Insets insets = getOpticalInsets();
17193            int oWidth  = insets.left + insets.right;
17194            int oHeight = insets.top  + insets.bottom;
17195            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
17196            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
17197        }
17198
17199        // Suppress sign extension for the low bytes
17200        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
17201        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
17202
17203        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
17204                widthMeasureSpec != mOldWidthMeasureSpec ||
17205                heightMeasureSpec != mOldHeightMeasureSpec) {
17206
17207            // first clears the measured dimension flag
17208            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
17209
17210            resolveRtlPropertiesIfNeeded();
17211
17212            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
17213                    mMeasureCache.indexOfKey(key);
17214            if (cacheIndex < 0 || sIgnoreMeasureCache) {
17215                // measure ourselves, this should set the measured dimension flag back
17216                onMeasure(widthMeasureSpec, heightMeasureSpec);
17217                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17218            } else {
17219                long value = mMeasureCache.valueAt(cacheIndex);
17220                // Casting a long to int drops the high 32 bits, no mask needed
17221                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
17222                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
17223            }
17224
17225            // flag not set, setMeasuredDimension() was not invoked, we raise
17226            // an exception to warn the developer
17227            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
17228                throw new IllegalStateException("onMeasure() did not set the"
17229                        + " measured dimension by calling"
17230                        + " setMeasuredDimension()");
17231            }
17232
17233            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
17234        }
17235
17236        mOldWidthMeasureSpec = widthMeasureSpec;
17237        mOldHeightMeasureSpec = heightMeasureSpec;
17238
17239        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
17240                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
17241    }
17242
17243    /**
17244     * <p>
17245     * Measure the view and its content to determine the measured width and the
17246     * measured height. This method is invoked by {@link #measure(int, int)} and
17247     * should be overriden by subclasses to provide accurate and efficient
17248     * measurement of their contents.
17249     * </p>
17250     *
17251     * <p>
17252     * <strong>CONTRACT:</strong> When overriding this method, you
17253     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
17254     * measured width and height of this view. Failure to do so will trigger an
17255     * <code>IllegalStateException</code>, thrown by
17256     * {@link #measure(int, int)}. Calling the superclass'
17257     * {@link #onMeasure(int, int)} is a valid use.
17258     * </p>
17259     *
17260     * <p>
17261     * The base class implementation of measure defaults to the background size,
17262     * unless a larger size is allowed by the MeasureSpec. Subclasses should
17263     * override {@link #onMeasure(int, int)} to provide better measurements of
17264     * their content.
17265     * </p>
17266     *
17267     * <p>
17268     * If this method is overridden, it is the subclass's responsibility to make
17269     * sure the measured height and width are at least the view's minimum height
17270     * and width ({@link #getSuggestedMinimumHeight()} and
17271     * {@link #getSuggestedMinimumWidth()}).
17272     * </p>
17273     *
17274     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
17275     *                         The requirements are encoded with
17276     *                         {@link android.view.View.MeasureSpec}.
17277     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
17278     *                         The requirements are encoded with
17279     *                         {@link android.view.View.MeasureSpec}.
17280     *
17281     * @see #getMeasuredWidth()
17282     * @see #getMeasuredHeight()
17283     * @see #setMeasuredDimension(int, int)
17284     * @see #getSuggestedMinimumHeight()
17285     * @see #getSuggestedMinimumWidth()
17286     * @see android.view.View.MeasureSpec#getMode(int)
17287     * @see android.view.View.MeasureSpec#getSize(int)
17288     */
17289    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
17290        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
17291                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
17292    }
17293
17294    /**
17295     * <p>This method must be called by {@link #onMeasure(int, int)} to store the
17296     * measured width and measured height. Failing to do so will trigger an
17297     * exception at measurement time.</p>
17298     *
17299     * @param measuredWidth The measured width of this view.  May be a complex
17300     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17301     * {@link #MEASURED_STATE_TOO_SMALL}.
17302     * @param measuredHeight The measured height of this view.  May be a complex
17303     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17304     * {@link #MEASURED_STATE_TOO_SMALL}.
17305     */
17306    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
17307        boolean optical = isLayoutModeOptical(this);
17308        if (optical != isLayoutModeOptical(mParent)) {
17309            Insets insets = getOpticalInsets();
17310            int opticalWidth  = insets.left + insets.right;
17311            int opticalHeight = insets.top  + insets.bottom;
17312
17313            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
17314            measuredHeight += optical ? opticalHeight : -opticalHeight;
17315        }
17316        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
17317    }
17318
17319    /**
17320     * Sets the measured dimension without extra processing for things like optical bounds.
17321     * Useful for reapplying consistent values that have already been cooked with adjustments
17322     * for optical bounds, etc. such as those from the measurement cache.
17323     *
17324     * @param measuredWidth The measured width of this view.  May be a complex
17325     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17326     * {@link #MEASURED_STATE_TOO_SMALL}.
17327     * @param measuredHeight The measured height of this view.  May be a complex
17328     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
17329     * {@link #MEASURED_STATE_TOO_SMALL}.
17330     */
17331    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
17332        mMeasuredWidth = measuredWidth;
17333        mMeasuredHeight = measuredHeight;
17334
17335        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
17336    }
17337
17338    /**
17339     * Merge two states as returned by {@link #getMeasuredState()}.
17340     * @param curState The current state as returned from a view or the result
17341     * of combining multiple views.
17342     * @param newState The new view state to combine.
17343     * @return Returns a new integer reflecting the combination of the two
17344     * states.
17345     */
17346    public static int combineMeasuredStates(int curState, int newState) {
17347        return curState | newState;
17348    }
17349
17350    /**
17351     * Version of {@link #resolveSizeAndState(int, int, int)}
17352     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
17353     */
17354    public static int resolveSize(int size, int measureSpec) {
17355        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
17356    }
17357
17358    /**
17359     * Utility to reconcile a desired size and state, with constraints imposed
17360     * by a MeasureSpec.  Will take the desired size, unless a different size
17361     * is imposed by the constraints.  The returned value is a compound integer,
17362     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
17363     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
17364     * size is smaller than the size the view wants to be.
17365     *
17366     * @param size How big the view wants to be
17367     * @param measureSpec Constraints imposed by the parent
17368     * @return Size information bit mask as defined by
17369     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
17370     */
17371    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
17372        int result = size;
17373        int specMode = MeasureSpec.getMode(measureSpec);
17374        int specSize =  MeasureSpec.getSize(measureSpec);
17375        switch (specMode) {
17376        case MeasureSpec.UNSPECIFIED:
17377            result = size;
17378            break;
17379        case MeasureSpec.AT_MOST:
17380            if (specSize < size) {
17381                result = specSize | MEASURED_STATE_TOO_SMALL;
17382            } else {
17383                result = size;
17384            }
17385            break;
17386        case MeasureSpec.EXACTLY:
17387            result = specSize;
17388            break;
17389        }
17390        return result | (childMeasuredState&MEASURED_STATE_MASK);
17391    }
17392
17393    /**
17394     * Utility to return a default size. Uses the supplied size if the
17395     * MeasureSpec imposed no constraints. Will get larger if allowed
17396     * by the MeasureSpec.
17397     *
17398     * @param size Default size for this view
17399     * @param measureSpec Constraints imposed by the parent
17400     * @return The size this view should be.
17401     */
17402    public static int getDefaultSize(int size, int measureSpec) {
17403        int result = size;
17404        int specMode = MeasureSpec.getMode(measureSpec);
17405        int specSize = MeasureSpec.getSize(measureSpec);
17406
17407        switch (specMode) {
17408        case MeasureSpec.UNSPECIFIED:
17409            result = size;
17410            break;
17411        case MeasureSpec.AT_MOST:
17412        case MeasureSpec.EXACTLY:
17413            result = specSize;
17414            break;
17415        }
17416        return result;
17417    }
17418
17419    /**
17420     * Returns the suggested minimum height that the view should use. This
17421     * returns the maximum of the view's minimum height
17422     * and the background's minimum height
17423     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
17424     * <p>
17425     * When being used in {@link #onMeasure(int, int)}, the caller should still
17426     * ensure the returned height is within the requirements of the parent.
17427     *
17428     * @return The suggested minimum height of the view.
17429     */
17430    protected int getSuggestedMinimumHeight() {
17431        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
17432
17433    }
17434
17435    /**
17436     * Returns the suggested minimum width that the view should use. This
17437     * returns the maximum of the view's minimum width)
17438     * and the background's minimum width
17439     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
17440     * <p>
17441     * When being used in {@link #onMeasure(int, int)}, the caller should still
17442     * ensure the returned width is within the requirements of the parent.
17443     *
17444     * @return The suggested minimum width of the view.
17445     */
17446    protected int getSuggestedMinimumWidth() {
17447        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
17448    }
17449
17450    /**
17451     * Returns the minimum height of the view.
17452     *
17453     * @return the minimum height the view will try to be.
17454     *
17455     * @see #setMinimumHeight(int)
17456     *
17457     * @attr ref android.R.styleable#View_minHeight
17458     */
17459    public int getMinimumHeight() {
17460        return mMinHeight;
17461    }
17462
17463    /**
17464     * Sets the minimum height of the view. It is not guaranteed the view will
17465     * be able to achieve this minimum height (for example, if its parent layout
17466     * constrains it with less available height).
17467     *
17468     * @param minHeight The minimum height the view will try to be.
17469     *
17470     * @see #getMinimumHeight()
17471     *
17472     * @attr ref android.R.styleable#View_minHeight
17473     */
17474    public void setMinimumHeight(int minHeight) {
17475        mMinHeight = minHeight;
17476        requestLayout();
17477    }
17478
17479    /**
17480     * Returns the minimum width of the view.
17481     *
17482     * @return the minimum width the view will try to be.
17483     *
17484     * @see #setMinimumWidth(int)
17485     *
17486     * @attr ref android.R.styleable#View_minWidth
17487     */
17488    public int getMinimumWidth() {
17489        return mMinWidth;
17490    }
17491
17492    /**
17493     * Sets the minimum width of the view. It is not guaranteed the view will
17494     * be able to achieve this minimum width (for example, if its parent layout
17495     * constrains it with less available width).
17496     *
17497     * @param minWidth The minimum width the view will try to be.
17498     *
17499     * @see #getMinimumWidth()
17500     *
17501     * @attr ref android.R.styleable#View_minWidth
17502     */
17503    public void setMinimumWidth(int minWidth) {
17504        mMinWidth = minWidth;
17505        requestLayout();
17506
17507    }
17508
17509    /**
17510     * Get the animation currently associated with this view.
17511     *
17512     * @return The animation that is currently playing or
17513     *         scheduled to play for this view.
17514     */
17515    public Animation getAnimation() {
17516        return mCurrentAnimation;
17517    }
17518
17519    /**
17520     * Start the specified animation now.
17521     *
17522     * @param animation the animation to start now
17523     */
17524    public void startAnimation(Animation animation) {
17525        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
17526        setAnimation(animation);
17527        invalidateParentCaches();
17528        invalidate(true);
17529    }
17530
17531    /**
17532     * Cancels any animations for this view.
17533     */
17534    public void clearAnimation() {
17535        if (mCurrentAnimation != null) {
17536            mCurrentAnimation.detach();
17537        }
17538        mCurrentAnimation = null;
17539        invalidateParentIfNeeded();
17540    }
17541
17542    /**
17543     * Sets the next animation to play for this view.
17544     * If you want the animation to play immediately, use
17545     * {@link #startAnimation(android.view.animation.Animation)} instead.
17546     * This method provides allows fine-grained
17547     * control over the start time and invalidation, but you
17548     * must make sure that 1) the animation has a start time set, and
17549     * 2) the view's parent (which controls animations on its children)
17550     * will be invalidated when the animation is supposed to
17551     * start.
17552     *
17553     * @param animation The next animation, or null.
17554     */
17555    public void setAnimation(Animation animation) {
17556        mCurrentAnimation = animation;
17557
17558        if (animation != null) {
17559            // If the screen is off assume the animation start time is now instead of
17560            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
17561            // would cause the animation to start when the screen turns back on
17562            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
17563                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
17564                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
17565            }
17566            animation.reset();
17567        }
17568    }
17569
17570    /**
17571     * Invoked by a parent ViewGroup to notify the start of the animation
17572     * currently associated with this view. If you override this method,
17573     * always call super.onAnimationStart();
17574     *
17575     * @see #setAnimation(android.view.animation.Animation)
17576     * @see #getAnimation()
17577     */
17578    protected void onAnimationStart() {
17579        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
17580    }
17581
17582    /**
17583     * Invoked by a parent ViewGroup to notify the end of the animation
17584     * currently associated with this view. If you override this method,
17585     * always call super.onAnimationEnd();
17586     *
17587     * @see #setAnimation(android.view.animation.Animation)
17588     * @see #getAnimation()
17589     */
17590    protected void onAnimationEnd() {
17591        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
17592    }
17593
17594    /**
17595     * Invoked if there is a Transform that involves alpha. Subclass that can
17596     * draw themselves with the specified alpha should return true, and then
17597     * respect that alpha when their onDraw() is called. If this returns false
17598     * then the view may be redirected to draw into an offscreen buffer to
17599     * fulfill the request, which will look fine, but may be slower than if the
17600     * subclass handles it internally. The default implementation returns false.
17601     *
17602     * @param alpha The alpha (0..255) to apply to the view's drawing
17603     * @return true if the view can draw with the specified alpha.
17604     */
17605    protected boolean onSetAlpha(int alpha) {
17606        return false;
17607    }
17608
17609    /**
17610     * This is used by the RootView to perform an optimization when
17611     * the view hierarchy contains one or several SurfaceView.
17612     * SurfaceView is always considered transparent, but its children are not,
17613     * therefore all View objects remove themselves from the global transparent
17614     * region (passed as a parameter to this function).
17615     *
17616     * @param region The transparent region for this ViewAncestor (window).
17617     *
17618     * @return Returns true if the effective visibility of the view at this
17619     * point is opaque, regardless of the transparent region; returns false
17620     * if it is possible for underlying windows to be seen behind the view.
17621     *
17622     * {@hide}
17623     */
17624    public boolean gatherTransparentRegion(Region region) {
17625        final AttachInfo attachInfo = mAttachInfo;
17626        if (region != null && attachInfo != null) {
17627            final int pflags = mPrivateFlags;
17628            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
17629                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
17630                // remove it from the transparent region.
17631                final int[] location = attachInfo.mTransparentLocation;
17632                getLocationInWindow(location);
17633                region.op(location[0], location[1], location[0] + mRight - mLeft,
17634                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
17635            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null &&
17636                    mBackground.getOpacity() != PixelFormat.TRANSPARENT) {
17637                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
17638                // exists, so we remove the background drawable's non-transparent
17639                // parts from this transparent region.
17640                applyDrawableToTransparentRegion(mBackground, region);
17641            }
17642        }
17643        return true;
17644    }
17645
17646    /**
17647     * Play a sound effect for this view.
17648     *
17649     * <p>The framework will play sound effects for some built in actions, such as
17650     * clicking, but you may wish to play these effects in your widget,
17651     * for instance, for internal navigation.
17652     *
17653     * <p>The sound effect will only be played if sound effects are enabled by the user, and
17654     * {@link #isSoundEffectsEnabled()} is true.
17655     *
17656     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
17657     */
17658    public void playSoundEffect(int soundConstant) {
17659        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
17660            return;
17661        }
17662        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
17663    }
17664
17665    /**
17666     * BZZZTT!!1!
17667     *
17668     * <p>Provide haptic feedback to the user for this view.
17669     *
17670     * <p>The framework will provide haptic feedback for some built in actions,
17671     * such as long presses, but you may wish to provide feedback for your
17672     * own widget.
17673     *
17674     * <p>The feedback will only be performed if
17675     * {@link #isHapticFeedbackEnabled()} is true.
17676     *
17677     * @param feedbackConstant One of the constants defined in
17678     * {@link HapticFeedbackConstants}
17679     */
17680    public boolean performHapticFeedback(int feedbackConstant) {
17681        return performHapticFeedback(feedbackConstant, 0);
17682    }
17683
17684    /**
17685     * BZZZTT!!1!
17686     *
17687     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
17688     *
17689     * @param feedbackConstant One of the constants defined in
17690     * {@link HapticFeedbackConstants}
17691     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
17692     */
17693    public boolean performHapticFeedback(int feedbackConstant, int flags) {
17694        if (mAttachInfo == null) {
17695            return false;
17696        }
17697        //noinspection SimplifiableIfStatement
17698        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
17699                && !isHapticFeedbackEnabled()) {
17700            return false;
17701        }
17702        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
17703                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
17704    }
17705
17706    /**
17707     * Request that the visibility of the status bar or other screen/window
17708     * decorations be changed.
17709     *
17710     * <p>This method is used to put the over device UI into temporary modes
17711     * where the user's attention is focused more on the application content,
17712     * by dimming or hiding surrounding system affordances.  This is typically
17713     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
17714     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
17715     * to be placed behind the action bar (and with these flags other system
17716     * affordances) so that smooth transitions between hiding and showing them
17717     * can be done.
17718     *
17719     * <p>Two representative examples of the use of system UI visibility is
17720     * implementing a content browsing application (like a magazine reader)
17721     * and a video playing application.
17722     *
17723     * <p>The first code shows a typical implementation of a View in a content
17724     * browsing application.  In this implementation, the application goes
17725     * into a content-oriented mode by hiding the status bar and action bar,
17726     * and putting the navigation elements into lights out mode.  The user can
17727     * then interact with content while in this mode.  Such an application should
17728     * provide an easy way for the user to toggle out of the mode (such as to
17729     * check information in the status bar or access notifications).  In the
17730     * implementation here, this is done simply by tapping on the content.
17731     *
17732     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
17733     *      content}
17734     *
17735     * <p>This second code sample shows a typical implementation of a View
17736     * in a video playing application.  In this situation, while the video is
17737     * playing the application would like to go into a complete full-screen mode,
17738     * to use as much of the display as possible for the video.  When in this state
17739     * the user can not interact with the application; the system intercepts
17740     * touching on the screen to pop the UI out of full screen mode.  See
17741     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
17742     *
17743     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
17744     *      content}
17745     *
17746     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17747     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17748     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17749     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17750     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17751     */
17752    public void setSystemUiVisibility(int visibility) {
17753        if (visibility != mSystemUiVisibility) {
17754            mSystemUiVisibility = visibility;
17755            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17756                mParent.recomputeViewAttributes(this);
17757            }
17758        }
17759    }
17760
17761    /**
17762     * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested.
17763     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17764     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
17765     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
17766     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
17767     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
17768     */
17769    public int getSystemUiVisibility() {
17770        return mSystemUiVisibility;
17771    }
17772
17773    /**
17774     * Returns the current system UI visibility that is currently set for
17775     * the entire window.  This is the combination of the
17776     * {@link #setSystemUiVisibility(int)} values supplied by all of the
17777     * views in the window.
17778     */
17779    public int getWindowSystemUiVisibility() {
17780        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
17781    }
17782
17783    /**
17784     * Override to find out when the window's requested system UI visibility
17785     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
17786     * This is different from the callbacks received through
17787     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
17788     * in that this is only telling you about the local request of the window,
17789     * not the actual values applied by the system.
17790     */
17791    public void onWindowSystemUiVisibilityChanged(int visible) {
17792    }
17793
17794    /**
17795     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
17796     * the view hierarchy.
17797     */
17798    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
17799        onWindowSystemUiVisibilityChanged(visible);
17800    }
17801
17802    /**
17803     * Set a listener to receive callbacks when the visibility of the system bar changes.
17804     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
17805     */
17806    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
17807        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
17808        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
17809            mParent.recomputeViewAttributes(this);
17810        }
17811    }
17812
17813    /**
17814     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
17815     * the view hierarchy.
17816     */
17817    public void dispatchSystemUiVisibilityChanged(int visibility) {
17818        ListenerInfo li = mListenerInfo;
17819        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
17820            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
17821                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
17822        }
17823    }
17824
17825    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
17826        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
17827        if (val != mSystemUiVisibility) {
17828            setSystemUiVisibility(val);
17829            return true;
17830        }
17831        return false;
17832    }
17833
17834    /** @hide */
17835    public void setDisabledSystemUiVisibility(int flags) {
17836        if (mAttachInfo != null) {
17837            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
17838                mAttachInfo.mDisabledSystemUiVisibility = flags;
17839                if (mParent != null) {
17840                    mParent.recomputeViewAttributes(this);
17841                }
17842            }
17843        }
17844    }
17845
17846    /**
17847     * Creates an image that the system displays during the drag and drop
17848     * operation. This is called a &quot;drag shadow&quot;. The default implementation
17849     * for a DragShadowBuilder based on a View returns an image that has exactly the same
17850     * appearance as the given View. The default also positions the center of the drag shadow
17851     * directly under the touch point. If no View is provided (the constructor with no parameters
17852     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
17853     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
17854     * default is an invisible drag shadow.
17855     * <p>
17856     * You are not required to use the View you provide to the constructor as the basis of the
17857     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
17858     * anything you want as the drag shadow.
17859     * </p>
17860     * <p>
17861     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
17862     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
17863     *  size and position of the drag shadow. It uses this data to construct a
17864     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
17865     *  so that your application can draw the shadow image in the Canvas.
17866     * </p>
17867     *
17868     * <div class="special reference">
17869     * <h3>Developer Guides</h3>
17870     * <p>For a guide to implementing drag and drop features, read the
17871     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17872     * </div>
17873     */
17874    public static class DragShadowBuilder {
17875        private final WeakReference<View> mView;
17876
17877        /**
17878         * Constructs a shadow image builder based on a View. By default, the resulting drag
17879         * shadow will have the same appearance and dimensions as the View, with the touch point
17880         * over the center of the View.
17881         * @param view A View. Any View in scope can be used.
17882         */
17883        public DragShadowBuilder(View view) {
17884            mView = new WeakReference<View>(view);
17885        }
17886
17887        /**
17888         * Construct a shadow builder object with no associated View.  This
17889         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
17890         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
17891         * to supply the drag shadow's dimensions and appearance without
17892         * reference to any View object. If they are not overridden, then the result is an
17893         * invisible drag shadow.
17894         */
17895        public DragShadowBuilder() {
17896            mView = new WeakReference<View>(null);
17897        }
17898
17899        /**
17900         * Returns the View object that had been passed to the
17901         * {@link #View.DragShadowBuilder(View)}
17902         * constructor.  If that View parameter was {@code null} or if the
17903         * {@link #View.DragShadowBuilder()}
17904         * constructor was used to instantiate the builder object, this method will return
17905         * null.
17906         *
17907         * @return The View object associate with this builder object.
17908         */
17909        @SuppressWarnings({"JavadocReference"})
17910        final public View getView() {
17911            return mView.get();
17912        }
17913
17914        /**
17915         * Provides the metrics for the shadow image. These include the dimensions of
17916         * the shadow image, and the point within that shadow that should
17917         * be centered under the touch location while dragging.
17918         * <p>
17919         * The default implementation sets the dimensions of the shadow to be the
17920         * same as the dimensions of the View itself and centers the shadow under
17921         * the touch point.
17922         * </p>
17923         *
17924         * @param shadowSize A {@link android.graphics.Point} containing the width and height
17925         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
17926         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
17927         * image.
17928         *
17929         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
17930         * shadow image that should be underneath the touch point during the drag and drop
17931         * operation. Your application must set {@link android.graphics.Point#x} to the
17932         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
17933         */
17934        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
17935            final View view = mView.get();
17936            if (view != null) {
17937                shadowSize.set(view.getWidth(), view.getHeight());
17938                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
17939            } else {
17940                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
17941            }
17942        }
17943
17944        /**
17945         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
17946         * based on the dimensions it received from the
17947         * {@link #onProvideShadowMetrics(Point, Point)} callback.
17948         *
17949         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
17950         */
17951        public void onDrawShadow(Canvas canvas) {
17952            final View view = mView.get();
17953            if (view != null) {
17954                view.draw(canvas);
17955            } else {
17956                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
17957            }
17958        }
17959    }
17960
17961    /**
17962     * Starts a drag and drop operation. When your application calls this method, it passes a
17963     * {@link android.view.View.DragShadowBuilder} object to the system. The
17964     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
17965     * to get metrics for the drag shadow, and then calls the object's
17966     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
17967     * <p>
17968     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
17969     *  drag events to all the View objects in your application that are currently visible. It does
17970     *  this either by calling the View object's drag listener (an implementation of
17971     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
17972     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
17973     *  Both are passed a {@link android.view.DragEvent} object that has a
17974     *  {@link android.view.DragEvent#getAction()} value of
17975     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
17976     * </p>
17977     * <p>
17978     * Your application can invoke startDrag() on any attached View object. The View object does not
17979     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
17980     * be related to the View the user selected for dragging.
17981     * </p>
17982     * @param data A {@link android.content.ClipData} object pointing to the data to be
17983     * transferred by the drag and drop operation.
17984     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
17985     * drag shadow.
17986     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
17987     * drop operation. This Object is put into every DragEvent object sent by the system during the
17988     * current drag.
17989     * <p>
17990     * myLocalState is a lightweight mechanism for the sending information from the dragged View
17991     * to the target Views. For example, it can contain flags that differentiate between a
17992     * a copy operation and a move operation.
17993     * </p>
17994     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
17995     * so the parameter should be set to 0.
17996     * @return {@code true} if the method completes successfully, or
17997     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
17998     * do a drag, and so no drag operation is in progress.
17999     */
18000    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
18001            Object myLocalState, int flags) {
18002        if (ViewDebug.DEBUG_DRAG) {
18003            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
18004        }
18005        boolean okay = false;
18006
18007        Point shadowSize = new Point();
18008        Point shadowTouchPoint = new Point();
18009        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
18010
18011        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
18012                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
18013            throw new IllegalStateException("Drag shadow dimensions must not be negative");
18014        }
18015
18016        if (ViewDebug.DEBUG_DRAG) {
18017            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
18018                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
18019        }
18020        Surface surface = new Surface();
18021        try {
18022            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
18023                    flags, shadowSize.x, shadowSize.y, surface);
18024            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
18025                    + " surface=" + surface);
18026            if (token != null) {
18027                Canvas canvas = surface.lockCanvas(null);
18028                try {
18029                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
18030                    shadowBuilder.onDrawShadow(canvas);
18031                } finally {
18032                    surface.unlockCanvasAndPost(canvas);
18033                }
18034
18035                final ViewRootImpl root = getViewRootImpl();
18036
18037                // Cache the local state object for delivery with DragEvents
18038                root.setLocalDragState(myLocalState);
18039
18040                // repurpose 'shadowSize' for the last touch point
18041                root.getLastTouchPoint(shadowSize);
18042
18043                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
18044                        shadowSize.x, shadowSize.y,
18045                        shadowTouchPoint.x, shadowTouchPoint.y, data);
18046                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
18047
18048                // Off and running!  Release our local surface instance; the drag
18049                // shadow surface is now managed by the system process.
18050                surface.release();
18051            }
18052        } catch (Exception e) {
18053            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
18054            surface.destroy();
18055        }
18056
18057        return okay;
18058    }
18059
18060    /**
18061     * Handles drag events sent by the system following a call to
18062     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
18063     *<p>
18064     * When the system calls this method, it passes a
18065     * {@link android.view.DragEvent} object. A call to
18066     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
18067     * in DragEvent. The method uses these to determine what is happening in the drag and drop
18068     * operation.
18069     * @param event The {@link android.view.DragEvent} sent by the system.
18070     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
18071     * in DragEvent, indicating the type of drag event represented by this object.
18072     * @return {@code true} if the method was successful, otherwise {@code false}.
18073     * <p>
18074     *  The method should return {@code true} in response to an action type of
18075     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
18076     *  operation.
18077     * </p>
18078     * <p>
18079     *  The method should also return {@code true} in response to an action type of
18080     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
18081     *  {@code false} if it didn't.
18082     * </p>
18083     */
18084    public boolean onDragEvent(DragEvent event) {
18085        return false;
18086    }
18087
18088    /**
18089     * Detects if this View is enabled and has a drag event listener.
18090     * If both are true, then it calls the drag event listener with the
18091     * {@link android.view.DragEvent} it received. If the drag event listener returns
18092     * {@code true}, then dispatchDragEvent() returns {@code true}.
18093     * <p>
18094     * For all other cases, the method calls the
18095     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
18096     * method and returns its result.
18097     * </p>
18098     * <p>
18099     * This ensures that a drag event is always consumed, even if the View does not have a drag
18100     * event listener. However, if the View has a listener and the listener returns true, then
18101     * onDragEvent() is not called.
18102     * </p>
18103     */
18104    public boolean dispatchDragEvent(DragEvent event) {
18105        ListenerInfo li = mListenerInfo;
18106        //noinspection SimplifiableIfStatement
18107        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
18108                && li.mOnDragListener.onDrag(this, event)) {
18109            return true;
18110        }
18111        return onDragEvent(event);
18112    }
18113
18114    boolean canAcceptDrag() {
18115        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
18116    }
18117
18118    /**
18119     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
18120     * it is ever exposed at all.
18121     * @hide
18122     */
18123    public void onCloseSystemDialogs(String reason) {
18124    }
18125
18126    /**
18127     * Given a Drawable whose bounds have been set to draw into this view,
18128     * update a Region being computed for
18129     * {@link #gatherTransparentRegion(android.graphics.Region)} so
18130     * that any non-transparent parts of the Drawable are removed from the
18131     * given transparent region.
18132     *
18133     * @param dr The Drawable whose transparency is to be applied to the region.
18134     * @param region A Region holding the current transparency information,
18135     * where any parts of the region that are set are considered to be
18136     * transparent.  On return, this region will be modified to have the
18137     * transparency information reduced by the corresponding parts of the
18138     * Drawable that are not transparent.
18139     * {@hide}
18140     */
18141    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
18142        if (DBG) {
18143            Log.i("View", "Getting transparent region for: " + this);
18144        }
18145        final Region r = dr.getTransparentRegion();
18146        final Rect db = dr.getBounds();
18147        final AttachInfo attachInfo = mAttachInfo;
18148        if (r != null && attachInfo != null) {
18149            final int w = getRight()-getLeft();
18150            final int h = getBottom()-getTop();
18151            if (db.left > 0) {
18152                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
18153                r.op(0, 0, db.left, h, Region.Op.UNION);
18154            }
18155            if (db.right < w) {
18156                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
18157                r.op(db.right, 0, w, h, Region.Op.UNION);
18158            }
18159            if (db.top > 0) {
18160                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
18161                r.op(0, 0, w, db.top, Region.Op.UNION);
18162            }
18163            if (db.bottom < h) {
18164                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
18165                r.op(0, db.bottom, w, h, Region.Op.UNION);
18166            }
18167            final int[] location = attachInfo.mTransparentLocation;
18168            getLocationInWindow(location);
18169            r.translate(location[0], location[1]);
18170            region.op(r, Region.Op.INTERSECT);
18171        } else {
18172            region.op(db, Region.Op.DIFFERENCE);
18173        }
18174    }
18175
18176    private void checkForLongClick(int delayOffset) {
18177        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
18178            mHasPerformedLongPress = false;
18179
18180            if (mPendingCheckForLongPress == null) {
18181                mPendingCheckForLongPress = new CheckForLongPress();
18182            }
18183            mPendingCheckForLongPress.rememberWindowAttachCount();
18184            postDelayed(mPendingCheckForLongPress,
18185                    ViewConfiguration.getLongPressTimeout() - delayOffset);
18186        }
18187    }
18188
18189    /**
18190     * Inflate a view from an XML resource.  This convenience method wraps the {@link
18191     * LayoutInflater} class, which provides a full range of options for view inflation.
18192     *
18193     * @param context The Context object for your activity or application.
18194     * @param resource The resource ID to inflate
18195     * @param root A view group that will be the parent.  Used to properly inflate the
18196     * layout_* parameters.
18197     * @see LayoutInflater
18198     */
18199    public static View inflate(Context context, int resource, ViewGroup root) {
18200        LayoutInflater factory = LayoutInflater.from(context);
18201        return factory.inflate(resource, root);
18202    }
18203
18204    /**
18205     * Scroll the view with standard behavior for scrolling beyond the normal
18206     * content boundaries. Views that call this method should override
18207     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
18208     * results of an over-scroll operation.
18209     *
18210     * Views can use this method to handle any touch or fling-based scrolling.
18211     *
18212     * @param deltaX Change in X in pixels
18213     * @param deltaY Change in Y in pixels
18214     * @param scrollX Current X scroll value in pixels before applying deltaX
18215     * @param scrollY Current Y scroll value in pixels before applying deltaY
18216     * @param scrollRangeX Maximum content scroll range along the X axis
18217     * @param scrollRangeY Maximum content scroll range along the Y axis
18218     * @param maxOverScrollX Number of pixels to overscroll by in either direction
18219     *          along the X axis.
18220     * @param maxOverScrollY Number of pixels to overscroll by in either direction
18221     *          along the Y axis.
18222     * @param isTouchEvent true if this scroll operation is the result of a touch event.
18223     * @return true if scrolling was clamped to an over-scroll boundary along either
18224     *          axis, false otherwise.
18225     */
18226    @SuppressWarnings({"UnusedParameters"})
18227    protected boolean overScrollBy(int deltaX, int deltaY,
18228            int scrollX, int scrollY,
18229            int scrollRangeX, int scrollRangeY,
18230            int maxOverScrollX, int maxOverScrollY,
18231            boolean isTouchEvent) {
18232        final int overScrollMode = mOverScrollMode;
18233        final boolean canScrollHorizontal =
18234                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
18235        final boolean canScrollVertical =
18236                computeVerticalScrollRange() > computeVerticalScrollExtent();
18237        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
18238                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
18239        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
18240                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
18241
18242        int newScrollX = scrollX + deltaX;
18243        if (!overScrollHorizontal) {
18244            maxOverScrollX = 0;
18245        }
18246
18247        int newScrollY = scrollY + deltaY;
18248        if (!overScrollVertical) {
18249            maxOverScrollY = 0;
18250        }
18251
18252        // Clamp values if at the limits and record
18253        final int left = -maxOverScrollX;
18254        final int right = maxOverScrollX + scrollRangeX;
18255        final int top = -maxOverScrollY;
18256        final int bottom = maxOverScrollY + scrollRangeY;
18257
18258        boolean clampedX = false;
18259        if (newScrollX > right) {
18260            newScrollX = right;
18261            clampedX = true;
18262        } else if (newScrollX < left) {
18263            newScrollX = left;
18264            clampedX = true;
18265        }
18266
18267        boolean clampedY = false;
18268        if (newScrollY > bottom) {
18269            newScrollY = bottom;
18270            clampedY = true;
18271        } else if (newScrollY < top) {
18272            newScrollY = top;
18273            clampedY = true;
18274        }
18275
18276        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
18277
18278        return clampedX || clampedY;
18279    }
18280
18281    /**
18282     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
18283     * respond to the results of an over-scroll operation.
18284     *
18285     * @param scrollX New X scroll value in pixels
18286     * @param scrollY New Y scroll value in pixels
18287     * @param clampedX True if scrollX was clamped to an over-scroll boundary
18288     * @param clampedY True if scrollY was clamped to an over-scroll boundary
18289     */
18290    protected void onOverScrolled(int scrollX, int scrollY,
18291            boolean clampedX, boolean clampedY) {
18292        // Intentionally empty.
18293    }
18294
18295    /**
18296     * Returns the over-scroll mode for this view. The result will be
18297     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18298     * (allow over-scrolling only if the view content is larger than the container),
18299     * or {@link #OVER_SCROLL_NEVER}.
18300     *
18301     * @return This view's over-scroll mode.
18302     */
18303    public int getOverScrollMode() {
18304        return mOverScrollMode;
18305    }
18306
18307    /**
18308     * Set the over-scroll mode for this view. Valid over-scroll modes are
18309     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
18310     * (allow over-scrolling only if the view content is larger than the container),
18311     * or {@link #OVER_SCROLL_NEVER}.
18312     *
18313     * Setting the over-scroll mode of a view will have an effect only if the
18314     * view is capable of scrolling.
18315     *
18316     * @param overScrollMode The new over-scroll mode for this view.
18317     */
18318    public void setOverScrollMode(int overScrollMode) {
18319        if (overScrollMode != OVER_SCROLL_ALWAYS &&
18320                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
18321                overScrollMode != OVER_SCROLL_NEVER) {
18322            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
18323        }
18324        mOverScrollMode = overScrollMode;
18325    }
18326
18327    /**
18328     * Enable or disable nested scrolling for this view.
18329     *
18330     * <p>If this property is set to true the view will be permitted to initiate nested
18331     * scrolling operations with a compatible parent view in the current hierarchy. If this
18332     * view does not implement nested scrolling this will have no effect. Disabling nested scrolling
18333     * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping}
18334     * the nested scroll.</p>
18335     *
18336     * @param enabled true to enable nested scrolling, false to disable
18337     *
18338     * @see #isNestedScrollingEnabled()
18339     */
18340    public void setNestedScrollingEnabled(boolean enabled) {
18341        if (enabled) {
18342            mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED;
18343        } else {
18344            stopNestedScroll();
18345            mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED;
18346        }
18347    }
18348
18349    /**
18350     * Returns true if nested scrolling is enabled for this view.
18351     *
18352     * <p>If nested scrolling is enabled and this View class implementation supports it,
18353     * this view will act as a nested scrolling child view when applicable, forwarding data
18354     * about the scroll operation in progress to a compatible and cooperating nested scrolling
18355     * parent.</p>
18356     *
18357     * @return true if nested scrolling is enabled
18358     *
18359     * @see #setNestedScrollingEnabled(boolean)
18360     */
18361    public boolean isNestedScrollingEnabled() {
18362        return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) ==
18363                PFLAG3_NESTED_SCROLLING_ENABLED;
18364    }
18365
18366    /**
18367     * Begin a nestable scroll operation along the given axes.
18368     *
18369     * <p>A view starting a nested scroll promises to abide by the following contract:</p>
18370     *
18371     * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case
18372     * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}.
18373     * In the case of touch scrolling the nested scroll will be terminated automatically in
18374     * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}.
18375     * In the event of programmatic scrolling the caller must explicitly call
18376     * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p>
18377     *
18378     * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found.
18379     * If it returns false the caller may ignore the rest of this contract until the next scroll.
18380     * Calling startNestedScroll while a nested scroll is already in progress will return true.</p>
18381     *
18382     * <p>At each incremental step of the scroll the caller should invoke
18383     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll}
18384     * once it has calculated the requested scrolling delta. If it returns true the nested scrolling
18385     * parent at least partially consumed the scroll and the caller should adjust the amount it
18386     * scrolls by.</p>
18387     *
18388     * <p>After applying the remainder of the scroll delta the caller should invoke
18389     * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing
18390     * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat
18391     * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}.
18392     * </p>
18393     *
18394     * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or
18395     *             {@link #SCROLL_AXIS_VERTICAL}.
18396     * @return true if a cooperative parent was found and nested scrolling has been enabled for
18397     *         the current gesture.
18398     *
18399     * @see #stopNestedScroll()
18400     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18401     * @see #dispatchNestedScroll(int, int, int, int, int[])
18402     */
18403    public boolean startNestedScroll(int axes) {
18404        if (hasNestedScrollingParent()) {
18405            // Already in progress
18406            return true;
18407        }
18408        if (isNestedScrollingEnabled()) {
18409            ViewParent p = getParent();
18410            View child = this;
18411            while (p != null) {
18412                try {
18413                    if (p.onStartNestedScroll(child, this, axes)) {
18414                        mNestedScrollingParent = p;
18415                        p.onNestedScrollAccepted(child, this, axes);
18416                        return true;
18417                    }
18418                } catch (AbstractMethodError e) {
18419                    Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " +
18420                            "method onStartNestedScroll", e);
18421                    // Allow the search upward to continue
18422                }
18423                if (p instanceof View) {
18424                    child = (View) p;
18425                }
18426                p = p.getParent();
18427            }
18428        }
18429        return false;
18430    }
18431
18432    /**
18433     * Stop a nested scroll in progress.
18434     *
18435     * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p>
18436     *
18437     * @see #startNestedScroll(int)
18438     */
18439    public void stopNestedScroll() {
18440        if (mNestedScrollingParent != null) {
18441            mNestedScrollingParent.onStopNestedScroll(this);
18442            mNestedScrollingParent = null;
18443        }
18444    }
18445
18446    /**
18447     * Returns true if this view has a nested scrolling parent.
18448     *
18449     * <p>The presence of a nested scrolling parent indicates that this view has initiated
18450     * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p>
18451     *
18452     * @return whether this view has a nested scrolling parent
18453     */
18454    public boolean hasNestedScrollingParent() {
18455        return mNestedScrollingParent != null;
18456    }
18457
18458    /**
18459     * Dispatch one step of a nested scroll in progress.
18460     *
18461     * <p>Implementations of views that support nested scrolling should call this to report
18462     * info about a scroll in progress to the current nested scrolling parent. If a nested scroll
18463     * is not currently in progress or nested scrolling is not
18464     * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p>
18465     *
18466     * <p>Compatible View implementations should also call
18467     * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before
18468     * consuming a component of the scroll event themselves.</p>
18469     *
18470     * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step
18471     * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step
18472     * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view
18473     * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view
18474     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18475     *                       in local view coordinates of this view from before this operation
18476     *                       to after it completes. View implementations may use this to adjust
18477     *                       expected input coordinate tracking.
18478     * @return true if the event was dispatched, false if it could not be dispatched.
18479     * @see #dispatchNestedPreScroll(int, int, int[], int[])
18480     */
18481    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
18482            int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
18483        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18484            if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) {
18485                int startX = 0;
18486                int startY = 0;
18487                if (offsetInWindow != null) {
18488                    getLocationInWindow(offsetInWindow);
18489                    startX = offsetInWindow[0];
18490                    startY = offsetInWindow[1];
18491                }
18492
18493                mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed,
18494                        dxUnconsumed, dyUnconsumed);
18495
18496                if (offsetInWindow != null) {
18497                    getLocationInWindow(offsetInWindow);
18498                    offsetInWindow[0] -= startX;
18499                    offsetInWindow[1] -= startY;
18500                }
18501                return true;
18502            } else if (offsetInWindow != null) {
18503                // No motion, no dispatch. Keep offsetInWindow up to date.
18504                offsetInWindow[0] = 0;
18505                offsetInWindow[1] = 0;
18506            }
18507        }
18508        return false;
18509    }
18510
18511    /**
18512     * Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
18513     *
18514     * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch.
18515     * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested
18516     * scrolling operation to consume some or all of the scroll operation before the child view
18517     * consumes it.</p>
18518     *
18519     * @param dx Horizontal scroll distance in pixels
18520     * @param dy Vertical scroll distance in pixels
18521     * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx
18522     *                 and consumed[1] the consumed dy.
18523     * @param offsetInWindow Optional. If not null, on return this will contain the offset
18524     *                       in local view coordinates of this view from before this operation
18525     *                       to after it completes. View implementations may use this to adjust
18526     *                       expected input coordinate tracking.
18527     * @return true if the parent consumed some or all of the scroll delta
18528     * @see #dispatchNestedScroll(int, int, int, int, int[])
18529     */
18530    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
18531        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18532            if (dx != 0 || dy != 0) {
18533                int startX = 0;
18534                int startY = 0;
18535                if (offsetInWindow != null) {
18536                    getLocationInWindow(offsetInWindow);
18537                    startX = offsetInWindow[0];
18538                    startY = offsetInWindow[1];
18539                }
18540
18541                if (consumed == null) {
18542                    if (mTempNestedScrollConsumed == null) {
18543                        mTempNestedScrollConsumed = new int[2];
18544                    }
18545                    consumed = mTempNestedScrollConsumed;
18546                }
18547                consumed[0] = 0;
18548                consumed[1] = 0;
18549                mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed);
18550
18551                if (offsetInWindow != null) {
18552                    getLocationInWindow(offsetInWindow);
18553                    offsetInWindow[0] -= startX;
18554                    offsetInWindow[1] -= startY;
18555                }
18556                return consumed[0] != 0 || consumed[1] != 0;
18557            } else if (offsetInWindow != null) {
18558                offsetInWindow[0] = 0;
18559                offsetInWindow[1] = 0;
18560            }
18561        }
18562        return false;
18563    }
18564
18565    /**
18566     * Dispatch a fling to a nested scrolling parent.
18567     *
18568     * <p>This method should be used to indicate that a nested scrolling child has detected
18569     * suitable conditions for a fling. Generally this means that a touch scroll has ended with a
18570     * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds
18571     * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity}
18572     * along a scrollable axis.</p>
18573     *
18574     * <p>If a nested scrolling child view would normally fling but it is at the edge of
18575     * its own content, it can use this method to delegate the fling to its nested scrolling
18576     * parent instead. The parent may optionally consume the fling or observe a child fling.</p>
18577     *
18578     * @param velocityX Horizontal fling velocity in pixels per second
18579     * @param velocityY Vertical fling velocity in pixels per second
18580     * @param consumed true if the child consumed the fling, false otherwise
18581     * @return true if the nested scrolling parent consumed or otherwise reacted to the fling
18582     */
18583    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
18584        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18585            return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed);
18586        }
18587        return false;
18588    }
18589
18590    /**
18591     * Dispatch a fling to a nested scrolling parent before it is processed by this view.
18592     *
18593     * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch
18594     * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code>
18595     * offsets an opportunity for the parent view in a nested fling to fully consume the fling
18596     * before the child view consumes it. If this method returns <code>true</code>, a nested
18597     * parent view consumed the fling and this view should not scroll as a result.</p>
18598     *
18599     * <p>For a better user experience, only one view in a nested scrolling chain should consume
18600     * the fling at a time. If a parent view consumed the fling this method will return false.
18601     * Custom view implementations should account for this in two ways:</p>
18602     *
18603     * <ul>
18604     *     <li>If a custom view is paged and needs to settle to a fixed page-point, do not
18605     *     call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid
18606     *     position regardless.</li>
18607     *     <li>If a nested parent does consume the fling, this view should not scroll at all,
18608     *     even to settle back to a valid idle position.</li>
18609     * </ul>
18610     *
18611     * <p>Views should also not offer fling velocities to nested parent views along an axis
18612     * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView}
18613     * should not offer a horizontal fling velocity to its parents since scrolling along that
18614     * axis is not permitted and carrying velocity along that motion does not make sense.</p>
18615     *
18616     * @param velocityX Horizontal fling velocity in pixels per second
18617     * @param velocityY Vertical fling velocity in pixels per second
18618     * @return true if a nested scrolling parent consumed the fling
18619     */
18620    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
18621        if (isNestedScrollingEnabled() && mNestedScrollingParent != null) {
18622            return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY);
18623        }
18624        return false;
18625    }
18626
18627    /**
18628     * Gets a scale factor that determines the distance the view should scroll
18629     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
18630     * @return The vertical scroll scale factor.
18631     * @hide
18632     */
18633    protected float getVerticalScrollFactor() {
18634        if (mVerticalScrollFactor == 0) {
18635            TypedValue outValue = new TypedValue();
18636            if (!mContext.getTheme().resolveAttribute(
18637                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
18638                throw new IllegalStateException(
18639                        "Expected theme to define listPreferredItemHeight.");
18640            }
18641            mVerticalScrollFactor = outValue.getDimension(
18642                    mContext.getResources().getDisplayMetrics());
18643        }
18644        return mVerticalScrollFactor;
18645    }
18646
18647    /**
18648     * Gets a scale factor that determines the distance the view should scroll
18649     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
18650     * @return The horizontal scroll scale factor.
18651     * @hide
18652     */
18653    protected float getHorizontalScrollFactor() {
18654        // TODO: Should use something else.
18655        return getVerticalScrollFactor();
18656    }
18657
18658    /**
18659     * Return the value specifying the text direction or policy that was set with
18660     * {@link #setTextDirection(int)}.
18661     *
18662     * @return the defined text direction. It can be one of:
18663     *
18664     * {@link #TEXT_DIRECTION_INHERIT},
18665     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18666     * {@link #TEXT_DIRECTION_ANY_RTL},
18667     * {@link #TEXT_DIRECTION_LTR},
18668     * {@link #TEXT_DIRECTION_RTL},
18669     * {@link #TEXT_DIRECTION_LOCALE}
18670     *
18671     * @attr ref android.R.styleable#View_textDirection
18672     *
18673     * @hide
18674     */
18675    @ViewDebug.ExportedProperty(category = "text", mapping = {
18676            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18677            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18678            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18679            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18680            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18681            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18682    })
18683    public int getRawTextDirection() {
18684        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
18685    }
18686
18687    /**
18688     * Set the text direction.
18689     *
18690     * @param textDirection the direction to set. Should be one of:
18691     *
18692     * {@link #TEXT_DIRECTION_INHERIT},
18693     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18694     * {@link #TEXT_DIRECTION_ANY_RTL},
18695     * {@link #TEXT_DIRECTION_LTR},
18696     * {@link #TEXT_DIRECTION_RTL},
18697     * {@link #TEXT_DIRECTION_LOCALE}
18698     *
18699     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
18700     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
18701     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
18702     *
18703     * @attr ref android.R.styleable#View_textDirection
18704     */
18705    public void setTextDirection(int textDirection) {
18706        if (getRawTextDirection() != textDirection) {
18707            // Reset the current text direction and the resolved one
18708            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
18709            resetResolvedTextDirection();
18710            // Set the new text direction
18711            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
18712            // Do resolution
18713            resolveTextDirection();
18714            // Notify change
18715            onRtlPropertiesChanged(getLayoutDirection());
18716            // Refresh
18717            requestLayout();
18718            invalidate(true);
18719        }
18720    }
18721
18722    /**
18723     * Return the resolved text direction.
18724     *
18725     * @return the resolved text direction. Returns one of:
18726     *
18727     * {@link #TEXT_DIRECTION_FIRST_STRONG}
18728     * {@link #TEXT_DIRECTION_ANY_RTL},
18729     * {@link #TEXT_DIRECTION_LTR},
18730     * {@link #TEXT_DIRECTION_RTL},
18731     * {@link #TEXT_DIRECTION_LOCALE}
18732     *
18733     * @attr ref android.R.styleable#View_textDirection
18734     */
18735    @ViewDebug.ExportedProperty(category = "text", mapping = {
18736            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
18737            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
18738            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
18739            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
18740            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
18741            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
18742    })
18743    public int getTextDirection() {
18744        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
18745    }
18746
18747    /**
18748     * Resolve the text direction.
18749     *
18750     * @return true if resolution has been done, false otherwise.
18751     *
18752     * @hide
18753     */
18754    public boolean resolveTextDirection() {
18755        // Reset any previous text direction resolution
18756        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18757
18758        if (hasRtlSupport()) {
18759            // Set resolved text direction flag depending on text direction flag
18760            final int textDirection = getRawTextDirection();
18761            switch(textDirection) {
18762                case TEXT_DIRECTION_INHERIT:
18763                    if (!canResolveTextDirection()) {
18764                        // We cannot do the resolution if there is no parent, so use the default one
18765                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18766                        // Resolution will need to happen again later
18767                        return false;
18768                    }
18769
18770                    // Parent has not yet resolved, so we still return the default
18771                    try {
18772                        if (!mParent.isTextDirectionResolved()) {
18773                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18774                            // Resolution will need to happen again later
18775                            return false;
18776                        }
18777                    } catch (AbstractMethodError e) {
18778                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18779                                " does not fully implement ViewParent", e);
18780                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED |
18781                                PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18782                        return true;
18783                    }
18784
18785                    // Set current resolved direction to the same value as the parent's one
18786                    int parentResolvedDirection;
18787                    try {
18788                        parentResolvedDirection = mParent.getTextDirection();
18789                    } catch (AbstractMethodError e) {
18790                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18791                                " does not fully implement ViewParent", e);
18792                        parentResolvedDirection = TEXT_DIRECTION_LTR;
18793                    }
18794                    switch (parentResolvedDirection) {
18795                        case TEXT_DIRECTION_FIRST_STRONG:
18796                        case TEXT_DIRECTION_ANY_RTL:
18797                        case TEXT_DIRECTION_LTR:
18798                        case TEXT_DIRECTION_RTL:
18799                        case TEXT_DIRECTION_LOCALE:
18800                            mPrivateFlags2 |=
18801                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18802                            break;
18803                        default:
18804                            // Default resolved direction is "first strong" heuristic
18805                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18806                    }
18807                    break;
18808                case TEXT_DIRECTION_FIRST_STRONG:
18809                case TEXT_DIRECTION_ANY_RTL:
18810                case TEXT_DIRECTION_LTR:
18811                case TEXT_DIRECTION_RTL:
18812                case TEXT_DIRECTION_LOCALE:
18813                    // Resolved direction is the same as text direction
18814                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
18815                    break;
18816                default:
18817                    // Default resolved direction is "first strong" heuristic
18818                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18819            }
18820        } else {
18821            // Default resolved direction is "first strong" heuristic
18822            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18823        }
18824
18825        // Set to resolved
18826        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
18827        return true;
18828    }
18829
18830    /**
18831     * Check if text direction resolution can be done.
18832     *
18833     * @return true if text direction resolution can be done otherwise return false.
18834     */
18835    public boolean canResolveTextDirection() {
18836        switch (getRawTextDirection()) {
18837            case TEXT_DIRECTION_INHERIT:
18838                if (mParent != null) {
18839                    try {
18840                        return mParent.canResolveTextDirection();
18841                    } catch (AbstractMethodError e) {
18842                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
18843                                " does not fully implement ViewParent", e);
18844                    }
18845                }
18846                return false;
18847
18848            default:
18849                return true;
18850        }
18851    }
18852
18853    /**
18854     * Reset resolved text direction. Text direction will be resolved during a call to
18855     * {@link #onMeasure(int, int)}.
18856     *
18857     * @hide
18858     */
18859    public void resetResolvedTextDirection() {
18860        // Reset any previous text direction resolution
18861        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
18862        // Set to default value
18863        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
18864    }
18865
18866    /**
18867     * @return true if text direction is inherited.
18868     *
18869     * @hide
18870     */
18871    public boolean isTextDirectionInherited() {
18872        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
18873    }
18874
18875    /**
18876     * @return true if text direction is resolved.
18877     */
18878    public boolean isTextDirectionResolved() {
18879        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
18880    }
18881
18882    /**
18883     * Return the value specifying the text alignment or policy that was set with
18884     * {@link #setTextAlignment(int)}.
18885     *
18886     * @return the defined text alignment. It can be one of:
18887     *
18888     * {@link #TEXT_ALIGNMENT_INHERIT},
18889     * {@link #TEXT_ALIGNMENT_GRAVITY},
18890     * {@link #TEXT_ALIGNMENT_CENTER},
18891     * {@link #TEXT_ALIGNMENT_TEXT_START},
18892     * {@link #TEXT_ALIGNMENT_TEXT_END},
18893     * {@link #TEXT_ALIGNMENT_VIEW_START},
18894     * {@link #TEXT_ALIGNMENT_VIEW_END}
18895     *
18896     * @attr ref android.R.styleable#View_textAlignment
18897     *
18898     * @hide
18899     */
18900    @ViewDebug.ExportedProperty(category = "text", mapping = {
18901            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18902            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18903            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18904            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18905            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18906            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18907            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18908    })
18909    @TextAlignment
18910    public int getRawTextAlignment() {
18911        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
18912    }
18913
18914    /**
18915     * Set the text alignment.
18916     *
18917     * @param textAlignment The text alignment to set. Should be one of
18918     *
18919     * {@link #TEXT_ALIGNMENT_INHERIT},
18920     * {@link #TEXT_ALIGNMENT_GRAVITY},
18921     * {@link #TEXT_ALIGNMENT_CENTER},
18922     * {@link #TEXT_ALIGNMENT_TEXT_START},
18923     * {@link #TEXT_ALIGNMENT_TEXT_END},
18924     * {@link #TEXT_ALIGNMENT_VIEW_START},
18925     * {@link #TEXT_ALIGNMENT_VIEW_END}
18926     *
18927     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
18928     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
18929     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
18930     *
18931     * @attr ref android.R.styleable#View_textAlignment
18932     */
18933    public void setTextAlignment(@TextAlignment int textAlignment) {
18934        if (textAlignment != getRawTextAlignment()) {
18935            // Reset the current and resolved text alignment
18936            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
18937            resetResolvedTextAlignment();
18938            // Set the new text alignment
18939            mPrivateFlags2 |=
18940                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
18941            // Do resolution
18942            resolveTextAlignment();
18943            // Notify change
18944            onRtlPropertiesChanged(getLayoutDirection());
18945            // Refresh
18946            requestLayout();
18947            invalidate(true);
18948        }
18949    }
18950
18951    /**
18952     * Return the resolved text alignment.
18953     *
18954     * @return the resolved text alignment. Returns one of:
18955     *
18956     * {@link #TEXT_ALIGNMENT_GRAVITY},
18957     * {@link #TEXT_ALIGNMENT_CENTER},
18958     * {@link #TEXT_ALIGNMENT_TEXT_START},
18959     * {@link #TEXT_ALIGNMENT_TEXT_END},
18960     * {@link #TEXT_ALIGNMENT_VIEW_START},
18961     * {@link #TEXT_ALIGNMENT_VIEW_END}
18962     *
18963     * @attr ref android.R.styleable#View_textAlignment
18964     */
18965    @ViewDebug.ExportedProperty(category = "text", mapping = {
18966            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
18967            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
18968            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
18969            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
18970            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
18971            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
18972            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
18973    })
18974    @TextAlignment
18975    public int getTextAlignment() {
18976        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
18977                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
18978    }
18979
18980    /**
18981     * Resolve the text alignment.
18982     *
18983     * @return true if resolution has been done, false otherwise.
18984     *
18985     * @hide
18986     */
18987    public boolean resolveTextAlignment() {
18988        // Reset any previous text alignment resolution
18989        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
18990
18991        if (hasRtlSupport()) {
18992            // Set resolved text alignment flag depending on text alignment flag
18993            final int textAlignment = getRawTextAlignment();
18994            switch (textAlignment) {
18995                case TEXT_ALIGNMENT_INHERIT:
18996                    // Check if we can resolve the text alignment
18997                    if (!canResolveTextAlignment()) {
18998                        // We cannot do the resolution if there is no parent so use the default
18999                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19000                        // Resolution will need to happen again later
19001                        return false;
19002                    }
19003
19004                    // Parent has not yet resolved, so we still return the default
19005                    try {
19006                        if (!mParent.isTextAlignmentResolved()) {
19007                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19008                            // Resolution will need to happen again later
19009                            return false;
19010                        }
19011                    } catch (AbstractMethodError e) {
19012                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19013                                " does not fully implement ViewParent", e);
19014                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED |
19015                                PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19016                        return true;
19017                    }
19018
19019                    int parentResolvedTextAlignment;
19020                    try {
19021                        parentResolvedTextAlignment = mParent.getTextAlignment();
19022                    } catch (AbstractMethodError e) {
19023                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19024                                " does not fully implement ViewParent", e);
19025                        parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY;
19026                    }
19027                    switch (parentResolvedTextAlignment) {
19028                        case TEXT_ALIGNMENT_GRAVITY:
19029                        case TEXT_ALIGNMENT_TEXT_START:
19030                        case TEXT_ALIGNMENT_TEXT_END:
19031                        case TEXT_ALIGNMENT_CENTER:
19032                        case TEXT_ALIGNMENT_VIEW_START:
19033                        case TEXT_ALIGNMENT_VIEW_END:
19034                            // Resolved text alignment is the same as the parent resolved
19035                            // text alignment
19036                            mPrivateFlags2 |=
19037                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19038                            break;
19039                        default:
19040                            // Use default resolved text alignment
19041                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19042                    }
19043                    break;
19044                case TEXT_ALIGNMENT_GRAVITY:
19045                case TEXT_ALIGNMENT_TEXT_START:
19046                case TEXT_ALIGNMENT_TEXT_END:
19047                case TEXT_ALIGNMENT_CENTER:
19048                case TEXT_ALIGNMENT_VIEW_START:
19049                case TEXT_ALIGNMENT_VIEW_END:
19050                    // Resolved text alignment is the same as text alignment
19051                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
19052                    break;
19053                default:
19054                    // Use default resolved text alignment
19055                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19056            }
19057        } else {
19058            // Use default resolved text alignment
19059            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19060        }
19061
19062        // Set the resolved
19063        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19064        return true;
19065    }
19066
19067    /**
19068     * Check if text alignment resolution can be done.
19069     *
19070     * @return true if text alignment resolution can be done otherwise return false.
19071     */
19072    public boolean canResolveTextAlignment() {
19073        switch (getRawTextAlignment()) {
19074            case TEXT_DIRECTION_INHERIT:
19075                if (mParent != null) {
19076                    try {
19077                        return mParent.canResolveTextAlignment();
19078                    } catch (AbstractMethodError e) {
19079                        Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
19080                                " does not fully implement ViewParent", e);
19081                    }
19082                }
19083                return false;
19084
19085            default:
19086                return true;
19087        }
19088    }
19089
19090    /**
19091     * Reset resolved text alignment. Text alignment will be resolved during a call to
19092     * {@link #onMeasure(int, int)}.
19093     *
19094     * @hide
19095     */
19096    public void resetResolvedTextAlignment() {
19097        // Reset any previous text alignment resolution
19098        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
19099        // Set to default
19100        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
19101    }
19102
19103    /**
19104     * @return true if text alignment is inherited.
19105     *
19106     * @hide
19107     */
19108    public boolean isTextAlignmentInherited() {
19109        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
19110    }
19111
19112    /**
19113     * @return true if text alignment is resolved.
19114     */
19115    public boolean isTextAlignmentResolved() {
19116        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
19117    }
19118
19119    /**
19120     * Generate a value suitable for use in {@link #setId(int)}.
19121     * This value will not collide with ID values generated at build time by aapt for R.id.
19122     *
19123     * @return a generated ID value
19124     */
19125    public static int generateViewId() {
19126        for (;;) {
19127            final int result = sNextGeneratedId.get();
19128            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
19129            int newValue = result + 1;
19130            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
19131            if (sNextGeneratedId.compareAndSet(result, newValue)) {
19132                return result;
19133            }
19134        }
19135    }
19136
19137    /**
19138     * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions.
19139     * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and
19140     *                           a normal View or a ViewGroup with
19141     *                           {@link android.view.ViewGroup#isTransitionGroup()} true.
19142     * @hide
19143     */
19144    public void captureTransitioningViews(List<View> transitioningViews) {
19145        if (getVisibility() == View.VISIBLE) {
19146            transitioningViews.add(this);
19147        }
19148    }
19149
19150    /**
19151     * Adds all Views that have {@link #getTransitionName()} non-null to namedElements.
19152     * @param namedElements Will contain all Views in the hierarchy having a transitionName.
19153     * @hide
19154     */
19155    public void findNamedViews(Map<String, View> namedElements) {
19156        if (getVisibility() == VISIBLE || mGhostView != null) {
19157            String transitionName = getTransitionName();
19158            if (transitionName != null) {
19159                namedElements.put(transitionName, this);
19160            }
19161        }
19162    }
19163
19164    //
19165    // Properties
19166    //
19167    /**
19168     * A Property wrapper around the <code>alpha</code> functionality handled by the
19169     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
19170     */
19171    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
19172        @Override
19173        public void setValue(View object, float value) {
19174            object.setAlpha(value);
19175        }
19176
19177        @Override
19178        public Float get(View object) {
19179            return object.getAlpha();
19180        }
19181    };
19182
19183    /**
19184     * A Property wrapper around the <code>translationX</code> functionality handled by the
19185     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
19186     */
19187    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
19188        @Override
19189        public void setValue(View object, float value) {
19190            object.setTranslationX(value);
19191        }
19192
19193                @Override
19194        public Float get(View object) {
19195            return object.getTranslationX();
19196        }
19197    };
19198
19199    /**
19200     * A Property wrapper around the <code>translationY</code> functionality handled by the
19201     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
19202     */
19203    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
19204        @Override
19205        public void setValue(View object, float value) {
19206            object.setTranslationY(value);
19207        }
19208
19209        @Override
19210        public Float get(View object) {
19211            return object.getTranslationY();
19212        }
19213    };
19214
19215    /**
19216     * A Property wrapper around the <code>translationZ</code> functionality handled by the
19217     * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods.
19218     */
19219    public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") {
19220        @Override
19221        public void setValue(View object, float value) {
19222            object.setTranslationZ(value);
19223        }
19224
19225        @Override
19226        public Float get(View object) {
19227            return object.getTranslationZ();
19228        }
19229    };
19230
19231    /**
19232     * A Property wrapper around the <code>x</code> functionality handled by the
19233     * {@link View#setX(float)} and {@link View#getX()} methods.
19234     */
19235    public static final Property<View, Float> X = new FloatProperty<View>("x") {
19236        @Override
19237        public void setValue(View object, float value) {
19238            object.setX(value);
19239        }
19240
19241        @Override
19242        public Float get(View object) {
19243            return object.getX();
19244        }
19245    };
19246
19247    /**
19248     * A Property wrapper around the <code>y</code> functionality handled by the
19249     * {@link View#setY(float)} and {@link View#getY()} methods.
19250     */
19251    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
19252        @Override
19253        public void setValue(View object, float value) {
19254            object.setY(value);
19255        }
19256
19257        @Override
19258        public Float get(View object) {
19259            return object.getY();
19260        }
19261    };
19262
19263    /**
19264     * A Property wrapper around the <code>z</code> functionality handled by the
19265     * {@link View#setZ(float)} and {@link View#getZ()} methods.
19266     */
19267    public static final Property<View, Float> Z = new FloatProperty<View>("z") {
19268        @Override
19269        public void setValue(View object, float value) {
19270            object.setZ(value);
19271        }
19272
19273        @Override
19274        public Float get(View object) {
19275            return object.getZ();
19276        }
19277    };
19278
19279    /**
19280     * A Property wrapper around the <code>rotation</code> functionality handled by the
19281     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
19282     */
19283    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
19284        @Override
19285        public void setValue(View object, float value) {
19286            object.setRotation(value);
19287        }
19288
19289        @Override
19290        public Float get(View object) {
19291            return object.getRotation();
19292        }
19293    };
19294
19295    /**
19296     * A Property wrapper around the <code>rotationX</code> functionality handled by the
19297     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
19298     */
19299    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
19300        @Override
19301        public void setValue(View object, float value) {
19302            object.setRotationX(value);
19303        }
19304
19305        @Override
19306        public Float get(View object) {
19307            return object.getRotationX();
19308        }
19309    };
19310
19311    /**
19312     * A Property wrapper around the <code>rotationY</code> functionality handled by the
19313     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
19314     */
19315    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
19316        @Override
19317        public void setValue(View object, float value) {
19318            object.setRotationY(value);
19319        }
19320
19321        @Override
19322        public Float get(View object) {
19323            return object.getRotationY();
19324        }
19325    };
19326
19327    /**
19328     * A Property wrapper around the <code>scaleX</code> functionality handled by the
19329     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
19330     */
19331    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
19332        @Override
19333        public void setValue(View object, float value) {
19334            object.setScaleX(value);
19335        }
19336
19337        @Override
19338        public Float get(View object) {
19339            return object.getScaleX();
19340        }
19341    };
19342
19343    /**
19344     * A Property wrapper around the <code>scaleY</code> functionality handled by the
19345     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
19346     */
19347    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
19348        @Override
19349        public void setValue(View object, float value) {
19350            object.setScaleY(value);
19351        }
19352
19353        @Override
19354        public Float get(View object) {
19355            return object.getScaleY();
19356        }
19357    };
19358
19359    /**
19360     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
19361     * Each MeasureSpec represents a requirement for either the width or the height.
19362     * A MeasureSpec is comprised of a size and a mode. There are three possible
19363     * modes:
19364     * <dl>
19365     * <dt>UNSPECIFIED</dt>
19366     * <dd>
19367     * The parent has not imposed any constraint on the child. It can be whatever size
19368     * it wants.
19369     * </dd>
19370     *
19371     * <dt>EXACTLY</dt>
19372     * <dd>
19373     * The parent has determined an exact size for the child. The child is going to be
19374     * given those bounds regardless of how big it wants to be.
19375     * </dd>
19376     *
19377     * <dt>AT_MOST</dt>
19378     * <dd>
19379     * The child can be as large as it wants up to the specified size.
19380     * </dd>
19381     * </dl>
19382     *
19383     * MeasureSpecs are implemented as ints to reduce object allocation. This class
19384     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
19385     */
19386    public static class MeasureSpec {
19387        private static final int MODE_SHIFT = 30;
19388        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
19389
19390        /**
19391         * Measure specification mode: The parent has not imposed any constraint
19392         * on the child. It can be whatever size it wants.
19393         */
19394        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
19395
19396        /**
19397         * Measure specification mode: The parent has determined an exact size
19398         * for the child. The child is going to be given those bounds regardless
19399         * of how big it wants to be.
19400         */
19401        public static final int EXACTLY     = 1 << MODE_SHIFT;
19402
19403        /**
19404         * Measure specification mode: The child can be as large as it wants up
19405         * to the specified size.
19406         */
19407        public static final int AT_MOST     = 2 << MODE_SHIFT;
19408
19409        /**
19410         * Creates a measure specification based on the supplied size and mode.
19411         *
19412         * The mode must always be one of the following:
19413         * <ul>
19414         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
19415         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
19416         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
19417         * </ul>
19418         *
19419         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
19420         * implementation was such that the order of arguments did not matter
19421         * and overflow in either value could impact the resulting MeasureSpec.
19422         * {@link android.widget.RelativeLayout} was affected by this bug.
19423         * Apps targeting API levels greater than 17 will get the fixed, more strict
19424         * behavior.</p>
19425         *
19426         * @param size the size of the measure specification
19427         * @param mode the mode of the measure specification
19428         * @return the measure specification based on size and mode
19429         */
19430        public static int makeMeasureSpec(int size, int mode) {
19431            if (sUseBrokenMakeMeasureSpec) {
19432                return size + mode;
19433            } else {
19434                return (size & ~MODE_MASK) | (mode & MODE_MASK);
19435            }
19436        }
19437
19438        /**
19439         * Extracts the mode from the supplied measure specification.
19440         *
19441         * @param measureSpec the measure specification to extract the mode from
19442         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
19443         *         {@link android.view.View.MeasureSpec#AT_MOST} or
19444         *         {@link android.view.View.MeasureSpec#EXACTLY}
19445         */
19446        public static int getMode(int measureSpec) {
19447            return (measureSpec & MODE_MASK);
19448        }
19449
19450        /**
19451         * Extracts the size from the supplied measure specification.
19452         *
19453         * @param measureSpec the measure specification to extract the size from
19454         * @return the size in pixels defined in the supplied measure specification
19455         */
19456        public static int getSize(int measureSpec) {
19457            return (measureSpec & ~MODE_MASK);
19458        }
19459
19460        static int adjust(int measureSpec, int delta) {
19461            final int mode = getMode(measureSpec);
19462            if (mode == UNSPECIFIED) {
19463                // No need to adjust size for UNSPECIFIED mode.
19464                return makeMeasureSpec(0, UNSPECIFIED);
19465            }
19466            int size = getSize(measureSpec) + delta;
19467            if (size < 0) {
19468                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
19469                        ") spec: " + toString(measureSpec) + " delta: " + delta);
19470                size = 0;
19471            }
19472            return makeMeasureSpec(size, mode);
19473        }
19474
19475        /**
19476         * Returns a String representation of the specified measure
19477         * specification.
19478         *
19479         * @param measureSpec the measure specification to convert to a String
19480         * @return a String with the following format: "MeasureSpec: MODE SIZE"
19481         */
19482        public static String toString(int measureSpec) {
19483            int mode = getMode(measureSpec);
19484            int size = getSize(measureSpec);
19485
19486            StringBuilder sb = new StringBuilder("MeasureSpec: ");
19487
19488            if (mode == UNSPECIFIED)
19489                sb.append("UNSPECIFIED ");
19490            else if (mode == EXACTLY)
19491                sb.append("EXACTLY ");
19492            else if (mode == AT_MOST)
19493                sb.append("AT_MOST ");
19494            else
19495                sb.append(mode).append(" ");
19496
19497            sb.append(size);
19498            return sb.toString();
19499        }
19500    }
19501
19502    private final class CheckForLongPress implements Runnable {
19503        private int mOriginalWindowAttachCount;
19504
19505        @Override
19506        public void run() {
19507            if (isPressed() && (mParent != null)
19508                    && mOriginalWindowAttachCount == mWindowAttachCount) {
19509                if (performLongClick()) {
19510                    mHasPerformedLongPress = true;
19511                }
19512            }
19513        }
19514
19515        public void rememberWindowAttachCount() {
19516            mOriginalWindowAttachCount = mWindowAttachCount;
19517        }
19518    }
19519
19520    private final class CheckForTap implements Runnable {
19521        public float x;
19522        public float y;
19523
19524        @Override
19525        public void run() {
19526            mPrivateFlags &= ~PFLAG_PREPRESSED;
19527            setPressed(true, x, y);
19528            checkForLongClick(ViewConfiguration.getTapTimeout());
19529        }
19530    }
19531
19532    private final class PerformClick implements Runnable {
19533        @Override
19534        public void run() {
19535            performClick();
19536        }
19537    }
19538
19539    /** @hide */
19540    public void hackTurnOffWindowResizeAnim(boolean off) {
19541        mAttachInfo.mTurnOffWindowResizeAnim = off;
19542    }
19543
19544    /**
19545     * This method returns a ViewPropertyAnimator object, which can be used to animate
19546     * specific properties on this View.
19547     *
19548     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
19549     */
19550    public ViewPropertyAnimator animate() {
19551        if (mAnimator == null) {
19552            mAnimator = new ViewPropertyAnimator(this);
19553        }
19554        return mAnimator;
19555    }
19556
19557    /**
19558     * Sets the name of the View to be used to identify Views in Transitions.
19559     * Names should be unique in the View hierarchy.
19560     *
19561     * @param transitionName The name of the View to uniquely identify it for Transitions.
19562     */
19563    public final void setTransitionName(String transitionName) {
19564        mTransitionName = transitionName;
19565    }
19566
19567    /**
19568     * Returns the name of the View to be used to identify Views in Transitions.
19569     * Names should be unique in the View hierarchy.
19570     *
19571     * <p>This returns null if the View has not been given a name.</p>
19572     *
19573     * @return The name used of the View to be used to identify Views in Transitions or null
19574     * if no name has been given.
19575     */
19576    @ViewDebug.ExportedProperty
19577    public String getTransitionName() {
19578        return mTransitionName;
19579    }
19580
19581    /**
19582     * Interface definition for a callback to be invoked when a hardware key event is
19583     * dispatched to this view. The callback will be invoked before the key event is
19584     * given to the view. This is only useful for hardware keyboards; a software input
19585     * method has no obligation to trigger this listener.
19586     */
19587    public interface OnKeyListener {
19588        /**
19589         * Called when a hardware key is dispatched to a view. This allows listeners to
19590         * get a chance to respond before the target view.
19591         * <p>Key presses in software keyboards will generally NOT trigger this method,
19592         * although some may elect to do so in some situations. Do not assume a
19593         * software input method has to be key-based; even if it is, it may use key presses
19594         * in a different way than you expect, so there is no way to reliably catch soft
19595         * input key presses.
19596         *
19597         * @param v The view the key has been dispatched to.
19598         * @param keyCode The code for the physical key that was pressed
19599         * @param event The KeyEvent object containing full information about
19600         *        the event.
19601         * @return True if the listener has consumed the event, false otherwise.
19602         */
19603        boolean onKey(View v, int keyCode, KeyEvent event);
19604    }
19605
19606    /**
19607     * Interface definition for a callback to be invoked when a touch event is
19608     * dispatched to this view. The callback will be invoked before the touch
19609     * event is given to the view.
19610     */
19611    public interface OnTouchListener {
19612        /**
19613         * Called when a touch event is dispatched to a view. This allows listeners to
19614         * get a chance to respond before the target view.
19615         *
19616         * @param v The view the touch event has been dispatched to.
19617         * @param event The MotionEvent object containing full information about
19618         *        the event.
19619         * @return True if the listener has consumed the event, false otherwise.
19620         */
19621        boolean onTouch(View v, MotionEvent event);
19622    }
19623
19624    /**
19625     * Interface definition for a callback to be invoked when a hover event is
19626     * dispatched to this view. The callback will be invoked before the hover
19627     * event is given to the view.
19628     */
19629    public interface OnHoverListener {
19630        /**
19631         * Called when a hover event is dispatched to a view. This allows listeners to
19632         * get a chance to respond before the target view.
19633         *
19634         * @param v The view the hover event has been dispatched to.
19635         * @param event The MotionEvent object containing full information about
19636         *        the event.
19637         * @return True if the listener has consumed the event, false otherwise.
19638         */
19639        boolean onHover(View v, MotionEvent event);
19640    }
19641
19642    /**
19643     * Interface definition for a callback to be invoked when a generic motion event is
19644     * dispatched to this view. The callback will be invoked before the generic motion
19645     * event is given to the view.
19646     */
19647    public interface OnGenericMotionListener {
19648        /**
19649         * Called when a generic motion event is dispatched to a view. This allows listeners to
19650         * get a chance to respond before the target view.
19651         *
19652         * @param v The view the generic motion event has been dispatched to.
19653         * @param event The MotionEvent object containing full information about
19654         *        the event.
19655         * @return True if the listener has consumed the event, false otherwise.
19656         */
19657        boolean onGenericMotion(View v, MotionEvent event);
19658    }
19659
19660    /**
19661     * Interface definition for a callback to be invoked when a view has been clicked and held.
19662     */
19663    public interface OnLongClickListener {
19664        /**
19665         * Called when a view has been clicked and held.
19666         *
19667         * @param v The view that was clicked and held.
19668         *
19669         * @return true if the callback consumed the long click, false otherwise.
19670         */
19671        boolean onLongClick(View v);
19672    }
19673
19674    /**
19675     * Interface definition for a callback to be invoked when a drag is being dispatched
19676     * to this view.  The callback will be invoked before the hosting view's own
19677     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
19678     * onDrag(event) behavior, it should return 'false' from this callback.
19679     *
19680     * <div class="special reference">
19681     * <h3>Developer Guides</h3>
19682     * <p>For a guide to implementing drag and drop features, read the
19683     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
19684     * </div>
19685     */
19686    public interface OnDragListener {
19687        /**
19688         * Called when a drag event is dispatched to a view. This allows listeners
19689         * to get a chance to override base View behavior.
19690         *
19691         * @param v The View that received the drag event.
19692         * @param event The {@link android.view.DragEvent} object for the drag event.
19693         * @return {@code true} if the drag event was handled successfully, or {@code false}
19694         * if the drag event was not handled. Note that {@code false} will trigger the View
19695         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
19696         */
19697        boolean onDrag(View v, DragEvent event);
19698    }
19699
19700    /**
19701     * Interface definition for a callback to be invoked when the focus state of
19702     * a view changed.
19703     */
19704    public interface OnFocusChangeListener {
19705        /**
19706         * Called when the focus state of a view has changed.
19707         *
19708         * @param v The view whose state has changed.
19709         * @param hasFocus The new focus state of v.
19710         */
19711        void onFocusChange(View v, boolean hasFocus);
19712    }
19713
19714    /**
19715     * Interface definition for a callback to be invoked when a view is clicked.
19716     */
19717    public interface OnClickListener {
19718        /**
19719         * Called when a view has been clicked.
19720         *
19721         * @param v The view that was clicked.
19722         */
19723        void onClick(View v);
19724    }
19725
19726    /**
19727     * Interface definition for a callback to be invoked when the context menu
19728     * for this view is being built.
19729     */
19730    public interface OnCreateContextMenuListener {
19731        /**
19732         * Called when the context menu for this view is being built. It is not
19733         * safe to hold onto the menu after this method returns.
19734         *
19735         * @param menu The context menu that is being built
19736         * @param v The view for which the context menu is being built
19737         * @param menuInfo Extra information about the item for which the
19738         *            context menu should be shown. This information will vary
19739         *            depending on the class of v.
19740         */
19741        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
19742    }
19743
19744    /**
19745     * Interface definition for a callback to be invoked when the status bar changes
19746     * visibility.  This reports <strong>global</strong> changes to the system UI
19747     * state, not what the application is requesting.
19748     *
19749     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
19750     */
19751    public interface OnSystemUiVisibilityChangeListener {
19752        /**
19753         * Called when the status bar changes visibility because of a call to
19754         * {@link View#setSystemUiVisibility(int)}.
19755         *
19756         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
19757         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
19758         * This tells you the <strong>global</strong> state of these UI visibility
19759         * flags, not what your app is currently applying.
19760         */
19761        public void onSystemUiVisibilityChange(int visibility);
19762    }
19763
19764    /**
19765     * Interface definition for a callback to be invoked when this view is attached
19766     * or detached from its window.
19767     */
19768    public interface OnAttachStateChangeListener {
19769        /**
19770         * Called when the view is attached to a window.
19771         * @param v The view that was attached
19772         */
19773        public void onViewAttachedToWindow(View v);
19774        /**
19775         * Called when the view is detached from a window.
19776         * @param v The view that was detached
19777         */
19778        public void onViewDetachedFromWindow(View v);
19779    }
19780
19781    /**
19782     * Listener for applying window insets on a view in a custom way.
19783     *
19784     * <p>Apps may choose to implement this interface if they want to apply custom policy
19785     * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener
19786     * is set, its
19787     * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets}
19788     * method will be called instead of the View's own
19789     * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener
19790     * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply
19791     * the View's normal behavior as part of its own.</p>
19792     */
19793    public interface OnApplyWindowInsetsListener {
19794        /**
19795         * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set}
19796         * on a View, this listener method will be called instead of the view's own
19797         * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method.
19798         *
19799         * @param v The view applying window insets
19800         * @param insets The insets to apply
19801         * @return The insets supplied, minus any insets that were consumed
19802         */
19803        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets);
19804    }
19805
19806    private final class UnsetPressedState implements Runnable {
19807        @Override
19808        public void run() {
19809            setPressed(false);
19810        }
19811    }
19812
19813    /**
19814     * Base class for derived classes that want to save and restore their own
19815     * state in {@link android.view.View#onSaveInstanceState()}.
19816     */
19817    public static class BaseSavedState extends AbsSavedState {
19818        /**
19819         * Constructor used when reading from a parcel. Reads the state of the superclass.
19820         *
19821         * @param source
19822         */
19823        public BaseSavedState(Parcel source) {
19824            super(source);
19825        }
19826
19827        /**
19828         * Constructor called by derived classes when creating their SavedState objects
19829         *
19830         * @param superState The state of the superclass of this view
19831         */
19832        public BaseSavedState(Parcelable superState) {
19833            super(superState);
19834        }
19835
19836        public static final Parcelable.Creator<BaseSavedState> CREATOR =
19837                new Parcelable.Creator<BaseSavedState>() {
19838            public BaseSavedState createFromParcel(Parcel in) {
19839                return new BaseSavedState(in);
19840            }
19841
19842            public BaseSavedState[] newArray(int size) {
19843                return new BaseSavedState[size];
19844            }
19845        };
19846    }
19847
19848    /**
19849     * A set of information given to a view when it is attached to its parent
19850     * window.
19851     */
19852    final static class AttachInfo {
19853        interface Callbacks {
19854            void playSoundEffect(int effectId);
19855            boolean performHapticFeedback(int effectId, boolean always);
19856        }
19857
19858        /**
19859         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
19860         * to a Handler. This class contains the target (View) to invalidate and
19861         * the coordinates of the dirty rectangle.
19862         *
19863         * For performance purposes, this class also implements a pool of up to
19864         * POOL_LIMIT objects that get reused. This reduces memory allocations
19865         * whenever possible.
19866         */
19867        static class InvalidateInfo {
19868            private static final int POOL_LIMIT = 10;
19869
19870            private static final SynchronizedPool<InvalidateInfo> sPool =
19871                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
19872
19873            View target;
19874
19875            int left;
19876            int top;
19877            int right;
19878            int bottom;
19879
19880            public static InvalidateInfo obtain() {
19881                InvalidateInfo instance = sPool.acquire();
19882                return (instance != null) ? instance : new InvalidateInfo();
19883            }
19884
19885            public void recycle() {
19886                target = null;
19887                sPool.release(this);
19888            }
19889        }
19890
19891        final IWindowSession mSession;
19892
19893        final IWindow mWindow;
19894
19895        final IBinder mWindowToken;
19896
19897        final Display mDisplay;
19898
19899        final Callbacks mRootCallbacks;
19900
19901        IWindowId mIWindowId;
19902        WindowId mWindowId;
19903
19904        /**
19905         * The top view of the hierarchy.
19906         */
19907        View mRootView;
19908
19909        IBinder mPanelParentWindowToken;
19910
19911        boolean mHardwareAccelerated;
19912        boolean mHardwareAccelerationRequested;
19913        HardwareRenderer mHardwareRenderer;
19914
19915        /**
19916         * The state of the display to which the window is attached, as reported
19917         * by {@link Display#getState()}.  Note that the display state constants
19918         * declared by {@link Display} do not exactly line up with the screen state
19919         * constants declared by {@link View} (there are more display states than
19920         * screen states).
19921         */
19922        int mDisplayState = Display.STATE_UNKNOWN;
19923
19924        /**
19925         * Scale factor used by the compatibility mode
19926         */
19927        float mApplicationScale;
19928
19929        /**
19930         * Indicates whether the application is in compatibility mode
19931         */
19932        boolean mScalingRequired;
19933
19934        /**
19935         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
19936         */
19937        boolean mTurnOffWindowResizeAnim;
19938
19939        /**
19940         * Left position of this view's window
19941         */
19942        int mWindowLeft;
19943
19944        /**
19945         * Top position of this view's window
19946         */
19947        int mWindowTop;
19948
19949        /**
19950         * Indicates whether views need to use 32-bit drawing caches
19951         */
19952        boolean mUse32BitDrawingCache;
19953
19954        /**
19955         * For windows that are full-screen but using insets to layout inside
19956         * of the screen areas, these are the current insets to appear inside
19957         * the overscan area of the display.
19958         */
19959        final Rect mOverscanInsets = new Rect();
19960
19961        /**
19962         * For windows that are full-screen but using insets to layout inside
19963         * of the screen decorations, these are the current insets for the
19964         * content of the window.
19965         */
19966        final Rect mContentInsets = new Rect();
19967
19968        /**
19969         * For windows that are full-screen but using insets to layout inside
19970         * of the screen decorations, these are the current insets for the
19971         * actual visible parts of the window.
19972         */
19973        final Rect mVisibleInsets = new Rect();
19974
19975        /**
19976         * For windows that are full-screen but using insets to layout inside
19977         * of the screen decorations, these are the current insets for the
19978         * stable system windows.
19979         */
19980        final Rect mStableInsets = new Rect();
19981
19982        /**
19983         * The internal insets given by this window.  This value is
19984         * supplied by the client (through
19985         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
19986         * be given to the window manager when changed to be used in laying
19987         * out windows behind it.
19988         */
19989        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
19990                = new ViewTreeObserver.InternalInsetsInfo();
19991
19992        /**
19993         * Set to true when mGivenInternalInsets is non-empty.
19994         */
19995        boolean mHasNonEmptyGivenInternalInsets;
19996
19997        /**
19998         * All views in the window's hierarchy that serve as scroll containers,
19999         * used to determine if the window can be resized or must be panned
20000         * to adjust for a soft input area.
20001         */
20002        final ArrayList<View> mScrollContainers = new ArrayList<View>();
20003
20004        final KeyEvent.DispatcherState mKeyDispatchState
20005                = new KeyEvent.DispatcherState();
20006
20007        /**
20008         * Indicates whether the view's window currently has the focus.
20009         */
20010        boolean mHasWindowFocus;
20011
20012        /**
20013         * The current visibility of the window.
20014         */
20015        int mWindowVisibility;
20016
20017        /**
20018         * Indicates the time at which drawing started to occur.
20019         */
20020        long mDrawingTime;
20021
20022        /**
20023         * Indicates whether or not ignoring the DIRTY_MASK flags.
20024         */
20025        boolean mIgnoreDirtyState;
20026
20027        /**
20028         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
20029         * to avoid clearing that flag prematurely.
20030         */
20031        boolean mSetIgnoreDirtyState = false;
20032
20033        /**
20034         * Indicates whether the view's window is currently in touch mode.
20035         */
20036        boolean mInTouchMode;
20037
20038        /**
20039         * Indicates whether the view has requested unbuffered input dispatching for the current
20040         * event stream.
20041         */
20042        boolean mUnbufferedDispatchRequested;
20043
20044        /**
20045         * Indicates that ViewAncestor should trigger a global layout change
20046         * the next time it performs a traversal
20047         */
20048        boolean mRecomputeGlobalAttributes;
20049
20050        /**
20051         * Always report new attributes at next traversal.
20052         */
20053        boolean mForceReportNewAttributes;
20054
20055        /**
20056         * Set during a traveral if any views want to keep the screen on.
20057         */
20058        boolean mKeepScreenOn;
20059
20060        /**
20061         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
20062         */
20063        int mSystemUiVisibility;
20064
20065        /**
20066         * Hack to force certain system UI visibility flags to be cleared.
20067         */
20068        int mDisabledSystemUiVisibility;
20069
20070        /**
20071         * Last global system UI visibility reported by the window manager.
20072         */
20073        int mGlobalSystemUiVisibility;
20074
20075        /**
20076         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
20077         * attached.
20078         */
20079        boolean mHasSystemUiListeners;
20080
20081        /**
20082         * Set if the window has requested to extend into the overscan region
20083         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
20084         */
20085        boolean mOverscanRequested;
20086
20087        /**
20088         * Set if the visibility of any views has changed.
20089         */
20090        boolean mViewVisibilityChanged;
20091
20092        /**
20093         * Set to true if a view has been scrolled.
20094         */
20095        boolean mViewScrollChanged;
20096
20097        /**
20098         * Set to true if high contrast mode enabled
20099         */
20100        boolean mHighContrastText;
20101
20102        /**
20103         * Global to the view hierarchy used as a temporary for dealing with
20104         * x/y points in the transparent region computations.
20105         */
20106        final int[] mTransparentLocation = new int[2];
20107
20108        /**
20109         * Global to the view hierarchy used as a temporary for dealing with
20110         * x/y points in the ViewGroup.invalidateChild implementation.
20111         */
20112        final int[] mInvalidateChildLocation = new int[2];
20113
20114        /**
20115         * Global to the view hierarchy used as a temporary for dealng with
20116         * computing absolute on-screen location.
20117         */
20118        final int[] mTmpLocation = new int[2];
20119
20120        /**
20121         * Global to the view hierarchy used as a temporary for dealing with
20122         * x/y location when view is transformed.
20123         */
20124        final float[] mTmpTransformLocation = new float[2];
20125
20126        /**
20127         * The view tree observer used to dispatch global events like
20128         * layout, pre-draw, touch mode change, etc.
20129         */
20130        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
20131
20132        /**
20133         * A Canvas used by the view hierarchy to perform bitmap caching.
20134         */
20135        Canvas mCanvas;
20136
20137        /**
20138         * The view root impl.
20139         */
20140        final ViewRootImpl mViewRootImpl;
20141
20142        /**
20143         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
20144         * handler can be used to pump events in the UI events queue.
20145         */
20146        final Handler mHandler;
20147
20148        /**
20149         * Temporary for use in computing invalidate rectangles while
20150         * calling up the hierarchy.
20151         */
20152        final Rect mTmpInvalRect = new Rect();
20153
20154        /**
20155         * Temporary for use in computing hit areas with transformed views
20156         */
20157        final RectF mTmpTransformRect = new RectF();
20158
20159        /**
20160         * Temporary for use in transforming invalidation rect
20161         */
20162        final Matrix mTmpMatrix = new Matrix();
20163
20164        /**
20165         * Temporary for use in transforming invalidation rect
20166         */
20167        final Transformation mTmpTransformation = new Transformation();
20168
20169        /**
20170         * Temporary for use in querying outlines from OutlineProviders
20171         */
20172        final Outline mTmpOutline = new Outline();
20173
20174        /**
20175         * Temporary list for use in collecting focusable descendents of a view.
20176         */
20177        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
20178
20179        /**
20180         * The id of the window for accessibility purposes.
20181         */
20182        int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
20183
20184        /**
20185         * Flags related to accessibility processing.
20186         *
20187         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
20188         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
20189         */
20190        int mAccessibilityFetchFlags;
20191
20192        /**
20193         * The drawable for highlighting accessibility focus.
20194         */
20195        Drawable mAccessibilityFocusDrawable;
20196
20197        /**
20198         * Show where the margins, bounds and layout bounds are for each view.
20199         */
20200        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
20201
20202        /**
20203         * Point used to compute visible regions.
20204         */
20205        final Point mPoint = new Point();
20206
20207        /**
20208         * Used to track which View originated a requestLayout() call, used when
20209         * requestLayout() is called during layout.
20210         */
20211        View mViewRequestingLayout;
20212
20213        /**
20214         * Creates a new set of attachment information with the specified
20215         * events handler and thread.
20216         *
20217         * @param handler the events handler the view must use
20218         */
20219        AttachInfo(IWindowSession session, IWindow window, Display display,
20220                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
20221            mSession = session;
20222            mWindow = window;
20223            mWindowToken = window.asBinder();
20224            mDisplay = display;
20225            mViewRootImpl = viewRootImpl;
20226            mHandler = handler;
20227            mRootCallbacks = effectPlayer;
20228        }
20229    }
20230
20231    /**
20232     * <p>ScrollabilityCache holds various fields used by a View when scrolling
20233     * is supported. This avoids keeping too many unused fields in most
20234     * instances of View.</p>
20235     */
20236    private static class ScrollabilityCache implements Runnable {
20237
20238        /**
20239         * Scrollbars are not visible
20240         */
20241        public static final int OFF = 0;
20242
20243        /**
20244         * Scrollbars are visible
20245         */
20246        public static final int ON = 1;
20247
20248        /**
20249         * Scrollbars are fading away
20250         */
20251        public static final int FADING = 2;
20252
20253        public boolean fadeScrollBars;
20254
20255        public int fadingEdgeLength;
20256        public int scrollBarDefaultDelayBeforeFade;
20257        public int scrollBarFadeDuration;
20258
20259        public int scrollBarSize;
20260        public ScrollBarDrawable scrollBar;
20261        public float[] interpolatorValues;
20262        public View host;
20263
20264        public final Paint paint;
20265        public final Matrix matrix;
20266        public Shader shader;
20267
20268        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
20269
20270        private static final float[] OPAQUE = { 255 };
20271        private static final float[] TRANSPARENT = { 0.0f };
20272
20273        /**
20274         * When fading should start. This time moves into the future every time
20275         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
20276         */
20277        public long fadeStartTime;
20278
20279
20280        /**
20281         * The current state of the scrollbars: ON, OFF, or FADING
20282         */
20283        public int state = OFF;
20284
20285        private int mLastColor;
20286
20287        public ScrollabilityCache(ViewConfiguration configuration, View host) {
20288            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
20289            scrollBarSize = configuration.getScaledScrollBarSize();
20290            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
20291            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
20292
20293            paint = new Paint();
20294            matrix = new Matrix();
20295            // use use a height of 1, and then wack the matrix each time we
20296            // actually use it.
20297            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20298            paint.setShader(shader);
20299            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20300
20301            this.host = host;
20302        }
20303
20304        public void setFadeColor(int color) {
20305            if (color != mLastColor) {
20306                mLastColor = color;
20307
20308                if (color != 0) {
20309                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
20310                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
20311                    paint.setShader(shader);
20312                    // Restore the default transfer mode (src_over)
20313                    paint.setXfermode(null);
20314                } else {
20315                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
20316                    paint.setShader(shader);
20317                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
20318                }
20319            }
20320        }
20321
20322        public void run() {
20323            long now = AnimationUtils.currentAnimationTimeMillis();
20324            if (now >= fadeStartTime) {
20325
20326                // the animation fades the scrollbars out by changing
20327                // the opacity (alpha) from fully opaque to fully
20328                // transparent
20329                int nextFrame = (int) now;
20330                int framesCount = 0;
20331
20332                Interpolator interpolator = scrollBarInterpolator;
20333
20334                // Start opaque
20335                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
20336
20337                // End transparent
20338                nextFrame += scrollBarFadeDuration;
20339                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
20340
20341                state = FADING;
20342
20343                // Kick off the fade animation
20344                host.invalidate(true);
20345            }
20346        }
20347    }
20348
20349    /**
20350     * Resuable callback for sending
20351     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
20352     */
20353    private class SendViewScrolledAccessibilityEvent implements Runnable {
20354        public volatile boolean mIsPending;
20355
20356        public void run() {
20357            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
20358            mIsPending = false;
20359        }
20360    }
20361
20362    /**
20363     * <p>
20364     * This class represents a delegate that can be registered in a {@link View}
20365     * to enhance accessibility support via composition rather via inheritance.
20366     * It is specifically targeted to widget developers that extend basic View
20367     * classes i.e. classes in package android.view, that would like their
20368     * applications to be backwards compatible.
20369     * </p>
20370     * <div class="special reference">
20371     * <h3>Developer Guides</h3>
20372     * <p>For more information about making applications accessible, read the
20373     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
20374     * developer guide.</p>
20375     * </div>
20376     * <p>
20377     * A scenario in which a developer would like to use an accessibility delegate
20378     * is overriding a method introduced in a later API version then the minimal API
20379     * version supported by the application. For example, the method
20380     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
20381     * in API version 4 when the accessibility APIs were first introduced. If a
20382     * developer would like his application to run on API version 4 devices (assuming
20383     * all other APIs used by the application are version 4 or lower) and take advantage
20384     * of this method, instead of overriding the method which would break the application's
20385     * backwards compatibility, he can override the corresponding method in this
20386     * delegate and register the delegate in the target View if the API version of
20387     * the system is high enough i.e. the API version is same or higher to the API
20388     * version that introduced
20389     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
20390     * </p>
20391     * <p>
20392     * Here is an example implementation:
20393     * </p>
20394     * <code><pre><p>
20395     * if (Build.VERSION.SDK_INT >= 14) {
20396     *     // If the API version is equal of higher than the version in
20397     *     // which onInitializeAccessibilityNodeInfo was introduced we
20398     *     // register a delegate with a customized implementation.
20399     *     View view = findViewById(R.id.view_id);
20400     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
20401     *         public void onInitializeAccessibilityNodeInfo(View host,
20402     *                 AccessibilityNodeInfo info) {
20403     *             // Let the default implementation populate the info.
20404     *             super.onInitializeAccessibilityNodeInfo(host, info);
20405     *             // Set some other information.
20406     *             info.setEnabled(host.isEnabled());
20407     *         }
20408     *     });
20409     * }
20410     * </code></pre></p>
20411     * <p>
20412     * This delegate contains methods that correspond to the accessibility methods
20413     * in View. If a delegate has been specified the implementation in View hands
20414     * off handling to the corresponding method in this delegate. The default
20415     * implementation the delegate methods behaves exactly as the corresponding
20416     * method in View for the case of no accessibility delegate been set. Hence,
20417     * to customize the behavior of a View method, clients can override only the
20418     * corresponding delegate method without altering the behavior of the rest
20419     * accessibility related methods of the host view.
20420     * </p>
20421     */
20422    public static class AccessibilityDelegate {
20423
20424        /**
20425         * Sends an accessibility event of the given type. If accessibility is not
20426         * enabled this method has no effect.
20427         * <p>
20428         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
20429         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
20430         * been set.
20431         * </p>
20432         *
20433         * @param host The View hosting the delegate.
20434         * @param eventType The type of the event to send.
20435         *
20436         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
20437         */
20438        public void sendAccessibilityEvent(View host, int eventType) {
20439            host.sendAccessibilityEventInternal(eventType);
20440        }
20441
20442        /**
20443         * Performs the specified accessibility action on the view. For
20444         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
20445         * <p>
20446         * The default implementation behaves as
20447         * {@link View#performAccessibilityAction(int, Bundle)
20448         *  View#performAccessibilityAction(int, Bundle)} for the case of
20449         *  no accessibility delegate been set.
20450         * </p>
20451         *
20452         * @param action The action to perform.
20453         * @return Whether the action was performed.
20454         *
20455         * @see View#performAccessibilityAction(int, Bundle)
20456         *      View#performAccessibilityAction(int, Bundle)
20457         */
20458        public boolean performAccessibilityAction(View host, int action, Bundle args) {
20459            return host.performAccessibilityActionInternal(action, args);
20460        }
20461
20462        /**
20463         * Sends an accessibility event. This method behaves exactly as
20464         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
20465         * empty {@link AccessibilityEvent} and does not perform a check whether
20466         * accessibility is enabled.
20467         * <p>
20468         * The default implementation behaves as
20469         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20470         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
20471         * the case of no accessibility delegate been set.
20472         * </p>
20473         *
20474         * @param host The View hosting the delegate.
20475         * @param event The event to send.
20476         *
20477         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20478         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
20479         */
20480        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
20481            host.sendAccessibilityEventUncheckedInternal(event);
20482        }
20483
20484        /**
20485         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
20486         * to its children for adding their text content to the event.
20487         * <p>
20488         * The default implementation behaves as
20489         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20490         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
20491         * the case of no accessibility delegate been set.
20492         * </p>
20493         *
20494         * @param host The View hosting the delegate.
20495         * @param event The event.
20496         * @return True if the event population was completed.
20497         *
20498         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20499         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
20500         */
20501        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20502            return host.dispatchPopulateAccessibilityEventInternal(event);
20503        }
20504
20505        /**
20506         * Gives a chance to the host View to populate the accessibility event with its
20507         * text content.
20508         * <p>
20509         * The default implementation behaves as
20510         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
20511         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
20512         * the case of no accessibility delegate been set.
20513         * </p>
20514         *
20515         * @param host The View hosting the delegate.
20516         * @param event The accessibility event which to populate.
20517         *
20518         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
20519         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
20520         */
20521        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
20522            host.onPopulateAccessibilityEventInternal(event);
20523        }
20524
20525        /**
20526         * Initializes an {@link AccessibilityEvent} with information about the
20527         * the host View which is the event source.
20528         * <p>
20529         * The default implementation behaves as
20530         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
20531         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
20532         * the case of no accessibility delegate been set.
20533         * </p>
20534         *
20535         * @param host The View hosting the delegate.
20536         * @param event The event to initialize.
20537         *
20538         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
20539         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
20540         */
20541        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
20542            host.onInitializeAccessibilityEventInternal(event);
20543        }
20544
20545        /**
20546         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
20547         * <p>
20548         * The default implementation behaves as
20549         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20550         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
20551         * the case of no accessibility delegate been set.
20552         * </p>
20553         *
20554         * @param host The View hosting the delegate.
20555         * @param info The instance to initialize.
20556         *
20557         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20558         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
20559         */
20560        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
20561            host.onInitializeAccessibilityNodeInfoInternal(info);
20562        }
20563
20564        /**
20565         * Called when a child of the host View has requested sending an
20566         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
20567         * to augment the event.
20568         * <p>
20569         * The default implementation behaves as
20570         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20571         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
20572         * the case of no accessibility delegate been set.
20573         * </p>
20574         *
20575         * @param host The View hosting the delegate.
20576         * @param child The child which requests sending the event.
20577         * @param event The event to be sent.
20578         * @return True if the event should be sent
20579         *
20580         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20581         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
20582         */
20583        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
20584                AccessibilityEvent event) {
20585            return host.onRequestSendAccessibilityEventInternal(child, event);
20586        }
20587
20588        /**
20589         * Gets the provider for managing a virtual view hierarchy rooted at this View
20590         * and reported to {@link android.accessibilityservice.AccessibilityService}s
20591         * that explore the window content.
20592         * <p>
20593         * The default implementation behaves as
20594         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
20595         * the case of no accessibility delegate been set.
20596         * </p>
20597         *
20598         * @return The provider.
20599         *
20600         * @see AccessibilityNodeProvider
20601         */
20602        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
20603            return null;
20604        }
20605
20606        /**
20607         * Returns an {@link AccessibilityNodeInfo} representing the host view from the
20608         * point of view of an {@link android.accessibilityservice.AccessibilityService}.
20609         * This method is responsible for obtaining an accessibility node info from a
20610         * pool of reusable instances and calling
20611         * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host
20612         * view to initialize the former.
20613         * <p>
20614         * <strong>Note:</strong> The client is responsible for recycling the obtained
20615         * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object
20616         * creation.
20617         * </p>
20618         * <p>
20619         * The default implementation behaves as
20620         * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for
20621         * the case of no accessibility delegate been set.
20622         * </p>
20623         * @return A populated {@link AccessibilityNodeInfo}.
20624         *
20625         * @see AccessibilityNodeInfo
20626         *
20627         * @hide
20628         */
20629        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
20630            return host.createAccessibilityNodeInfoInternal();
20631        }
20632    }
20633
20634    private class MatchIdPredicate implements Predicate<View> {
20635        public int mId;
20636
20637        @Override
20638        public boolean apply(View view) {
20639            return (view.mID == mId);
20640        }
20641    }
20642
20643    private class MatchLabelForPredicate implements Predicate<View> {
20644        private int mLabeledId;
20645
20646        @Override
20647        public boolean apply(View view) {
20648            return (view.mLabelForId == mLabeledId);
20649        }
20650    }
20651
20652    private class SendViewStateChangedAccessibilityEvent implements Runnable {
20653        private int mChangeTypes = 0;
20654        private boolean mPosted;
20655        private boolean mPostedWithDelay;
20656        private long mLastEventTimeMillis;
20657
20658        @Override
20659        public void run() {
20660            mPosted = false;
20661            mPostedWithDelay = false;
20662            mLastEventTimeMillis = SystemClock.uptimeMillis();
20663            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
20664                final AccessibilityEvent event = AccessibilityEvent.obtain();
20665                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
20666                event.setContentChangeTypes(mChangeTypes);
20667                sendAccessibilityEventUnchecked(event);
20668            }
20669            mChangeTypes = 0;
20670        }
20671
20672        public void runOrPost(int changeType) {
20673            mChangeTypes |= changeType;
20674
20675            // If this is a live region or the child of a live region, collect
20676            // all events from this frame and send them on the next frame.
20677            if (inLiveRegion()) {
20678                // If we're already posted with a delay, remove that.
20679                if (mPostedWithDelay) {
20680                    removeCallbacks(this);
20681                    mPostedWithDelay = false;
20682                }
20683                // Only post if we're not already posted.
20684                if (!mPosted) {
20685                    post(this);
20686                    mPosted = true;
20687                }
20688                return;
20689            }
20690
20691            if (mPosted) {
20692                return;
20693            }
20694            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
20695            final long minEventIntevalMillis =
20696                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
20697            if (timeSinceLastMillis >= minEventIntevalMillis) {
20698                removeCallbacks(this);
20699                run();
20700            } else {
20701                postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
20702                mPosted = true;
20703                mPostedWithDelay = true;
20704            }
20705        }
20706    }
20707
20708    private boolean inLiveRegion() {
20709        if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20710            return true;
20711        }
20712
20713        ViewParent parent = getParent();
20714        while (parent instanceof View) {
20715            if (((View) parent).getAccessibilityLiveRegion()
20716                    != View.ACCESSIBILITY_LIVE_REGION_NONE) {
20717                return true;
20718            }
20719            parent = parent.getParent();
20720        }
20721
20722        return false;
20723    }
20724
20725    /**
20726     * Dump all private flags in readable format, useful for documentation and
20727     * sanity checking.
20728     */
20729    private static void dumpFlags() {
20730        final HashMap<String, String> found = Maps.newHashMap();
20731        try {
20732            for (Field field : View.class.getDeclaredFields()) {
20733                final int modifiers = field.getModifiers();
20734                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
20735                    if (field.getType().equals(int.class)) {
20736                        final int value = field.getInt(null);
20737                        dumpFlag(found, field.getName(), value);
20738                    } else if (field.getType().equals(int[].class)) {
20739                        final int[] values = (int[]) field.get(null);
20740                        for (int i = 0; i < values.length; i++) {
20741                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
20742                        }
20743                    }
20744                }
20745            }
20746        } catch (IllegalAccessException e) {
20747            throw new RuntimeException(e);
20748        }
20749
20750        final ArrayList<String> keys = Lists.newArrayList();
20751        keys.addAll(found.keySet());
20752        Collections.sort(keys);
20753        for (String key : keys) {
20754            Log.d(VIEW_LOG_TAG, found.get(key));
20755        }
20756    }
20757
20758    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
20759        // Sort flags by prefix, then by bits, always keeping unique keys
20760        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
20761        final int prefix = name.indexOf('_');
20762        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
20763        final String output = bits + " " + name;
20764        found.put(key, output);
20765    }
20766}
20767